cecs 0.1.11

Entity database for the game 'Cao-Lo'
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
425
426
427
428
429
430
431
432
use std::{
    alloc::{Layout, alloc, dealloc},
    mem::{align_of, size_of},
    ptr::{self, NonNull},
};

use crate::{
    EntityTable, RowIndex,
    entity_id::{ENTITY_GEN_MASK, ENTITY_INDEX_MASK, EntityId},
};

#[derive(Debug, Clone, thiserror::Error)]
pub enum HandleTableError {
    #[error("EntityIndex has no free capacity")]
    OutOfCapacity,
    #[error("Entity not found")]
    NotFound,
    #[error("Handle was not initialized")]
    Uninitialized,
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum InsertError {
    #[error("Id {0} has already been allocated by a different entity")]
    Taken(EntityId),
    #[error("Id {0} has already been inserted")]
    AlreadyInserted(EntityId),
}

pub(crate) struct EntityIndex {
    entries: *mut Entry,
    cap: u32,
    /// Currently allocated entries
    count: u32,
    /// deallocated entities
    /// if empty allocate the next entity in the list
    free_list: u32,
}

#[cfg(feature = "clone")]
impl Clone for EntityIndex {
    fn clone(&self) -> Self {
        let mut result = Self::new(self.cap);
        result.entries_mut().copy_from_slice(self.entries());
        result.free_list = self.free_list;
        result.count = self.count;
        result
    }
}

unsafe impl Send for EntityIndex {}
unsafe impl Sync for EntityIndex {}

const SENTINEL: u32 = !0;

impl EntityIndex {
    pub fn new(initial_capacity: u32) -> Self {
        assert!(initial_capacity < ENTITY_INDEX_MASK);
        let entries;
        let cap = initial_capacity.max(1); // allocate at least 1 entry
        unsafe {
            entries = alloc(Layout::from_size_align_unchecked(
                size_of::<Entry>() * cap as usize,
                align_of::<Entry>(),
            )) as *mut Entry;
            assert!(!entries.is_null());
            for i in 0..cap {
                ptr::write(
                    entries.add(i as usize),
                    Entry {
                        generation: 0,
                        arch: std::ptr::null_mut(),
                        row_index: i + 1,
                    },
                );
            }
            (&mut *entries.add(cap as usize - 1)).row_index = SENTINEL;
        };
        Self {
            entries,
            cap,
            free_list: 0,
            count: 0,
        }
    }

    fn free_list_push(&mut self, index: u32) {
        let next = self.free_list;
        self.entries_mut()[index as usize].row_index = next;
        self.free_list = index;
    }

    fn free_list_pop(&mut self) -> Option<u32> {
        if self.free_list == SENTINEL {
            return None;
        }
        let result = self.free_list;
        self.free_list = self.entries()[result as usize].row_index;
        Some(result)
    }

    fn grow(&mut self, new_cap: u32) {
        #[cfg(feature = "tracing")]
        tracing::trace!("Growing from {} to {new_cap}", self.cap);
        let cap = self.cap;
        assert!(new_cap < ENTITY_INDEX_MASK);
        assert!(new_cap > cap);
        assert!(new_cap >= 2);
        let new_entries: *mut Entry;
        unsafe {
            new_entries = alloc(Layout::from_size_align_unchecked(
                size_of::<Entry>() * new_cap as usize,
                align_of::<Entry>(),
            ))
            .cast();

            ptr::copy_nonoverlapping(self.entries, new_entries, cap as usize);
            for i in cap..new_cap {
                ptr::write(
                    new_entries.add(i as usize),
                    Entry {
                        generation: 0,
                        arch: std::ptr::null_mut(),
                        row_index: i + 1,
                    },
                );
            }
            (&mut *new_entries.add(new_cap as usize - 1)).row_index = self.free_list;
            self.free_list = cap;

            dealloc(
                self.entries.cast(),
                Layout::from_size_align_unchecked(
                    size_of::<Entry>() * cap as usize,
                    align_of::<Entry>(),
                ),
            );
        }
        self.entries = new_entries;
        self.cap = new_cap;
    }

