summaryrefslogtreecommitdiff
path: root/engine/src/util.rs
blob: f820b64b81a7b0d049958999093398fc449f9761 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use std::fmt::{Debug, Display};

use crate::ecs::util::VecExt;

#[derive(Debug, Clone)]
pub struct MapVec<Key: Ord, Value>
{
    inner: Vec<(Key, Value)>,
}

impl<Key: Ord, Value> MapVec<Key, Value>
{
    pub fn with_capacity(capacity: usize) -> Self
    {
        Self { inner: Vec::with_capacity(capacity) }
    }

    pub fn insert(&mut self, key: Key, value: Value)
    {
        self.inner
            .insert_at_part_pt_by_key((key, value), |(a_key, _)| a_key);
    }

    pub fn insert_mut(&mut self, key: Key, value: Value) -> &mut Value
    {
        let insert_index = self
            .inner
            .partition_point(|(other_key, _other_value)| other_key <= &key);

        &mut self.inner.insert_mut(insert_index, (key, value)).1
    }

    pub fn remove(&mut self, key: Key) -> Option<Value>
    {
        let index = self
            .inner
            .binary_search_by_key(&&key, |(a_key, _)| a_key)
            .ok()?;

        let (_, value) = self.inner.remove(index);

        Some(value)
    }

    pub fn get(&self, key: &Key) -> Option<&Value>
    {
        let index = self
            .inner
            .binary_search_by_key(&key, |(a_key, _)| a_key)
            .ok()?;

        let Some((_, value)) = self.inner.get(index) else {
            unreachable!(); // Reason: Index from binary search cannot be OOB
        };

        Some(value)
    }

    pub fn get_mut(&mut self, key: &Key) -> Option<&mut Value>
    {
        let index = self
            .inner
            .binary_search_by_key(&key, |(a_key, _)| a_key)
            .ok()?;

        let Some((_, value)) = self.inner.get_mut(index) else {
            unreachable!(); // Reason: Index from binary search cannot be OOB
        };

        Some(value)
    }

    pub fn entry(&mut self, key: Key) -> MapVecEntry<'_, Key, Value>
    {
        let index = self
            .inner
            .binary_search_by_key(&&key, |(a_key, _)| a_key)
            .ok();

        MapVecEntry { map: self, key, index }
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&mut Key, &mut Value)>
    {
        self.inner.iter_mut().map(|(key, value)| (key, value))
    }

    pub fn values(&self) -> impl Iterator<Item = &Value>
    {
        self.inner.iter().map(|(_, value)| value)
    }
}

impl<Key: Ord, Value> FromIterator<(Key, Value)> for MapVec<Key, Value>
{
    fn from_iter<Iter: IntoIterator<Item = (Key, Value)>>(iter: Iter) -> Self
    {
        let mut items = iter.into_iter().collect::<Vec<_>>();

        if !items.is_sorted_by_key(|(key, _)| key) {
            items.sort_by(|(key_a, _), (key_b, _)| key_a.cmp(key_b));
        }

        Self { inner: items }
    }
}

impl<Key: Ord, Value> Default for MapVec<Key, Value>
{
    fn default() -> Self
    {
        Self { inner: Vec::new() }
    }
}

pub struct MapVecEntry<'map, Key: Ord, Value>
{
    map: &'map mut MapVec<Key, Value>,
    key: Key,
    index: Option<usize>,
}

impl<'map, Key: Ord, Value> MapVecEntry<'map, Key, Value>
{
    pub fn or_insert_with(self, func: impl FnOnce() -> Value) -> &'map mut Value
    {
        match self.index {
            Some(index) => {
                let (_, value) = unsafe { self.map.inner.get_unchecked_mut(index) };

                value
            }
            None => self.map.insert_mut(self.key, func()),
        }
    }
}

pub trait OptionExt<T>
{
    /// Substitute for the currently experimental function
    /// [`Option::get_or_try_insert_with`].
    /// See https://github.com/rust-lang/rust/issues/143648
    fn get_or_try_insert_with_fn<Err>(
        &mut self,
        func: impl Fn() -> Result<T, Err>,
    ) -> Result<&mut T, Err>;
}

