muds 0.1.5

Minimalistic Data Structures and Entity-Component-System Library
Documentation
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
//! Generational indices.

use crate::UnsignedNum;
use core::{
    cmp::Ordering,
    fmt::Debug,
    hash::{Hash, Hasher},
    marker::PhantomData,
};
use num::Bounded;

/// An index with generation that can be used as a weak reference to array values.
/// The generation part allows indices to be reused without suffering from [ABA problem](https://en.wikipedia.org/wiki/ABA_problem),
/// so that data can be safely stored in a packed array.
pub trait GenIndex: Copy + Debug + Default + Hash + PartialEq + PartialOrd {
    /// The type of index value.
    type Index: UnsignedNum;

    /// The type of generation value.
    type Generation: UnsignedNum;

    /// Returns the maximum generation value.
    fn max_generation() -> Self::Generation;

    /// Create a new `GenIndex` from its raw parts.
    fn from_raw_parts(index: Self::Index, generation: Self::Generation) -> Self;

    /// Returns the index value of this `GenIndex`.
    fn index(&self) -> Self::Index;

    /// Returns the generation value of this `GenIndex`.
    fn generation(&self) -> Self::Generation;

    /// Returns a null value.
    #[inline]
    fn null() -> Self {
        Default::default()
    }

    /// Checks if the value represents null.
    #[inline]
    fn is_null(&self) -> bool {
        *self == Self::null()
    }
}

// region: Index

/// A standard [GenIndex] with usize index and usize generation
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub struct Index<I: UnsignedNum = usize, G: Bounded + UnsignedNum = usize>(I, G);

impl<I: UnsignedNum, G: Bounded + UnsignedNum> Default for Index<I, G> {
    fn default() -> Self {
        Self::from_raw_parts(I::zero(), G::zero())
    }
}

impl<I: UnsignedNum, G: Bounded + UnsignedNum> GenIndex for Index<I, G> {
    type Index = I;
    type Generation = G;

    /// Returns the maximum generation value.
    #[inline]
    fn max_generation() -> Self::Generation {
        G::max_value()
    }

    #[inline]
    fn from_raw_parts(index: Self::Index, generation: Self::Generation) -> Self {
        Self(index, generation)
    }

    #[inline]
    fn index(&self) -> Self::Index {
        self.0
    }

    #[inline]
    fn generation(&self) -> Self::Generation {
        self.1
    }
}

impl<I: UnsignedNum, G: Bounded + UnsignedNum> From<Index<I, G>> for (I, G) {
    #[inline]
    fn from(idx: Index<I, G>) -> Self {
        (idx.0, idx.1)
    }
}

impl<I: UnsignedNum, G: Bounded + UnsignedNum> From<(I, G)> for Index<I, G> {
    #[inline]
    fn from((index, generation): (I, G)) -> Self {
        Index::from_raw_parts(index, generation)
    }
}

// endregion: Index

// region: IndexF64

/// A [GenIndex] that is stored as f64, which 32bit index and 21bit generation.
/// Useful for interfacing with Javascript
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct IndexF64(f64);

/// Equals 2^21 - 1. f64 can safely store integer up to 2^53 - 1.
/// We used 32bits for the index, leaving 21bits for generation.
const MAX_SAFE_F64_GENERATION: u32 = (1 << 21) - 1;

impl GenIndex for IndexF64 {
    type Index = u32;
    type Generation = u32;

    #[inline]
    fn max_generation() -> Self::Generation {
        MAX_SAFE_F64_GENERATION
    }

    #[inline]
    fn from_raw_parts(index: Self::Index, generation: Self::Generation) -> Self {
        Self(index as f64 + (((generation & Self::max_generation()) as u64) << 32) as f64)
    }

    #[inline]
    fn index(&self) -> Self::Index {
        (self.0 as u64 & (u32::MAX as u64)) as u32
    }

    #[inline]
    fn generation(&self) -> Self::Generation {
        ((self.0 as u64) >> 32) as u32
    }
}

impl Hash for IndexF64 {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (self.0 as i64).hash(state);
    }
}

impl From<IndexF64> for (u32, u32) {
    #[inline]
    fn from(idx: IndexF64) -> Self {
        (idx.index(), idx.generation())
    }
}

impl From<(u32, u32)> for IndexF64 {
    #[inline]
    fn from((index, generation): (u32, u32)) -> Self {
        IndexF64::from_raw_parts(index, generation)
    }
}

// endregion: IndexF64

// region: IndexU64

/// A [GenIndex] that is stored as u64, which 32bit index and 32bit generation.
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct IndexU64(u64);

impl GenIndex for IndexU64 {
    type Index = u32;
    type Generation = u32;

    #[inline]
    fn max_generation() -> Self::Generation {
        u32::MAX
    }

    #[inline]
    fn from_raw_parts(index: Self::Index, generation: Self::Generation) -> Self {
        Self(index as u64 + ((generation as u64) << 32))
    }

    #[inline]
    fn index(&self) -> Self::Index {
        (self.0 & (u32::MAX as u64)) as u32
    }

    #[inline]
    fn generation(&self) -> Self::Generation {
        (self.0 >> 32) as u32
    }
}