    pub fn len(&self) -> usize {
        self.count as usize
    }

    pub fn capacity(&self) -> usize {
        self.cap as usize
    }

    #[allow(unused)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Can resize the buffer, if out of capacity
    pub fn allocate_with_resize(&mut self) -> EntityId {
        if self.free_list == SENTINEL && self.count == self.cap {
            self.grow((self.cap as f32 * 3.0 / 2.0).ceil() as u32);
        }
        self.allocate().unwrap()
    }

    /// Insert is an O(n) operation that walks the free-list.
    /// Definitely avoid
    pub(crate) fn insert_id(&mut self, id: EntityId) -> Result<(), InsertError> {
        let needle = id.index();
        if self
            .entries()
            .get(needle as usize)
            .map(|entry| !entry.arch.is_null())
            .unwrap_or(false)
        {
            if self.entries()[needle as usize].generation == id.generation() {
                return Err(InsertError::AlreadyInserted(id));
            } else {
                return Err(InsertError::Taken(id));
            }
        }
        if needle as usize >= self.capacity() {
            self.grow(needle + 1);
        }
        unsafe {
            let mut free_list: *mut u32 = &mut self.free_list;
            while *free_list != SENTINEL {
                if *free_list == needle {
                    // unlink from the free list
                    let row = self.entries()[needle as usize].row_index;
                    *free_list = row;
                    self.init_allocated_id(needle);
                    self.entries_mut()[needle as usize].generation = id.generation();
                    #[cfg(feature = "tracing")]
                    tracing::trace!(%id, "Inserted");
                    return Ok(());
                }
                free_list = &mut self.entries_mut()[*free_list as usize].row_index;
            }
        }
        // not found
        if self.entries()[needle as usize].generation == id.generation() {
            return Err(InsertError::AlreadyInserted(id));
        } else {
            return Err(InsertError::Taken(id));
        }
    }

    /// Allocate will not grow the buffer, caller must ensure that sufficient capacity is reserved
    pub fn allocate(&mut self) -> Result<EntityId, HandleTableError> {
        // pop element off the free list
        //
        let index = match self.free_list_pop() {
            Some(i) => i,
            None => {
                if self.count == self.cap {
                    return Err(HandleTableError::OutOfCapacity);
                }
                self.count
            }
        };
        Ok(self.init_allocated_id(index))
    }

    fn init_allocated_id(&mut self, index: u32) -> EntityId {
        let entries = self.entries;
        self.count += 1;
        let entry;
        unsafe {
            entry = &mut *entries.add(index as usize);
            entry.arch = std::ptr::null_mut();
            entry.row_index = SENTINEL;
        }
        let id = EntityId::new(index as u32, entry.generation);
        #[cfg(feature = "tracing")]
        tracing::trace!(%id, "Initialized id");
        id
    }

    pub fn reserve(&mut self, additional: u32) {
        let new_cap = self.count + additional;
        if new_cap > self.cap {
            self.grow(new_cap);
        }
    }

    /// # Safety
    ///
    /// Caller must ensure that the id is valid
    pub(crate) unsafe fn update(&mut self, id: EntityId, arch: *mut EntityTable, row: RowIndex) {
        #[cfg(feature = "tracing")]
        tracing::trace!(%id, ?arch, %row, "Updating");
        unsafe {
            let index = id.index();
            debug_assert!(index < self.cap);
            let entry = &mut *self.entries.add(index as usize);
            debug_assert_eq!(id.generation(), entry.generation);
            entry.arch = arch;
            entry.row_index = row;
        }
    }

    /// # Safety
    ///
    /// Caller must ensure that the id is valid
    pub(crate) unsafe fn update_row_index(&mut self, id: EntityId, row: RowIndex) {
        #[cfg(feature = "tracing")]
        tracing::trace!(%id, %row, "Updating row index");
        unsafe {
            let index = id.index();
            debug_assert!(index < self.cap);
            let entry = &mut *self.entries.add(index as usize);
            debug_assert_eq!(id.generation(), entry.generation);
            entry.row_index = row;
        }
    }