impl<T> OptionExt<T> for Option<T>
{
    fn get_or_try_insert_with_fn<Err>(
        &mut self,
        func: impl FnOnce() -> Result<T, Err>,
    ) -> Result<&mut T, Err>
    {
        if let None = self {
            *self = Some(func()?);
        }

        Ok(unsafe { self.as_mut().unwrap_unchecked() })
    }
}

pub struct DisplaySlice<'a, Item>
{
    slice: &'a [Item],
}

impl<'a, Item> DisplaySlice<'a, Item>
{
    pub fn new(slice: &'a [Item]) -> Self
    {
        Self { slice }
    }
}

impl<Item> Display for DisplaySlice<'_, Item>
where
    Item: Display,
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        let Some(first_item) = self.slice.first() else {
            return formatter.write_str("<empty>");
        };

        write!(formatter, "{first_item}")?;

        if self.slice.len() == 1 {
            return Ok(());
        }

        for item in &self.slice[1..self.slice.len() - 1] {
            write!(formatter, ", {item}")?;
        }

        let Some(last_item) = self.slice.last() else {
            unreachable!();
        };

        write!(formatter, " & {last_item}")?;

        Ok(())
    }
}

#[derive(Debug)]
pub struct BitArray<const SIZE: usize, const BITS_PER_ITEM: usize>
{
    inner: [u8; SIZE],
}

impl<const SIZE: usize, const BITS_PER_ITEM: usize> BitArray<SIZE, BITS_PER_ITEM>
{
    const ITEM_MASK: u8 = !(u8::MAX << BITS_PER_ITEM);

    pub fn new() -> Self
    {
        assert!(BITS_PER_ITEM > 1);
        assert!(BITS_PER_ITEM <= 8);
        assert_eq!(BITS_PER_ITEM % 2, 0);

        Self { inner: [0; SIZE] }
    }

    pub fn get(&self, item_index: usize) -> u8
    {
        let bit_index = item_index * BITS_PER_ITEM;

        let byte_index = bit_index / 8;

        let bit_index_in_byte = bit_index - (byte_index * 8);

        (self.inner[byte_index] >> (bit_index_in_byte)) & Self::ITEM_MASK
    }

    #[tracing::instrument(skip_all)]
    pub fn set(&mut self, item_index: usize, item_bits: u8)
    {
        let item_bits = item_bits & Self::ITEM_MASK;

        let bit_index = item_index * BITS_PER_ITEM;

        let byte_index = bit_index / 8;

        let bit_index_in_byte = bit_index - (byte_index * 8);

        tracing::trace!(
            item_bits,
            bit_index,
            byte_index,
            bit_index_in_byte,
            "Setting item bits"
        );

        self.inner[byte_index] &= !(Self::ITEM_MASK << bit_index_in_byte);

        self.inner[byte_index] |= item_bits << bit_index_in_byte;
    }

    pub fn clear(&mut self)
    {
        self.inner.fill(0);
    }

    pub fn iter_occupied(&self) -> BitArrayOccupiedIter<'_, BITS_PER_ITEM>
    {
        BitArrayOccupiedIter {
            inner: self.inner.iter().copied().enumerate(),
            byte: None,
            mask: u8::MAX,
        }
    }

    pub fn bytes_mut(&mut self) -> &mut [u8]
    {
        &mut self.inner
    }
}

impl<const SIZE: usize, const BITS_PER_ITEM: usize> Default
    for BitArray<SIZE, BITS_PER_ITEM>
{
    fn default() -> Self
    {
        Self::new()
    }
}

pub struct BitArrayOccupiedIter<'a, const BITS_PER_ITEM: usize>
{
    inner: std::iter::Enumerate<std::iter::Copied<std::slice::Iter<'a, u8>>>,
    byte: Option<(u8, usize)>,
    mask: u8,
}

impl<const BITS_PER_ITEM: usize> BitArrayOccupiedIter<'_, BITS_PER_ITEM>
{
    const ITEM_MASK: u8 = !(u8::MAX << BITS_PER_ITEM);
}

