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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! # Tiny ECS
//!
//! This ECS intends to be simple, fast, and easy to use. As such it provides
//! management for entities and components, but not systems - this part is up
//! to you.
//!
//! You will need to create external systems; these can be a function, a loop,
//! or anything else you can think of to run - functionally you'll be doing
//! something with multiple `VecMap<T>`, which are what contain components.
//! One `VecMap` per component type.
//!
//! Internally this ECS is the use of `bitmasks`. Each entity ID is in
//! practice an internal index number in to an array which contains bitmasks.
//! The bitmasks themselves keep track of what components the entity has.
//!
//! **Note:** borrows of `VecMap` are checked at runtime.
//!
//! # Examples
//!
//! ## Init with a capacity
//!
//! This is good to do if you know the size required
//! as it will prevent many reallocs/moves as data is added. This affects
//! both the entity and component map allocs (they will be equal in length).
//!
//! ```
//! use tiny_ecs::Entities;
//!
//! let mut entities = Entities::new(Some(1000), Some(24));
//! ```
//!
//! ## Demonstrating use
//!
//! ```
//! use tiny_ecs::Entities;
//! use tiny_ecs::ECSError;
//!
//! // These are the "components" we will use
//! struct Vector1 {
//!     x: i32,
//! }
//! struct Vector2 {
//!     x: i32,
//!     y: i32,
//! }
//! struct Vector3 {
//!     x: i32,
//!     y: i32,
//!     z: i32,
//! }
//! # fn main() -> Result<(), ECSError> {
//! // Initialize the Entity collection
//! let mut entities = Entities::new(Some(3), Some(3));
//!
//! // Creating an entity uses the builder pattern.
//! // Be sure to return the ID if you need to track it
//! let entity_1 = entities.new_entity()
//!                        .with(Vector1 { x: 42 })?
//!                        .with(Vector3 { x: 3, y: 10, z: -12 })?
//!                        .finalise()?;
//! // The entity ID will increment up from 0
//! assert_eq!(entity_1, 0);
//!
//! // Do note however, that you can keep adding parts to this entity
//! // via the builder pattern until you choose to create another entity
//!
//! // To add another entity you need to create one
//! entities.new_entity()
//!         .with(Vector2 { x: 66, y: 6 })?
//!         .with(Vector1 { x: 6 })?
//!         .finalise()?;
//! # Ok(())
//! # }
//!```
//!
//! ## Access an entities part of type `<T>`
//! ```
//! # use tiny_ecs::Entities;
//! # use tiny_ecs::ECSError;
//! # fn main() -> Result<(), ECSError> {
//! struct Vector3 {x: i32, y: i32, z: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # let entity_1 = entities.new_entity()
//! #                         .with(Vector3 { x: 3, y: 10, z: -12 })?
//! #                         .finalise()?;
//! // To get access to a part belonging to an entity you need
//! // first to get the component map created for the part type
//! // You need to 'anchor' this with a let or the ref is
//! // dropped before you can use it
//! let mut components = entities
//!     .borrow_mut::<Vector3>()?;
//! // You can then use the part by getting a reference
//! let mut part = components.get_mut(entity_1).unwrap();
//! assert_eq!(part.z, -12);
//! # Ok(())
//! # }
//! ```
//!
//! ## Check if `Entity` contains a part type + remove part
//! ```
//! # use tiny_ecs::Entities;
//! # use tiny_ecs::ECSError;
//! # fn main() -> Result<(), ECSError> {
//! struct Vector1 {x: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! let entity_1 = entities.new_entity()
//!                        .with(Vector1 { x: 3 })?
//!                        .finalise()?;
//! // You can check if an entity contains a part with the type signature
//! if entities.entity_contains::<Vector1>(entity_1) {
//!     assert!(entities.rm_component::<Vector1>(entity_1).is_ok());
//! }
//! assert_eq!(entities.entity_contains::<Vector1>(entity_1), false);
//! # Ok(())
//! # }
//! ```
//!
//! ## A system that uses an `get_mut()`
//! ```
//! # use tiny_ecs::{Entities, VecMap};
//! # use tiny_ecs::ECSError;
//! # fn main() -> Result<(), ECSError> {
//! struct Vector1 {x: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # entities.new_entity().with(Vector1 { x: 3 })?.finalise()?;
//!
//! // Make a system of some form that takes a `VecMap<T>` arg
//! fn some_system(mut components: &mut VecMap<Vector1>) {
//!     // You can then iterate over the components directly
//!     for (k, v) in components.iter_mut() {
//!         v.x += 1;
//!         assert!(v.x > k as i32);
//!     }
//! }
//! # let mut components = entities.borrow_mut::<Vector1>()?;
//! some_system(&mut components);
//! # Ok(())
//! # }
//! ```
//!
//! ## Get components for an entity ID list
//! ```
//! # use tiny_ecs::{Entities, VecMap};
//! # use tiny_ecs::ECSError;
//! # fn main() -> Result<(), ECSError> {
//! struct Vector1 {x: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # entities.new_entity().with(Vector1 { x: 3 })?.finalise()?;
//!
//! // A system that fetches the components for only the entities you are require
//! fn second_system(active: &[usize], mut v1_map: &mut VecMap<Vector1>) {
//!     for id in active {
//!         if let Some(part) = v1_map.get_mut(*id) {
//!             part.x = 42;
//!         }
//!     }
//! }
//! # let mut components = entities.borrow_mut::<Vector1>()?;
//! second_system(&[0, 1, 2], &mut components);
//! # Ok(())
//! # }
//! ```
//!
//! ## A more complex system using VecMaps directly
//! ```
//! # use tiny_ecs::Entities;
//! # use tiny_ecs::ECSError;
//! # fn main() -> Result<(), ECSError> {
//! # struct Vector1 {x: i32 }
//! # struct Vector2 {x: i32, y: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # entities.new_entity()
//! # .with(Vector1 { x: 3 })?
//! # .with(Vector2 { x: 3, y: 3 })?
//! # .finalise()?;
//!
//! // Or a system handles the `Entities` container directly
//! fn other_system(active_ents: &[usize], entities: &mut Entities) -> Result<(), ECSError> {
//!     // You can mutably borrow multiple component maps at once
//!     let mut v1_components = entities
//!         .borrow_mut::<Vector1>()?;
//!
//!     let mut v2_components = entities
//!         .borrow_mut::<Vector2>()?;
//!
//!     // But not have a mutable borrow and immutable borrow to the same map
//!     // Fails at runtime!
//!     // let v2_components = entities.borrow::<Vector2>().unwrap();
//!     for id in active_ents {
//!         if entities.entity_contains::<Vector1>(*id) &&
//!            entities.entity_contains::<Vector2>(*id) {
//!             let v1_part = v1_components.get_mut(*id).unwrap();
//!             let v2_part = v2_components.get_mut(*id).unwrap();
//!             v1_part.x = 42;
//!             assert_ne!(v1_part.x, 43);
//!             assert_eq!(v1_part.x, 42);
//!         }
//!     }
//!     Ok(())
//! }
//! other_system(&[0, 1, 2], &mut entities);
//! # Ok(())
//! # }
//! ```

