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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
/* 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
//!
//! The intention of this crate is that a basic ECS is provided, where
//! you will be required to exercise a little additional control. This is
//! somewhat due to some limitations, and also due to trying to maintain
//! as little overhead as possible - this means no unneccesary copies/clones.
//!
//! Where most other ECS crates provide a mechanism for inserting "systems"
//! in to the ECS to run against entities, this one leaves it out - you can
//! think of it as a "system for entity/components". You will need to create
//! external systems; these can be a function, a loop, or anything else.
//!
//! The basis of 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.
//! For the most part, bitmasks are handled for you, and some helper methods
//! are available to hide their use, but there are also methods to get the
//! bitmask for any ID if you are inclined to do some manual management.
//!
//! # 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 partmaps allocs (they will be equal in size).
//!
//! ```
//! use tiny_ecs::Entities;
//!
//! let mut entities = Entities::new(Some(1000), Some(24));
//! ```
//!
//! ## Demonstrating use
//!
//! ```
//! use tiny_ecs::Entities;
//!
//! // 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,
//! }
//!
//! // Initialize the Entity collection
//! let mut entities = Entities::new(Some(3), Some(3));
//!
//! // To create an entity you only need to add the first part using
//! // a free slot
//! let entity_1 = entities.get_free_slot().unwrap();
//! entities.add_part(entity_1, Vector1 { x: 42 });
//! // And you can add more parts to it
//! // The entity is only considered newly created if no parts existed before
//! entities.add_part(entity_1,
//!                   Vector3 { x: 3,
//!                             y: 10,
//!                             z: -12 });
//!
//! // To add another entity you need another free slot
//! let entity_2 = entities.get_free_slot().unwrap();
//! entities.add_part(entity_2, Vector2 { x: 66, y: 6 });
//! entities.add_part(entity_2, Vector1 { x: 6 });
//!```
//!
//! ## Access an entities part of type `<T>`
//! ```
//! # use tiny_ecs::{Entities, PartMap};
//! # struct Vector3 {x: i32, y: i32, z: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # let entity_1 = entities.get_free_slot().unwrap();
//! # entities.add_part(entity_1, Vector3 { x: 3, y: 10, z: -12 });
//! // To get access to a part belonging to an entity you need
//! // first to get the partmap 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 partmap = entities.get_map_mut::<Vector3>()
//!                   .expect("No part found for entity");
//! // You can then use the part by getting a reference
//! let mut part = partmap.get_part_mut(entity_1).unwrap();
//! assert_eq!(part.z, -12);
//! ```
//!
//! ## Check if `Entity` contains a part type + remove part
//! ```
//! # use tiny_ecs::Entities;
//! # struct Vector1 {x: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # let entity_1 = entities.get_free_slot().unwrap();
//! # entities.add_part(entity_1, Vector1 { x: 3 });
//! // You can check if an entity contains a part with the type signature
//! if entities.entity_contains::<Vector1>(entity_1) {
//!     assert!(entities.rm_part::<Vector1>(entity_1));
//! }
//! assert_eq!(entities.entity_contains::<Vector1>(entity_1), false);
//! ```
//!
//! ## A system that uses an `iter_mut()`
//! ```
//! use std::cell::RefMut;
//! # use tiny_ecs::{Entities, PartMap};
//! # struct Vector1 {x: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # let entity_1 = entities.get_free_slot().unwrap();
//! # entities.add_part(entity_1, Vector1 { x: 3 });
//!
//! // Make a system of some form that takes a `PartMap<T>` arg
//! fn some_system(mut partmap: &mut PartMap<Vector1>) {
//!     // You can then iterate over the parts directly
//!     for (k, v) in partmap.iter_mut() {
//!         v.x += 1;
//!         assert!(v.x > *k as i32);
//!     }
//! }
//! # let mut partmap = entities.get_map_mut::<Vector1>()
//! #                .expect("No part found for entity");
//! some_system(&mut partmap);
//! ```
//!
//! ## Get parts for an entity ID list
//! ```
//! use std::cell::{Ref, RefMut};
//! # use tiny_ecs::{Entities, PartMap};
//! # struct Vector1 {x: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # let entity_1 = entities.get_free_slot().unwrap();
//! # entities.add_part(entity_1, Vector1 { x: 3 });
//!
//! // A system that fetches the parts for only the entities you are require
//! fn second_system(active: &[u32], mut v1_map: &mut PartMap<Vector1>) {
//!     for id in active {
//!         if let Ok(part) = v1_map.get_part_mut(*id) {
//!             part.x = 42;
//!         }
//!     }
//! }
//! # let mut partmap = entities.get_map_mut::<Vector1>()
//! #                .expect("No part found for entity");
//! second_system(&[0, 1, 2], &mut partmap);
//! ```
//!
//! ## A more complex system using PartMaps directly
//! ```
//! # use tiny_ecs::{Entities, PartMap};
//! # struct Vector1 {x: i32 }
//! # struct Vector2 {x: i32, y: i32 }
//! # let mut entities = Entities::new(Some(3), Some(3));
//! # let entity_1 = entities.get_free_slot().unwrap();
//! # entities.add_part(entity_1, Vector1 { x: 3 });
//! # entities.add_part(entity_1, Vector2 { x: 3, y: 3 });
//!
//! // Or a system handles the `Entities` container directly
//! fn other_system(active_ents: &[u32], entities: &mut Entities) {
//!     // You can mutably borrow multiple part types at once
//!     let mut v1_partmap = entities.get_map_mut::<Vector1>()
//!                 .expect("No part found for entity");
//!
//!     let mut v2_partmap = entities.get_map_mut::<Vector2>()
//!                 .expect("No part found for entity");
//!
//!     // But not have a mutable borrow and immutable borrow to the same
//!     // Fails at runtime!
//!     // let v2_partmap = entities.get_map_ref::<Vector2>().unwrap();
//!     // But you can have multiple immutable references to the same part
//!     for id in active_ents {
//!         if entities.entity_contains::<Vector1>(*id) &&
//!            entities.entity_contains::<Vector2>(*id) {
//!             let v1_part = v1_partmap.get_part_mut(*id).unwrap();
//!             let v2_part = v2_partmap.get_part_mut(*id).unwrap();
//!             v1_part.x = 42;
//!             assert_ne!(v1_part.x, 43);
//!             assert_eq!(v1_part.x, 42);
//!         }
//!     }
//! }
//! other_system(&[0, 1, 2], &mut entities);
//! ```

use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell, RefMut};
use std::collections::hash_map::{Iter, IterMut};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fmt::{Debug, Display};
use std::ops::{Deref, DerefMut};

pub enum ECSError {
    Borrow,
    BorrowMut,
    Downcast,
    DowncastMut,
    PtrRef,
    PtrMut,
    NoPartMap,
}

impl Debug for ECSError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(self.description(), f)
    }
}

impl Display for ECSError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(self.description(), f)
    }
}

impl Error for ECSError {
    fn description(&self) -> &str {
        match self {
            ECSError::Borrow => "already borrowed",
            ECSError::BorrowMut => "already mutably borrowed",
            ECSError::Downcast => "could not downcast to ref",
            ECSError::DowncastMut => "could not downcast to mut ref",
            ECSError::PtrRef => "failed to convert pointer to ref",
            ECSError::PtrMut => "failed to convert pointer to mut",
            ECSError::NoPartMap => "no part map for part type",
        }
    }
}

pub struct PartMapRef<'a, T> {
    _borrow: Ref<'a, Any>,
    value: &'a PartMap<T>,
}

impl<'a, T: 'static> PartMapRef<'a, T> {
    pub fn new(value: &'a RefCell<Box<Any>>) -> Result<PartMapRef<'a, T>, ECSError> {
        let v = (unsafe { value.as_ptr().as_ref().ok_or(ECSError::PtrMut)? })
            .downcast_ref::<PartMap<T>>()
            .ok_or(ECSError::Downcast)?;

        Ok(PartMapRef {
            value: v,
            _borrow: value.try_borrow().or(Err(ECSError::Borrow))?,
        })
    }
}

impl<'a, T> Deref for PartMapRef<'a, T> {
    type Target = PartMap<T>;

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

pub struct PartMapMut<'a, T> {
    _borrow: RefMut<'a, Any>,
    value: &'a mut PartMap<T>,
}

impl<'a, T: 'static> PartMapMut<'a, T> {
    pub fn new(value: &'a RefCell<Box<Any>>) -> Result<PartMapMut<'a, T>, ECSError> {
        let v = (unsafe { value.as_ptr().as_mut().ok_or(ECSError::PtrMut)? })
            .downcast_mut::<PartMap<T>>()
            .ok_or(ECSError::Downcast)?;

        Ok(PartMapMut {
            value: v,
            _borrow: value.try_borrow_mut().or(Err(ECSError::BorrowMut))?,
        })
    }
}

impl<'a, T> Deref for PartMapMut<'a, T> {
    type Target = PartMap<T>;

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

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

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

/// `PartMap` is a container type for the parts used by entities
pub struct PartMap<T> {
    map: HashMap<u32, T>,
}

impl<T> PartMap<T> {
    #[inline(always)]
    fn new(init_size: usize) -> PartMap<T> {
        PartMap {
            map: HashMap::with_capacity(init_size),
        }
    }

    #[inline(always)]
    fn insert(&mut self, id: u32, part: T) {
        self.map.insert(id, part);
    }

    #[inline(always)]
    fn remove(&mut self, id: u32) {
        self.map.remove(&id);
    }

    #[inline(always)]
    pub fn get_part_ref(&self, id: u32) -> Result<&T, &'static str> {
        if let Some(part) = self.map.get(&id) {
            return Ok(part);
        }
        Err("could find requested entity part")
    }

    /// Getting a reference to an entity part requires the entity ID and
    /// type signature. The type signature is required so that the internal
    /// downcast can be done for you.
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::{Entities, PartMap};
    /// #[derive(Debug, PartialEq)]
    /// struct Test1 {}
    ///
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.get_free_slot().unwrap();
    /// # entities.add_part(entity_1, Test1 {});
    /// let partmap = entities.get_map_ref::<Test1>()
    ///         .expect("No part found for entity");
    /// let part = partmap.get_part_ref(entity_1).unwrap();
    /// assert_eq!(part, &Test1 {});
    /// // or
    /// let part = partmap.get_part_ref(entity_1).unwrap();
    /// assert_eq!(part, &Test1 {});
    /// ```
    #[inline(always)]
    pub fn get_part_mut(&mut self, id: u32) -> Result<&mut T, &'static str> {
        if let Some(part) = self.map.get_mut(&id) {
            return Ok(part);
        }
        Err("could find requested entity part")
    }

    /// Returns an immutable iterator over the part map
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::{Entities, PartMap};
    /// # struct Test1 { x: u32, }
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let id = entities.get_free_slot().unwrap();
    /// # entities.add_part(id, Test1 { x: id });
    ///
    /// let partmap = entities.get_map_ref::<Test1>()
    ///         .expect("No part found for entity");
    /// for (k, v) in partmap.iter_ref() {
    ///     assert!(v.x == *k);
    /// }

    /// ```
    #[inline(always)]
    pub fn iter_ref(&self) -> Iter<u32, T> {
        return self.map.iter();
    }

    /// Returns a mutable iterator over the part map
    #[inline(always)]
    pub fn iter_mut(&mut self) -> IterMut<u32, T> {
        return self.map.iter_mut();
    }
}

/// This is the root of the ECS implementation
pub struct Entities {
    entity_masks: Vec<u32>,
    parts: HashMap<u32, RefCell<Box<Any>>>,
    next_free_entity: u32,
    type_masks: HashMap<TypeId, u32>,
    next_typemask: u32,
}

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
    ///   part 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.
    /// - `part_count` is as above, for total part types/kinds.
    pub fn new(entity_count: Option<usize>, part_count: Option<usize>) -> Entities {
        Entities {
            entity_masks: vec![EMPTY; entity_count.unwrap_or(0)],
            parts: HashMap::with_capacity(part_count.unwrap_or(0)),
            next_free_entity: 0,
            type_masks: HashMap::with_capacity(part_count.unwrap_or(0)),
            next_typemask: 1,
        }
    }

    /// Find the first `EMPTY` ID number to use
    ///
    /// As entities are only created by actually inserting new parts in to
    /// the Entity structure, this should be called to find the first
    /// available entity slot. Slot states are determined by the mask
    /// it holds.
    #[inline]
    pub fn get_free_slot(&mut self) -> Result<u32, &'static str> {
        if self.next_free_entity >= self.entity_masks.len() as u32 {
            self.entity_masks.push(EMPTY);
        }
        for index in 0..=self.next_free_entity {
            if self.entity_masks[index as usize] == EMPTY {
                if index >= self.next_free_entity {
                    self.next_free_entity += 1;
                }
                return Ok(index);
            }
        }
        Err("no free entity slots")
    }

    /// Returns the mask of the requested entity enabling you to manually
    /// check composition using bitmasks.
    #[inline]
    pub fn get_entity_mask(&self, id: u32) -> u32 {
        self.entity_masks[id as usize]
    }

    /// Returns the mask associated with the requested type.
    #[inline]
    pub fn get_type_mask<T: 'static>(&self) -> Result<u32, &'static str> {
        if let Some(mask) = self.type_masks.get(&TypeId::of::<T>()) {
            return Ok(*mask);
        }
        Err("requested non-existant mask for type")
    }

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

    /// Adding a part requires a valid slot along with the initialised data
    /// to use with the entity. Effectively creates the entity if the slot is
    /// currently empty.
    ///
    /// A bitmask is created internally for each data type added (only one per type).
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::Entities;
    /// struct Test1 {}
    /// const TEST1: u32 = 1 << 2;
    ///
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// let entity_1 = entities.get_free_slot().unwrap();
    /// entities.add_part(entity_1, Test1 {});
    /// ```
    #[inline]
    pub fn add_part<T: 'static>(&mut self, id: u32, part: T) {
        let tid = TypeId::of::<T>();
        if !self.type_masks.contains_key(&tid) {
            self.type_masks.insert(tid, self.next_typemask);
            let mask = self.next_typemask << 1;
            self.next_typemask = mask;
        }
        let type_mask = self.type_masks[&tid];
        // add HashMap for these parts if not exist
        self.parts
            .entry(type_mask)
            .or_insert(RefCell::new(Box::new(PartMap::<T>::new(
                self.entity_masks.len(),
            ))));

        if let Some(col) = self.parts.get_mut(&type_mask) {
            col.borrow_mut()
                .downcast_mut::<PartMap<T>>()
                .unwrap()
                .insert(id, part);
            let old = self.entity_masks[id as usize];
            self.entity_masks[id as usize] = old | type_mask;
        }
    }

    /// Remove an entities part. If no parts are left after part removal then
    /// the entity is considered deleted and an `EMPTY` (0) mask is inserted in
    /// its place.
    ///
    /// Removal requires the ID of the entity and the parts type signature.
    ///
    /// # Example
    ///
    /// ```
    /// # use tiny_ecs::{Entities, EMPTY};
    /// #[derive(Debug, PartialEq)]
    /// struct Test1 {}
    ///
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.get_free_slot().unwrap();
    /// # entities.add_part(entity_1, Test1 {});
    /// assert!(entities.rm_part::<Test1>(entity_1));
    /// assert_eq!(entities.get_entity_mask(entity_1), EMPTY);
    /// ```
    #[inline]
    pub fn rm_part<T: 'static>(&mut self, id: u32) -> bool {
        let type_mask = self.type_masks[&TypeId::of::<T>()];
        if let Some(map) = self.parts.get_mut(&type_mask) {
            map.borrow_mut()
                .downcast_mut::<PartMap<T>>()
                .unwrap()
                .remove(id);
            self.entity_masks[id as usize] ^= type_mask;
            return true;
        }
        false
    }

    /// Get a plain reference to the selected entity part map
    ///
    /// You may have multiple immutable references to the requested `PartMap`
    /// **type** but no mutable references if the same **typed** `PartMap`
    /// 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, PartMap};
    /// # struct Test1 { x: u32 }
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.get_free_slot().unwrap();
    /// # entities.add_part(entity_1, Test1 { x: 666 });
    /// let partmap = entities.get_map_ref::<Test1>()
    ///         .expect("No part found for entity");
    /// let part = partmap.get_part_ref(entity_1).unwrap();
    /// ```
    #[inline(always)]
    pub fn get_map_ref<T: 'static>(&self) -> Result<PartMapRef<T>, ECSError> {
        if let Some(type_mask) = self.type_masks.get(&TypeId::of::<T>()) {
            if let Some(partmap) = self.parts.get(&type_mask) {
                let x: PartMapRef<T> = PartMapRef::new(partmap)?;
                return Ok(x);
            }
        }
        Err(ECSError::NoPartMap)
    }

    /// Get a mutable reference to the selected entity part map
    ///
    /// You may have only one mutable reference to the requested `PartMap`
    /// **type** and no immutable references. You can however, have multiple
    /// mutable references to different **types** of `PartMap`
    ///
    /// - `Option` is whether or not there is a part of `<T>` for that entity.
    /// - `Result` covers if the map was able to be borrowed mutably or not.
    /// - Borrowing is checked at runtime.
    ///
    /// # Example
    /// ```
    /// # use tiny_ecs::{Entities, PartMap};
    /// # #[derive(Debug, PartialEq)]
    /// # struct Test1 { x: u32 }
    /// # let mut entities = Entities::new(Some(3), Some(3));
    /// # let entity_1 = entities.get_free_slot().unwrap();
    /// # entities.add_part(entity_1, Test1 { x: 0 });
    /// // 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 partmap = entities.get_map_mut::<Test1>()
    ///             .expect("No part found for entity");
    ///     for id in 0..5 {
    ///         if let Ok(part) = partmap.get_part_mut(id) {
    ///             part.x = 42;
    ///         }
    ///     }
    /// }
    ///
    /// // Now get a ref to the modified part
    /// let partmap = entities.get_map_ref::<Test1>()
    ///         .expect("No part found for entity");
    /// let part = partmap.get_part_ref(entity_1).unwrap();
    /// assert_eq!(part.x, 42);
    /// ```
    #[inline(always)]
    pub fn get_map_mut<T: 'static>(&self) -> Result<PartMapMut<T>, ECSError> {
        if let Some(type_mask) = self.type_masks.get(&TypeId::of::<T>()) {
            if let Some(partmap) = self.parts.get(&type_mask) {
                let x = PartMapMut::new(partmap)?;
                return Ok(x);
            }
        }
        Err(ECSError::NoPartMap)
    }
}

#[cfg(test)]
mod tests {
    use crate::Entities;

    #[test]
    fn add_entity_and_part_check_contains_and_mask() {
        struct Test1 {}
        struct Test2 {}
        struct Test3 {}

        let mut entities = Entities::new(Some(3), Some(3));
        // Creating a new entity should find the next free slot
        // and then insert a new blank bitmask
        // Return entity number
        let entity_1 = entities.get_free_slot().unwrap();
        assert_eq!(entity_1, 0);

        entities.add_part(entity_1, Test1 {});

        let entity_1_mask = entities.get_entity_mask(entity_1);
        // The mask for this entity should have been updated
        let type_mask = entities.get_type_mask::<Test1>().unwrap();
        assert_eq!(entity_1_mask, type_mask);
        assert!(entities.entity_contains::<Test1>(entity_1));
        assert!(!entities.entity_contains::<Test2>(entity_1));

        entities.add_part(entity_1, Test3 {});
        assert!(entities.entity_contains::<Test3>(entity_1));

        // should increment entities.next_free_entity
        let e2 = entities.get_free_slot().unwrap();
        assert_eq!(e2, 1);
    }

    #[test]
    fn get_part_map_for_type_as_ref() {
        struct Test1 {}

        let mut entities = Entities::new(Some(3), Some(3));
        // Should return None
        {
            let m = entities.get_map_ref::<Test1>();
            assert!(m.is_err());
        }

        let entity_1 = entities.get_free_slot().unwrap();
        entities.add_part(entity_1, Test1 {});
        // Should return the HashMap
        let map = entities.get_map_ref::<Test1>();
        assert!(map.is_ok());

        let map = entities.get_map_ref::<Test1>().unwrap();
        assert!(map.get_part_ref(entity_1).is_ok());
    }

    #[test]
    fn get_part_map_for_type_as_mut() {
        struct Test1 {}

        let mut entities = Entities::new(Some(3), Some(3));
        // Should return None
        {
            let m = entities.get_map_mut::<Test1>();
            assert!(m.is_err());
        }

        let entity_1 = entities.get_free_slot().unwrap();
        entities.add_part(entity_1, Test1 {});
        // Should return the HashMap

        let map = entities.get_map_mut::<Test1>();
        assert!(map.is_ok());

        let mut map = map.unwrap();
        assert!(map.get_part_mut(entity_1).is_ok());
    }

    #[test]
    fn partmap_ref_and_mut_diff_parts_and_modify() {
        #[derive(Debug, PartialEq)]
        struct Test1 {
            x: u32,
        }

        #[derive(Debug, PartialEq)]
        struct Test2 {
            x: u32,
        }

        let mut entities = Entities::new(Some(3), Some(3));
        let entity_1 = entities.get_free_slot().unwrap();
        entities.add_part(entity_1, Test1 { x: 66 });
        entities.add_part(entity_1, Test2 { x: 42 });

        let partmap = entities.get_map_ref::<Test1>().unwrap();
        let part = partmap.get_part_ref(entity_1).unwrap();
        assert_eq!(part, &Test1 { x: 66 });
        assert!(entities.entity_contains::<Test1>(entity_1));

        {
            let mut partmap = entities.get_map_mut::<Test2>().unwrap();
            let part = partmap.get_part_mut(entity_1).unwrap();
            assert_eq!(part.x, 42);
            part.x = 666;
            assert_ne!(part.x, 42);
        }
        let mut _p = entities.get_map_mut::<Test2>().unwrap();
        assert!(entities.get_map_mut::<Test2>().is_err());
    }

    #[test]
    fn partmap_iter_ref() {
        struct Test1 {
            x: u32,
        }

        let mut entities = Entities::new(Some(3), Some(3));
        let mut ids = Vec::new();
        // 1
        let id = entities.get_free_slot().unwrap();
        entities.add_part(id, Test1 { x: id });
        ids.push(id);
        // 2
        let id = entities.get_free_slot().unwrap();
        entities.add_part(id, Test1 { x: id });
        ids.push(id);
        // 3
        let id = entities.get_free_slot().unwrap();
        entities.add_part(id, Test1 { x: id });
        ids.push(id);

        let partmap = entities.get_map_ref::<Test1>().unwrap();
        for (k, v) in partmap.iter_ref() {
            assert!(v.x == *k);
        }
    }

    #[test]
    fn partmap_iter_mut() {
        struct Test1 {
            x: u32,
        }

        let mut entities = Entities::new(Some(3), Some(3));
        let mut ids = Vec::new();
        // 1
        let id = entities.get_free_slot().unwrap();
        entities.add_part(id, Test1 { x: id });
        ids.push(id);
        // 2
        let id = entities.get_free_slot().unwrap();
        entities.add_part(id, Test1 { x: id });
        ids.push(id);
        // 3
        let id = entities.get_free_slot().unwrap();
        entities.add_part(id, Test1 { x: id });
        ids.push(id);

        let mut partmap = entities.get_map_mut::<Test1>().unwrap();
        for (k, v) in partmap.iter_mut() {
            v.x += 1;
            assert!(v.x > *k);
        }
    }

    #[test]
    fn remove_parts_then_entity() {
        #[derive(Debug, PartialEq)]
        struct Test1 {}

        #[derive(Debug, PartialEq)]
        struct Test2 {
            x: u32,
        }

        let mut entities = Entities::new(Some(3), Some(3));
        let entity_1 = entities.get_free_slot().unwrap();
        entities.add_part(entity_1, Test1 {});
        entities.add_part(entity_1, Test2 { x: 42 });

        // rm and check entity components
        assert!(entities.entity_contains::<Test1>(entity_1));
        assert!(entities.rm_part::<Test1>(entity_1));
        assert!(!entities.entity_contains::<Test1>(entity_1));
        assert!(entities.entity_contains::<Test2>(entity_1));

        // check masks
        let type_mask_2 = entities.get_type_mask::<Test2>().unwrap();
        assert_eq!(entities.get_entity_mask(entity_1), type_mask_2);

        // Removing all parts erases the entity
        assert!(entities.rm_part::<Test2>(entity_1));
        assert_eq!(entities.get_entity_mask(entity_1), 0);
    }
}