impl<const BITS_PER_ITEM: usize> Iterator for BitArrayOccupiedIter<'_, BITS_PER_ITEM>
{
    type Item = (usize, u8);

    fn next(&mut self) -> Option<Self::Item>
    {
        let (byte_masked, byte_index, item_bit_index_in_byte) = loop {
            let current = self.byte.and_then(|(byte, byte_index)| {
                let byte_masked = byte & self.mask;

                let lowest_one = byte_masked.lowest_one()?;

                let item_bit_index_in_byte = match lowest_one as usize % BITS_PER_ITEM {
                    0 => lowest_one as usize,
                    remainder => lowest_one as usize - remainder,
                };

                Some((byte_masked, byte_index, item_bit_index_in_byte))
            });

            let Some((byte_masked, byte_index, item_bit_index_in_byte)) = current else {
                let (next_byte_index, next_byte) = self.inner.next()?;

                self.byte = Some((next_byte, next_byte_index));
                self.mask = u8::MAX;

                continue;
            };

            break (byte_masked, byte_index, item_bit_index_in_byte);
        };

        let item_bits = (byte_masked >> (item_bit_index_in_byte)) & Self::ITEM_MASK;

        self.mask &= (!Self::ITEM_MASK) << item_bit_index_in_byte;

        let item_index_in_byte = item_bit_index_in_byte as usize / BITS_PER_ITEM;

        let prev_bytes_item_cnt = (byte_index * 8) / BITS_PER_ITEM;

        let index = prev_bytes_item_cnt + item_index_in_byte;

        Some((index, item_bits))
    }
}

macro_rules! try_option {
    ($expr: expr) => {
        match $expr {
            Ok(value) => value,
            Err(err) => {
                return Some(Err(err.into()));
            }
        }
    };
}

pub(crate) use try_option;

macro_rules! or {
    (($($tt: tt)+) else ($($else_tt: tt)*)) => {
        $($tt)+
    };

    (() else ($($else_tt: tt)*)) => {
        $($else_tt)*
    };
}

pub(crate) use or;

#[macro_export]
macro_rules! expand_map_opt {
    ($in: tt, no_occurance=($($no_occurance: tt)*), occurance=($($occurance: tt)*)) => {
        $($occurance)*
    };

    (, no_occurance=($($no_occurance: tt)*), occurance=($($occurance: tt)*)) => {
        $($no_occurance)*
    };
}

#[macro_export]
macro_rules! builder {
    (
        $(#[doc = $doc: literal])*
        #[builder(
            name = $builder_name: ident
            $(, derives = ($($builder_derive: ident),+))?
        )]
        $(#[$attr: meta])*
        $visibility: vis struct $name: ident
        {
            $(
                $(#[doc = $field_doc: literal])*
                $(#[builder(skip_generate_fn$($field_skip_generate_fn: tt)?)])?
                $field_visibility: vis $field: ident: $field_type: ty,
            )*
        }
    ) => {
        $(#[doc = $doc])*
        $(#[$attr])*
        $visibility struct $name
        {
            $(
                $(#[doc = $field_doc])*
                $field_visibility $field: $field_type,
            )*
        }

        $(#[derive($($builder_derive),+)])?
        $visibility struct $builder_name
        {
            $(
                $field: $field_type,
            )*
        }

        impl $builder_name
        {
            $(
                $crate::expand_map_opt!(
                    $(true $($field_skip_generate_fn)?)?,
                    no_occurance=(
                        #[must_use]
                        $visibility fn $field(mut self, $field: $field_type) -> Self
                        {
                            self.$field = $field;
                            self
                        }
                    ),
                    occurance=()
                );
            )*

            #[must_use]
            $visibility const fn build(self) -> $name
            {
                $name {
                    $(
                        $field: self.$field,
                    )*
                }
            }
        }

        impl From<$name> for $builder_name
        {
            #[allow(unused_variables)]
            fn from(built: $name) -> Self
            {
                Self {
                    $(
                        $field: built.$field,
                    )*
                }
            }
        }
    };
}