mod errors;

pub use crate::errors::*;
use hashbrown::HashMap;
use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell, RefMut};
use std::ops::{Deref, DerefMut};
use vec_map;
pub use vec_map::VecMap;

#[cfg(feature = "component_max_31")]
type BitMaskType = u32;
#[cfg(feature = "component_max_63")]
type BitMaskType = u64;
#[cfg(feature = "component_max_127")]
type BitMaskType = u128;

type BoxAny = Box<dyn Any>;
type ComponentRmFn = dyn FnMut(usize, &mut BoxAny);

#[cfg(feature = "component_max_31")]
const BIT_MASK_MAX: BitMaskType = 31;
#[cfg(feature = "component_max_63")]
const BIT_MASK_MAX: BitMaskType = 63;
#[cfg(feature = "component_max_127")]
const BIT_MASK_MAX: BitMaskType = 127;

// Bitmask used to fill the initial mask list, and replace deleted entities
const EMPTY: BitMaskType = 0;

/// Immutable reference container for `VecMap` returned by `Entities::borrow()`
///
/// This struct is required to contain a hidden borrow to the requested `VecMap`.
/// The reason for this is so we can borrow multiple `VecMap`, but not break the
/// borrow checker rules for borrows on a single `VecMap`.
#[derive(Debug)]
pub struct MapRef<'a, T> {
    _borrow: Ref<'a, dyn Any>,
    value: &'a VecMap<T>,
}