impl From<IndexU64> for (u32, u32) {
    #[inline]
    fn from(idx: IndexU64) -> Self {
        (idx.index(), idx.generation())
    }
}

impl From<(u32, u32)> for IndexU64 {
    #[inline]
    fn from((index, generation): (u32, u32)) -> Self {
        IndexU64::from_raw_parts(index, generation)
    }
}

// endregion: IndexU64

// region: TypedIndex

/// A [GenIndex] newtype.
#[derive(Eq, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(transparent)
)]
#[repr(transparent)]
pub struct TypedIndex<T, I: GenIndex = IndexF64> {
    index: I,
    marker: PhantomData<*const T>,
}

impl<T, I: GenIndex> TypedIndex<T, I> {
    #[inline]
    pub fn from_index(index: I) -> Self {
        Self {
            index,
            marker: PhantomData,
        }
    }

    #[inline]
    pub fn to_index(&self) -> I {
        self.index
    }
}

impl<T, I: GenIndex> Clone for TypedIndex<T, I> {
    #[inline]
    fn clone(&self) -> Self {
        Self::from_index(self.index.clone())
    }
}

impl<T, I: GenIndex> Copy for TypedIndex<T, I> {}

impl<T, I: GenIndex> Default for TypedIndex<T, I> {
    #[inline]
    fn default() -> Self {
        Self::from_index(Default::default())
    }
}

impl<T, I: GenIndex> Debug for TypedIndex<T, I> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.index.fmt(f)
    }
}

impl<T, I: GenIndex> Hash for TypedIndex<T, I> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.index.hash(state)
    }
}

impl<T, I: GenIndex> PartialOrd for TypedIndex<T, I> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.index.partial_cmp(&other.index)
    }
}

impl<T, I: GenIndex> PartialEq for TypedIndex<T, I> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.index.eq(&other.index)
    }
}

impl<T, I: GenIndex> GenIndex for TypedIndex<T, I> {
    type Index = I::Index;

    type Generation = I::Generation;

    #[inline]
    fn max_generation() -> Self::Generation {
        I::max_generation()
    }

    #[inline]
    fn from_raw_parts(index: Self::Index, generation: Self::Generation) -> Self {
        Self {
            index: I::from_raw_parts(index, generation),
            marker: PhantomData,
        }
    }

    #[inline]
    fn index(&self) -> Self::Index {
        self.index.index()
    }

    #[inline]
    fn generation(&self) -> Self::Generation {
        self.index.generation()
    }
}

impl<T, I: GenIndex> From<TypedIndex<T, I>> for (I::Index, I::Generation) {
    #[inline]
    fn from(idx: TypedIndex<T, I>) -> Self {
        (idx.index(), idx.generation())
    }
}

impl<T, I: GenIndex> From<(I::Index, I::Generation)> for TypedIndex<T, I> {
    #[inline]
    fn from((index, generation): (I::Index, I::Generation)) -> Self {
        TypedIndex::from_raw_parts(index, generation)
    }
}

// endregion: TypedIndex

#[cfg(test)]
mod tests {
    #[cfg(feature = "serde")]
    #[test]
    fn test_indexf64_deserialize() {
        use crate::{GenIndex, IndexF64};
        use serde_json::{json, Value};

        let expected_index = IndexF64::from_raw_parts(123, 456);
        let json: Value = json!((456u64 << 32 | 123) as f64);

        let index: IndexF64 = serde_json::from_value(json).unwrap();

        assert_eq!(index, expected_index);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_indexf64_serialize() {
        use crate::{GenIndex, IndexF64};
        use serde_json::{json, Value};

        let index = IndexF64::from_raw_parts(123, 456);
        let expected_json: Value = json!((456u64 << 32 | 123) as f64);

        let json: Value = serde_json::to_value(index).unwrap();

        assert_eq!(json, expected_json);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_index_deserialize() {
        use crate::{GenIndex, Index};
        use alloc::vec;
        use serde_json::{json, Value};

        let expected_index = Index::from_raw_parts(123, 456);
        let json: Value = json!([123, 456]);

        let index: Index = serde_json::from_value(json).unwrap();

        assert_eq!(index, expected_index);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_index_serialize() {
        use crate::{GenIndex, Index};
        use alloc::vec;
        use serde_json::{json, Value};

        let index: Index = Index::from_raw_parts(123, 456);
        let expected_json: Value = json!([123, 456]);

        let json: Value = serde_json::to_value(index).unwrap();

        assert_eq!(json, expected_json);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_typedindex_deserialize() {
        use crate::{GenIndex, Index, TypedIndex};
        use alloc::vec;
        use serde_json::{json, Value};

        struct TestType;

        let expected_index = TypedIndex::<TestType, Index>::from_raw_parts(123, 456);
        let json: Value = json!([123, 456]);

        let index: TypedIndex<TestType, Index> = serde_json::from_value(json).unwrap();

        assert_eq!(index, expected_index);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_typedindex_serialize() {
        use crate::{GenIndex, Index, TypedIndex};
        use alloc::vec;
        use serde_json::{json, Value};

        struct TestType;

        let index = TypedIndex::<TestType, Index>::from_raw_parts(123, 456);
        let expected_json: Value = json!([123, 456]);

        let json: Value = serde_json::to_value(index).unwrap();

        assert_eq!(json, expected_json);
    }
}