    fn get(&self, id: EntityId) -> Option<&Entry> {
        let index = id.index();
        self.is_valid(id)
            .then(|| unsafe { &*self.entries.add(index as usize) })
    }

    pub fn read(&self, id: EntityId) -> Result<(NonNull<EntityTable>, RowIndex), HandleTableError> {
        let res = self.get(id).ok_or(HandleTableError::NotFound)?;
        if res.arch.is_null() {
            return Err(HandleTableError::Uninitialized);
        }

        Ok((unsafe { NonNull::new_unchecked(res.arch) }, res.row_index))
    }

    pub fn free(&mut self, id: EntityId) {
        #[cfg(feature = "tracing")]
        tracing::trace!(%id, "Freeing");
        self.count -= 1;
        let index = id.index();
        let entry: &mut Entry;
        unsafe {
            let entries = self.entries;
            entry = &mut *entries.add(index as usize);
        }
        debug_assert_eq!(id.generation(), entry.generation);
        entry.arch = std::ptr::null_mut();
        entry.row_index = SENTINEL;
        entry.generation = (entry.generation + 1) & ENTITY_GEN_MASK;
        self.free_list_push(index);
    }

    pub fn is_valid(&self, id: EntityId) -> bool {
        let index = id.index() as usize;
        let generation = id.generation();
        match self.entries().get(index) {
            Some(entry) => entry.generation == generation && entry.arch != std::ptr::null_mut(),
            None => return false,
        }
    }

    fn entries(&self) -> &[Entry] {
        unsafe { std::slice::from_raw_parts(self.entries, self.cap as usize) }
    }

    fn entries_mut(&mut self) -> &mut [Entry] {
        unsafe { std::slice::from_raw_parts_mut(self.entries, self.cap as usize) }
    }
}

impl Drop for EntityIndex {
    fn drop(&mut self) {
        unsafe {
            dealloc(
                self.entries.cast(),
                Layout::from_size_align_unchecked(
                    size_of::<Entry>() * (self.cap as usize),
                    align_of::<Entry>(),
                ),
            );
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct Entry {
    pub generation: u32,
    pub arch: *mut EntityTable,
    /// Store the index of the entity in the EntityTable
    /// When entity is invalid the row_index stores the position of the next Entry in the free-list
    pub row_index: RowIndex,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_alloc() {
        let mut table = EntityIndex::new(512);

        for _ in 0..4 {
            let e = table.allocate().unwrap();
            assert_eq!(e.generation(), 0); // assert for the next step in the test
        }
        for i in 0..4 {
            let e = EntityId::new(i, 0);
            table.free(e);
            assert!(!table.is_valid(e));
        }
        for _ in 0..512 {
            let _e = table.allocate();
        }
    }

    #[test]
    fn dealloc_test() {
        let mut table = EntityIndex::new(512);

        let a = table.allocate().unwrap();

        table.free(a);

        assert!(!table.is_valid(a));
    }

    #[test]
    fn can_grow_handles_test() {
        let mut table = EntityIndex::new(0);

        table.reserve(128);
        for _ in 0..128 {
            table.allocate().unwrap();
        }
    }

    #[test]
    fn reuses_entity_ids_test() {
        let mut table = EntityIndex::new(0);

        table.reserve(128);

        let mut a = table.allocate_with_resize();
        for _ in 0..10 {
            table.free(a);
            let b = table.allocate_with_resize();
            assert_eq!(a.index(), b.index());
            assert_ne!(a.generation(), b.generation());
            a = b;
        }
    }

    #[test]
    fn walking_the_free_list_terminates_test() {
        // see if the sentinel value is in the chain after resizing
        let mut table = EntityIndex::new(0);

        let ids = (0..256)
            .map(|_| table.allocate_with_resize())
            .collect::<Vec<_>>();
        for id in ids {
            table.free(id);
        }

        let mut next = table.free_list;
        let mut cnt = 0;
        let cap = table.capacity();
        while next != SENTINEL {
            cnt += 1;
            let entry = &table.entries()[next as usize];
            next = entry.row_index;
            assert!(entry.arch.is_null());
            assert!(cnt <= cap);
        }
        assert_eq!(cnt, cap);
    }
}