impl<'a, T: 'static> MapRef<'a, T> {
    fn new(value: &'a RefCell<BoxAny>) -> Result<MapRef<'a, T>, ECSError> {
        let borrow = value.try_borrow().or(Err(ECSError::Borrow))?;

        // This is required to sidestep the borrow issue in root Entities struct
        let v = (unsafe { value.as_ptr().as_ref() })
            .ok_or(ECSError::PtrRef)?
            .downcast_ref::<VecMap<T>>()
            .ok_or(ECSError::Downcast)?;

        // And make it safe by keeping the lifetime of the borrow with the downcast
        Ok(MapRef {
            value: v,
            _borrow: borrow,
        })
    }
}

impl<'a, T> Deref for MapRef<'a, T> {
    type Target = VecMap<T>;

    #[inline]
    fn deref(&self) -> &VecMap<T> {
        self.value
    }
}

/// Mutable reference container for `VecMap` returned by `Entities::borrow_mut()`
///
/// This struct is required to contain a hidden borrow to the requested `VecMap`.
/// The reason for this is so we can borrow multiple `VecMap`, but not break the
/// borrow checker rules for borrows on a single `VecMap`.
#[derive(Debug)]
pub struct MapRefMut<'a, T> {
    _borrow: RefMut<'a, dyn Any>,
    value: &'a mut VecMap<T>,
}

impl<'a, T: 'static> MapRefMut<'a, T> {
    #[inline]
    fn new(value: &'a RefCell<BoxAny>) -> Result<MapRefMut<'a, T>, ECSError> {
        let borrow = value.try_borrow_mut().or(Err(ECSError::BorrowMut))?;

        let v = (unsafe { value.as_ptr().as_mut() })
            .ok_or(ECSError::PtrMut)?
            .downcast_mut::<VecMap<T>>()
            .ok_or(ECSError::DowncastMut)?;

        Ok(MapRefMut {
            value: v,
            _borrow: borrow,
        })
    }
}

impl<'a, T> Deref for MapRefMut<'a, T> {
    type Target = VecMap<T>;

    #[inline]
    fn deref(&self) -> &VecMap<T> {
        self.value
    }
}

impl<'a, T> DerefMut for MapRefMut<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut VecMap<T> {
        self.value
    }
}

/// This is the root of the ECS implementation
pub struct Entities {
    // the index in to this Vec is the ID of the entity
    entity_masks: Vec<BitMaskType>,
    components: Vec<RefCell<BoxAny>>,
    next_free_entity: usize,
    current_entity: Option<usize>,
    vacated_slots: Vec<usize>,
    // BitMaskType is the mask assigned to the TypeId and is used to
    // quickly determine if an entity has a component type
    type_masks: HashMap<TypeId, (BitMaskType, usize)>,
    next_typemask: BitMaskType,
    // required so that an entity can be removed simply
    // index of remover matches associated component type index in self.components
    removers: Vec<Box<ComponentRmFn>>,
}

impl Default for Entities {
    /// Create a new `Entities` struct with no pre-allocated memory for maps
    fn default() -> Self {
        Entities::new(None, None)
    }
}

impl Entities {
    /// Create a new root entity container.
    ///
    /// - `entity_count` will initialize the entity map and new
    ///   component maps to this size. This is a good thing to do to
    ///   prevent unnecessary (re)allocations if you know the total
    ///   active entity count. Entity removals will free up slots which
    ///   are then reused instead of expanding the map.
    /// - `part_count` is as above, for total part types/kinds, there is
    ///   a maximum of either 32 or 64 individual parts you can add of
    ///   which the index starts at 0 to n-1
    pub fn new(entity_count: Option<usize>, part_count: Option<usize>) -> Entities {
        if let Some(part_count) = part_count {
            if part_count as BitMaskType > BIT_MASK_MAX {
                // Must panic if the component count is larger than the mask size
                // as we can only insert this many anyway
                panic!(
                    "Initial part count too large. Maximum of {} allowed",
                    BIT_MASK_MAX
                );
            }
        }
        Entities {
            entity_masks: vec![EMPTY; entity_count.unwrap_or(0)],
            components: Vec::with_capacity(part_count.unwrap_or(5)),
            next_free_entity: 0,
            current_entity: None,
            vacated_slots: Vec::new(),
            type_masks: HashMap::with_capacity(part_count.unwrap_or(5)),
            next_typemask: 1,
            removers: Vec::with_capacity(part_count.unwrap_or(5)),
        }
    }

    /// Start the creation of a new entity
    ///
    /// If no parts are added to this call with `with()` then the entity will
    /// not be created.
    #[inline]
    pub fn new_entity(&mut self) -> &mut Self {
        if let Some(slot) = self.vacated_slots.pop() {
            self.current_entity = Some(slot);
        } else {
            self.current_entity = Some(self.next_free_entity);
            self.entity_masks.push(EMPTY);
            self.next_free_entity += 1;
        }
        self
    }

    /// Chained with `new_entity()` to add components
    ///
    /// `with()` can be chained multiple times to add many components.
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::Entities;
    /// # use tiny_ecs::ECSError;
    /// # fn main() -> Result<(), ECSError> {
    /// struct Component1 {}
    /// struct Component2 {}
    ///
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// let entity_1 = entities
    ///                 .new_entity()
    ///                 .with(Component1 {})?
    ///                 .with(Component2 {})?
    ///                 .finalise()?;
    /// assert_eq!(entity_1, 0);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn with<T: 'static>(&mut self, part: T) -> Result<&mut Self, ECSError> {
        // Can't use .with() after entity is finalised
        if self.current_entity.is_none() {
            return Err(ECSError::WithAfterFinalise);
        }
        let type_id = TypeId::of::<T>();

        let (type_mask, type_index) = {
            // if the component doesn't already have a type_mask entry
            if !self.type_masks.contains_key(&type_id) {
                if (self.type_masks.len() as BitMaskType) >= BIT_MASK_MAX {
                    return Err(ECSError::BitMasksExhausted);
                }
                self.components
                    .push(RefCell::new(Box::new(VecMap::<T>::with_capacity(
                        self.entity_masks.len(),
                    ))));
                self.removers.push(Box::new(|id: usize, ve: &mut BoxAny| {
                    if let Some(m) = &mut ve.downcast_mut::<VecMap<T>>() {
                        m.remove(id);
                    };
                }));
                self.type_masks
                    .insert(type_id, (self.next_typemask, self.components.len() - 1));
                self.next_typemask <<= 1;
            }
            self.type_masks[&type_id]
        };

        // TODO: overwrite? Crate user will need to be made aware when it happens if so
        // this shouldn't ever fail
        let entity_mask = self.entity_masks[self.current_entity.unwrap()];
        if entity_mask & type_mask == type_mask {
            return Err(ECSError::AddDupeComponent);
        }

        // This really shouldn't ever fail
        let id = self.current_entity.unwrap();
        if let Some(col) = self.components.get_mut(type_index) {
            col.borrow_mut()
                .downcast_mut::<VecMap<T>>()
                .ok_or(ECSError::DowncastMut)?
                .insert(id, part);
            // update the entity mask
            let old = self.entity_masks[id];
            self.entity_masks[id] = old | type_mask;
        }
        Ok(self)
    }

    /// Optional final call in creating an entity - returns ID
    ///
    /// If you don't finalise an entity you can keep adding
    /// components to it later. This isn't recommended though
    /// as it's easy to lose track of which entity you are working
    /// on. The `add_component()` method allows you to add extra
    /// components to an existing entity if you know the ID.
    #[inline]
    pub fn finalise(&mut self) -> Result<usize, ECSError> {
        if let Some(entity) = self.current_entity {
            self.current_entity = None;
            return Ok(entity);
        }
        Err(ECSError::FinaliseNonEntity)
    }

    /// Check if an entity ID is valid (alive and has components)
    ///
    /// If `false` then there are no components attached to this ID and
    /// the entity is `None`.
    #[inline]
    pub fn entity_exists(&self, id: usize) -> bool {
        if let Some(ent) = self.entity_masks.get(id) {
            return *ent > 0;
        }
        false
    }

    #[inline]
    pub fn entity_contains<T: 'static>(&self, id: usize) -> bool {
        if let Some(entity_mask) = self.entity_masks.get(id) {
            if let Some((type_mask, _)) = self.type_masks.get(&TypeId::of::<T>()) {
                if entity_mask & type_mask == *type_mask {
                    return true;
                }
            }
        }
        false
    }

    /// Remove an entities part. If no components are left after part removal then
    /// the entity is considered deleted
    ///
    /// Removal requires the ID of the entity and the components type signature.
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::Entities;
    /// # use tiny_ecs::ECSError;
    /// # fn main() -> Result<(), ECSError> {
    /// #[derive(Debug, PartialEq)]
    /// struct Test1 {}
    ///
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.new_entity()
    /// # .with(Test1 {})?.finalise()?;
    /// assert!(entities.rm_component::<Test1>(entity_1).is_ok());
    /// assert!(!entities.entity_contains::<Test1>(entity_1));
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn rm_component<T: 'static>(&mut self, id: usize) -> Result<(), ECSError> {
        let type_id = TypeId::of::<T>();
        if let Some((type_mask, type_index)) = self.type_masks.get(&type_id) {
            if let Some(map) = self.components.get_mut(*type_index) {
                map.borrow_mut()
                    .downcast_mut::<VecMap<T>>()
                    .ok_or(ECSError::DowncastMut)?
                    .remove(id);
                self.entity_masks[id] ^= *type_mask;
                if self.entity_masks[id] == EMPTY {
                    self.vacated_slots.push(id)
                }
                return Ok(());
            }
        }
        Err(ECSError::NoComponentMap)
    }

    /// Remove an entity and all its components
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::Entities;
    /// # use tiny_ecs::ECSError;
    /// # fn main() -> Result<(), ECSError> {
    /// #[derive(Debug, PartialEq)]
    /// struct Test1 {}
    /// struct Test2 {}
    /// struct Test3 {}
    ///
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// let entity_1 = entities.new_entity()
    ///     .with(Test1 {})?
    ///     .with(Test2 {})?
    ///     .with(Test3 {})?.finalise()?;
    ///
    /// assert!(entities.entity_contains::<Test1>(entity_1));
    /// assert!(entities.entity_contains::<Test2>(entity_1));
    /// assert!(entities.entity_contains::<Test3>(entity_1));
    ///
    /// entities.rm_entity(entity_1);
    ///
    /// assert!(!entities.entity_contains::<Test1>(entity_1));
    /// assert!(!entities.entity_contains::<Test2>(entity_1));
    /// assert!(!entities.entity_contains::<Test3>(entity_1));
    ///
    /// assert_eq!(entities.entity_exists(entity_1), false);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn rm_entity(&mut self, id: usize) {
        for i in 0..self.components.len() {
            if let Some(m) = self.removers.get_mut(i) {
                // This should be deemed as safe due to the fact self is borrowed as mut exclusive
                // The cast is done only to bypass the runtime borrow check on interior mutability
                unsafe {
                    m(id, &mut *self.components[i].as_ptr());
                }
            }
        }
        self.entity_masks[id] = EMPTY;
    }

    /// Add a component to the existing Entity ID
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::Entities;
    /// # use tiny_ecs::ECSError;
    /// # fn main() -> Result<(), ECSError> {
    /// struct Test1 {}
    /// struct Test2 {}
    /// struct Test3 {}
    ///
    /// let mut entities = Entities::new(Some(3), Some(3));
    /// let entity_1 = entities
    ///     .new_entity()
    ///     .with(Test1 {})?
    ///     .with(Test2 {})?
    ///     .finalise()?;
    /// entities.add_component(entity_1, Test3 {});
    /// assert!(entities.entity_contains::<Test1>(entity_1));
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn add_component<T: 'static>(&mut self, id: usize, component: T) -> Result<(), ECSError> {
        if let Some(ent) = self.entity_masks.get(id) {
            if *ent == 0 {
                return Err(ECSError::WithAfterFinalise);
            }
        }
        self.current_entity = Some(id);
        self.with(component)?.finalise()?;
        Ok(())
    }

    /// Get a plain reference to the selected entity part map. Borrow rules are checked at runtime.
    ///
    /// You may have multiple immutable references to the requested `VecMap`
    /// **type** but no mutable references if the same **typed** `VecMap`
    /// is currently referenced.
    ///
    /// - `Option` is whether or not there is a part of `<T>` for that entity.
    /// - Borrowing (`Ref`) is checked at runtime.
    ///
    /// # Example
    /// ```
    /// # use tiny_ecs::Entities;
    /// # use tiny_ecs::ECSError;
    /// # fn main() -> Result<(), ECSError> {
    /// # struct Test1 { x: u32 }
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.new_entity()
    /// # .with(Test1 { x: 666 })?.finalise()?;
    /// let components = entities
    ///     .borrow::<Test1>()
    ///     .unwrap();
    /// let part = components.get(entity_1).unwrap();
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub fn borrow<T: 'static>(&self) -> Result<MapRef<T>, ECSError> {
        let type_id = TypeId::of::<T>();
        if let Some((_, type_index)) = self.type_masks.get(&type_id) {
            if let Some(components) = self.components.get(*type_index) {
                return Ok(MapRef::new(components)?);
            }
        }
        Err(ECSError::NoComponentMap)
    }

    /// Allows you to borrow without runtime check overhead or to borrow when the standard
    /// borrow rules prevent you from doing so and you enforce safety
    ///
    /// **Unsafe:** Borrows are not checked at compile-time or runtime. An unchecked borrow
    /// on a mutably borrowed `VecMap` is UB.
    #[inline(always)]
    pub unsafe fn borrow_unchecked<T: 'static>(&self) -> Result<&VecMap<T>, ECSError> {
        let type_id = TypeId::of::<T>();
        if let Some((_, type_index)) = self.type_masks.get(&type_id) {
            if let Some(components) = self.components.get(*type_index) {
                let components = (&*components.as_ptr())
                    .downcast_ref::<VecMap<T>>()
                    .ok_or(ECSError::Downcast)?;
                return Ok(components);
            }
        }
        Err(ECSError::NoComponentMap)
    }

    /// Get a mutable reference to the selected entity part map. Borrow rules are checked at runtime.
    ///
    /// You may have only one mutable reference to the requested `VecMap`
    /// **type** and no immutable references. You can however, have multiple
    /// mutable references to different **types** of `VecMap`
    ///
    /// - `Result` covers if the map was able to be borrowed mutably or not.
    /// - Borrowing is checked at runtime.
    ///
    /// # Example
    /// ```
    /// # use tiny_ecs::Entities;
    /// # use tiny_ecs::ECSError;
    /// # fn main() -> Result<(), ECSError> {
    /// # #[derive(Debug, PartialEq)]
    /// # struct Test1 { x: u32 }
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.new_entity()
    /// # .with(Test1 { x: 0 })?.finalise()?;
    /// // Because we later need a ref to the same `Type` of map, the mut ref
    /// // will need to be scoped. If the later ref was of a different type,
    /// // eg: Vector2, then it wouldn't need scoping.
    /// {
    ///     let mut components = entities
    ///         .borrow_mut::<Test1>()?;
    ///     for id in 0..5 {
    ///         if let Some(part) = components.get_mut(id) {
    ///             part.x = 42;
    ///         }
    ///     }
    /// }
    ///
    /// // Now get a ref to the modified part
    /// let components = entities.borrow::<Test1>()?;
    /// let part = components.get(entity_1).unwrap();
    /// assert_eq!(part.x, 42);
    /// # Ok(())
    /// # }
    /// ```
    #[inline(always)]
    pub fn borrow_mut<T: 'static>(&self) -> Result<MapRefMut<T>, ECSError> {
        let type_id = TypeId::of::<T>();
        if let Some((_, type_index)) = self.type_masks.get(&type_id) {
            if let Some(components) = self.components.get(*type_index) {
                return Ok(MapRefMut::new(components)?);
            }
        }
        Err(ECSError::NoComponentMap)
    }

    /// Allows you to borrow mutably without runtime check overhead or to borrow when the standard
    /// borrow rules prevent you from doing so and you enforce safety
    ///
    /// **Unsafe:** Borrows are not checked at compile-time or runtime. An unchecked mutable
    /// on an immutably borrowed `VecMap` is UB.
    #[inline(always)]
    pub unsafe fn borrow_mut_unchecked<T: 'static>(&self) -> Result<&mut VecMap<T>, ECSError> {
        let type_id = TypeId::of::<T>();
        if let Some((_, type_index)) = self.type_masks.get(&type_id) {
            if let Some(components) = self.components.get(*type_index) {
                let components = (&mut *components.as_ptr())
                    .downcast_mut::<VecMap<T>>()
                    .ok_or(ECSError::Downcast)?;
                return Ok(components);
            }
        }
        Err(ECSError::NoComponentMap)
    }
}