akashi 0.5.2

A framework for building collectible card games and gacha games.
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
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! Akashi's storage system for [`Entities`](Entity).

use std::any;
use std::fmt;
use std::ops::Deref;
use std::sync::{Arc, Weak};

extern crate stable_deref_trait;
use stable_deref_trait::CloneStableDeref;

use dashmap::DashMap;
use downcast_rs::{Downcast, DowncastSync};
use parking_lot::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};

use super::{ComponentManager, Entity};
use crate::snowflake::Snowflake;
use crate::util::Result;

rental! {
    pub mod handle_ref {
        //! Self-referential wrappers around shared locks.
        use super::*;

        /// A self-referential type that wraps `Arc<RwLock<StoreHandle>>`
        /// into a read-locked immutable reference.
        ///
        /// This struct effectively contains an `Arc` pointing to an
        /// `RwLock` and a read guard for that same lock.
        ///
        /// It also supports `Deref` to the inner StoreHandle, which is
        /// usually all you'll need.
        #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")]
        pub struct HandleReadRef<H: CloneStableDeref + Deref + 'static, T: 'static> {
            head: H,
            suffix: RwLockReadGuard<'head, T>,
        }

        /// A self-referential type that wraps `Arc<RwLock<StoreHandle>>`
        /// into a write-locked mutable reference.
        ///
        /// This struct effectively contains an `Arc` pointing to an
        /// `RwLock` and a write guard for that same lock.
        ///
        /// It also supports `Deref` and `DerefMut` to the inner
        /// StoreHandle, which is usually all you'll need.
        #[rental(debug, clone, deref_mut_suffix, covariant, map_suffix = "T")]
        pub struct HandleWriteRef<H: CloneStableDeref + Deref + 'static, T: 'static> {
            head: H,
            suffix: RwLockWriteGuard<'head, T>,
        }
    }
}

pub use handle_ref::{HandleReadRef, HandleWriteRef};

pub type StoreReference<T> = Arc<RwLock<T>>;
type WeakStoreReference<T> = Weak<RwLock<T>>;
pub type ReadReference<T> = HandleReadRef<StoreReference<T>, T>;
pub type WriteReference<T> = HandleWriteRef<StoreReference<T>, T>;

/// Converts `Arc<RwLock<T>>` to a [`ReadReference`] by taking the inner read lock.
pub fn read_store_reference<T: 'static>(head: StoreReference<T>) -> ReadReference<T> {
    HandleReadRef::new(head, |s| s.read())
}

/// Converts `Arc<RwLock<T>>` to a [`WriteReference`] by locking the inner write lock.
pub fn write_store_reference<T: 'static>(head: StoreReference<T>) -> WriteReference<T> {
    HandleWriteRef::new(head, |s| s.write())
}

/// This is a trait for wrapping up objects that contain stores for
/// multiple types of [`Entity`].
pub trait SharedStore<T, U>
where
    T: Entity + 'static,
    U: EntityBackend<T> + Sync + Send + 'static,
{
    fn get_store<'a>(&'a self) -> &'a Store<T, U>;
}

/// A shared handle to an [`Entity`] and its storage backend.
///
/// # Errors
///
/// Most of the methods associated with `StoreHandle` call methods on
/// storage backend objects. Errors returned by these methods will bubble up
/// through `StoreHandle`'s methods.
pub struct StoreHandle<T>
where
    T: Entity + 'static,
{
    backend: Arc<dyn EntityBackend<T> + Sync + Send + 'static>,
    id: Snowflake,
    object: Option<T>,
}

impl<T> StoreHandle<T>
where
    T: Entity + 'static,
{
    fn new<U>(backend: Arc<U>, id: Snowflake, object: Option<T>) -> StoreHandle<T>
    where
        U: EntityBackend<T> + Sync + Send + 'static,
    {
        StoreHandle {
            backend,
            id,
            object,
        }
    }

    /// Gets a reference to the object within this handle.
    pub fn get(&self) -> Option<&T> {
        self.object.as_ref()
    }

    /// Gets a mutable reference to the object within this handle.
    pub fn get_mut(&mut self) -> Option<&mut T> {
        self.object.as_mut()
    }

    /// Replaces the object within this handle with something else.
    pub fn replace(&mut self, object: T) -> Option<T> {
        self.object.replace(object)
    }

    /// Gets the ID of the [`Entity`] in this handle.
    pub fn id(&self) -> Snowflake {
        self.id
    }

    /// Checks whether anything is actually contained in this handle.
    pub fn exists(&self) -> bool {
        self.object.is_some()
    }

    /// Puts whatever is in this handle into storage.
    pub fn store(&self) -> Result<()> {
        match &self.object {
            None => self.backend.delete(self.id),
            Some(obj) => self.backend.store(self.id, &obj),
        }
    }

    /// Clears out the data in this handle, then deletes the [`Entity`]
    /// from storage.
    pub fn delete(&mut self) -> Result<()> {
        if let Some(obj) = &mut self.object {
            obj.clear_components()?;
        }

        self.object = None;
        self.backend.delete(self.id)
    }

    fn set_object(&mut self, object: Option<T>) {
        self.object = object;
    }
}

impl<T> Drop for StoreHandle<T>
where
    T: Entity + 'static,
{
    fn drop(&mut self) {
        if let Some(entity) = &self.object {
            if entity.dirty() {
                // No good way of handling errors here
                let _e = self.backend.store(self.id, &entity);
            }
        }
    }
}

#[doc(hidden)]
#[derive(Clone)]
pub struct StoredHandleData<T>
where
    T: Entity + 'static,
{
    initializer: Arc<Once>,
    handle: WeakStoreReference<StoreHandle<T>>,
}

// Strong version of StoredHandleData
#[doc(hidden)]
#[derive(Clone)]
pub struct HandleData<T>
where
    T: Entity + 'static,
{
    initializer: Arc<Once>,
    handle: StoreReference<StoreHandle<T>>,
}

/// Handles storing [`Entities`](Entity) and coordinating access to
/// them across multiple threads.
///
/// # Errors
///
/// Most of the methods associated with `Store` call methods on storage
/// backend objects. Errors returned by these methods will bubble up
/// through `Store`'s methods.
pub struct Store<T, U>
where
    T: Entity + 'static,
    U: EntityBackend<T> + Sync + Send + 'static,
{
    backend: Arc<U>,
    refs: DashMap<Snowflake, StoredHandleData<T>>,
}

impl<T, U> Store<T, U>
where
    T: Entity + 'static,
    U: EntityBackend<T> + Sync + Send + 'static,
{
    /// Creates a new `Store` using the given storage backend.
    pub fn new(backend: Arc<U>) -> Store<T, U> {
        Store {
            backend,
            refs: DashMap::new(),
        }
    }

    /// Retrieves or creates a possibly-uninitialized [`StoreHandle`] from
    /// the underlying hashmap.
    fn get_handle(&self, id: Snowflake) -> HandleData<T> {
        let mut entry = self.refs.entry(id).or_insert_with(|| StoredHandleData {
            initializer: Arc::new(Once::new()),
            handle: Weak::new(),
        });

        if let Some(strong) = entry.handle.upgrade() {
            HandleData {
                initializer: entry.initializer.clone(),
                handle: strong,
            }
        } else {
            let handle: StoreHandle<T> = StoreHandle::new(self.backend.clone(), id, None);
            let initializer = Arc::new(Once::new());
            let strong = Arc::new(RwLock::new(handle));

            entry.handle = Arc::downgrade(&strong);
            entry.initializer = initializer.clone();

            HandleData {
                initializer,
                handle: strong,
            }
        }
    }

    // Initializes a handle by loading data from the backend.
    // Uses the `initializer` contained in the handle_data to ensure
    // that only one thread tries to initialize at once.
    fn initialize_handle(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
        handle_data: HandleData<T>,
    ) -> Result<HandleData<T>> {
        let mut res: Result<()> = Result::Ok(());

        handle_data.initializer.call_once(|| {
            let mut write_handle = handle_data.handle.write();
            match self.backend.load(id, cm) {
                Err(e) => {
                    res = Err(e);
                    write_handle.set_object(None);
                }
                Ok(data) => {
                    write_handle.set_object(data);
                }
            };
        });

        match res {
            Err(e) => Err(e),
            Ok(_v) => Ok(handle_data),
        }
    }

    pub fn load_handle(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<StoreReference<StoreHandle<T>>> {
        let handle_data = self.initialize_handle(id, cm, self.get_handle(id))?;
        Ok(handle_data.handle.clone())
    }

    /// Gets an immutable reference to the handle for the [`Entity`]
    /// with the given ID.
    ///
    /// Data for the [`Entity`] will be loaded from storage if needed.
    ///
    /// The returned reference is read-locked, so multiple threads can
    /// use references from this function at once.
    pub fn load(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<ReadReference<StoreHandle<T>>> {
        let handle_data = self.initialize_handle(id, cm, self.get_handle(id))?;
        Ok(read_store_reference(handle_data.handle))
    }

    /// Gets a mutable reference to the handle for the [`Entity`] with
    /// the given ID.
    ///
    /// Data for the [`Entity`] will be loaded from storage if needed.
    ///
    /// The returned reference is write-locked, so exclusive access to
    /// the handle is ensured.
    pub fn load_mut(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<WriteReference<StoreHandle<T>>> {
        let handle_data = self.initialize_handle(id, cm, self.get_handle(id))?;
        Ok(write_store_reference(handle_data.handle))
    }

    /// Puts the given [`Entity`] into storage, overwriting any previously
    /// stored [`Entity`] data with the same ID.
    pub fn store(&self, object: T) -> Result<()> {
        let id = object.id();
        let handle_data = self.get_handle(id);

        // If the initializer gets called, `object` gets set to None,
        // and initializer_result is filled in with the result value.
        //
        // If the initializer is _not_ called, `object` remains as Some(object),
        // and initializer_result is None.
        let mut object: Option<T> = Some(object);
        let mut initializer_result: Option<Result<()>> = None;

        handle_data.initializer.call_once(|| {
            let mut handle = handle_data.handle.write();
            handle.set_object(object.take());
            initializer_result = Some(handle.store());
        });

        if let Some(obj) = object {
            let mut handle = handle_data.handle.write();
            handle.set_object(Some(obj));
            handle.store()
        } else {
            // This should be safe, because in the initializer,
            // object.take() is immediately followed by setting
            // initializer_result to some result.
            initializer_result.unwrap()
        }
    }

    /// Moves the given [`Entity`] into a store handle without writing
    /// it to storage, overwriting anything that may have been there before.
    ///
    /// Returns a write-locked reference to the handle.
    pub fn insert(&self, object: T) -> WriteReference<StoreHandle<T>> {
        let id = object.id();
        let handle_data = self.get_handle(id);

        // If the initializer gets called, `object` gets set to None,
        // and initializer_result is filled in with the result value.
        //
        // If the initializer is _not_ called, `object` remains as Some(object),
        // and initializer_result is None.
        let mut object: Option<T> = Some(object);
        let mut initializer_result: Option<WriteReference<StoreHandle<T>>> = None;

        handle_data.initializer.call_once(|| {
            let mut handle = write_store_reference(handle_data.handle.clone());
            handle.set_object(object.take());
            initializer_result = Some(handle);
        });

        if let Some(obj) = object {
            let mut ret = write_store_reference(handle_data.handle.clone());
            ret.set_object(Some(obj));
            ret
        } else {
            // This should be safe, because in the initializer,
            // object.take() is immediately followed by setting
            // initializer_result to some result.
            initializer_result.unwrap()
        }
    }

    /// Deletes the [`Entity`] with the given ID from storage.
    ///
    /// Note that internally, this method loads the [`Entity`] prior to
    /// deleting it, so that attached [`Components`](crate::Component) are
    /// properly deleted.
    ///
    /// If you already have an open handle to the [`Entity`], you should
    /// use [`StoreHandle::delete`] instead.
    pub fn delete(&self, id: Snowflake, cm: Arc<ComponentManager<T>>) -> Result<()> {
        let mut handle = self.load_mut(id, cm)?;
        handle.delete()
    }

    /// Checks to see if an [`Entity`] with the given ID exists.
    pub fn exists(&self, id: Snowflake) -> Result<bool> {
        let handle_data = self.get_handle(id);

        if handle_data.initializer.state().done() {
            let read_lock = handle_data.handle.read();
            Ok(read_lock.exists())
        } else {
            self.backend.exists(id)
        }
    }

    /// Retrieves a list of [`Entity`] IDs from storage.
    pub fn keys(&self, page: u64, limit: u64) -> Result<Vec<Snowflake>> {
        self.backend.keys(page, limit)
    }
}

/// Used as a 'stepping stone' when downcasting from an `EntityStoreDowncast`
/// trait object to an `EntityStore<T>`.
///
/// We can't downcast directly between two trait objects, so we need to
/// add an intermediate concrete type that `EntityStoreDowncast` can be
/// downcasted to, and from which we can further downcast to `EntityStore`.
#[doc(hidden)]
pub struct EntityStoreDowncastHelper<T: Entity + 'static>(pub Box<dyn EntityStore<T> + 'static>);

/// A downcastable trait that allows for erasing the [`Entity`] type parameter
/// from [`EntityStore`] trait objects.
///
/// You probably shouldn't use this yourself.
#[doc(hidden)]
pub trait EntityStoreDowncast: Downcast + Send + Sync + 'static {}
downcast_rs::impl_downcast!(EntityStoreDowncast);

impl<T: Entity + 'static> EntityStoreDowncast for EntityStoreDowncastHelper<T> {}

/// An interface for loading and storing [`Entities`](Entity).
///
/// This trait provides an abstract interface for loading and storing
/// [`Entities`](Entity) objects.
///
/// For example, you can use it as a way to access [`Stores`](Store)
/// without having to carry around a [`EntityBackend`](EntityBackend)
/// type parameter everywhere. This comes at the cost of dynamic dispatch
/// overhead, though.
pub trait EntityStore<T>: DowncastSync
where
    T: Entity + 'static,
{
    fn load(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<ReadReference<StoreHandle<T>>>;

    fn load_mut(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<WriteReference<StoreHandle<T>>>;

    fn store(&self, object: T) -> Result<()>;
    fn insert(&self, object: T) -> WriteReference<StoreHandle<T>>;
    fn delete(&self, id: Snowflake, cm: Arc<ComponentManager<T>>) -> Result<()>;
    fn exists(&self, id: Snowflake) -> Result<bool>;
    fn keys(&self, page: u64, limit: u64) -> Result<Vec<Snowflake>>;
}

downcast_rs::impl_downcast!(sync EntityStore<T> where T: Entity + 'static);

impl<T, U> EntityStore<T> for Store<T, U>
where
    T: Entity + 'static,
    U: EntityBackend<T> + Sync + Send + 'static,
{
    fn load(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<ReadReference<StoreHandle<T>>> {
        self.load(id, cm)
    }

    fn load_mut(
        &self,
        id: Snowflake,
        cm: Arc<ComponentManager<T>>,
    ) -> Result<WriteReference<StoreHandle<T>>> {
        self.load_mut(id, cm)
    }

    fn store(&self, object: T) -> Result<()> {
        self.store(object)
    }

    fn insert(&self, object: T) -> WriteReference<StoreHandle<T>> {
        self.insert(object)
    }

    fn delete(&self, id: Snowflake, cm: Arc<ComponentManager<T>>) -> Result<()> {
        self.delete(id, cm)
    }

    fn exists(&self, id: Snowflake) -> Result<bool> {
        self.exists(id)
    }

    fn keys(&self, page: u64, limit: u64) -> Result<Vec<Snowflake>> {
        self.keys(page, limit)
    }
}

impl<T, U> fmt::Debug for Store<T, U>
where
    T: Entity + 'static,
    U: EntityBackend<T> + Sync + Send + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Store<{}, {}> {{ {} keys }}",
            any::type_name::<T>(),
            any::type_name::<U>(),
            self.refs.len()
        )
    }
}

/// This trait is used to mark backing storage objects for [`Entities`](Entity).
///
/// Structs that implement this trait can be used as backing storage
/// for [`Entities`](Entity) such as [`Players`](crate::Player) and
/// [`Cards`](crate::Card), and can be passed to [`Store::new`].
pub trait EntityBackend<T: Entity + 'static> {
    /// Loads data for an [`Entity`] from storage, if any [`Entity`] with
    /// the given ID exists.
    fn load(&self, id: Snowflake, cm: Arc<ComponentManager<T>>) -> Result<Option<T>>;

    /// Checks to see if an [`Entity`] with the given ID exists in storage.
    fn exists(&self, id: Snowflake) -> Result<bool>;

    /// Saves data for an [`Entity`] to storage.
    fn store(&self, id: Snowflake, object: &T) -> Result<()>;

    /// Deletes data for an [`Entity`] from storage.
    fn delete(&self, id: Snowflake) -> Result<()>;

    /// Retrieve a list of [`Entity`] IDs from storage.
    fn keys(&self, page: u64, limit: u64) -> Result<Vec<Snowflake>>;
}

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

    use std::any::TypeId;
    use std::collections::{HashMap, HashSet};
    use std::sync::{mpsc, Arc, Barrier, RwLock};
    use std::thread;

    use dashmap::DashMap;

    use crate::ecs::Component;
    use crate::snowflake::SnowflakeGenerator;

    struct MockStoredData {
        id: Snowflake,
        field_a: String,
        field_b: u64,
        cm: Arc<ComponentManager<MockStoredData>>,
        components_attached: HashSet<TypeId>,
        component_preloads: DashMap<TypeId, Box<dyn Component<Self> + Send + Sync + 'static>>,
        dirty: bool,
    }

    impl MockStoredData {
        fn new(
            id: Snowflake,
            field_a: String,
            field_b: u64,
            cm: Arc<ComponentManager<MockStoredData>>,
        ) -> MockStoredData {
            MockStoredData {
                id,
                field_a,
                field_b,
                cm,
                components_attached: HashSet::new(),
                component_preloads: DashMap::new(),
                dirty: false,
            }
        }

        fn id<'a>(&'a self) -> &'a Snowflake {
            &self.id
        }
    }

    impl Entity for MockStoredData {
        fn new(
            id: Snowflake,
            cm: Arc<ComponentManager<Self>>,
            _components: HashSet<TypeId>,
        ) -> Self {
            MockStoredData::new(id, String::from(""), 0, cm)
        }

        fn id(&self) -> Snowflake {
            self.id
        }

        fn component_manager(&self) -> &ComponentManager<MockStoredData> {
            &self.cm
        }

        fn components_attached(&self) -> &HashSet<TypeId> {
            &self.components_attached
        }

        fn components_attached_mut(&mut self) -> &mut HashSet<TypeId> {
            &mut self.components_attached
        }

        fn preloaded_components(
            &self,
        ) -> &DashMap<TypeId, Box<dyn Component<Self> + Send + Sync + 'static>> {
            &self.component_preloads
        }

        fn dirty(&self) -> bool {
            self.dirty
        }

        fn dirty_mut(&mut self) -> &mut bool {
            &mut self.dirty
        }
    }

    impl Clone for MockStoredData {
        fn clone(&self) -> Self {
            Self {
                id: self.id,
                dirty: self.dirty,
                cm: self.cm.clone(),
                components_attached: self.components_attached.clone(),
                component_preloads: DashMap::new(),
                field_a: self.field_a.clone(),
                field_b: self.field_b,
            }
        }
    }

    struct MockEntityBackend {
        data: RwLock<HashMap<Snowflake, MockStoredData>>,
        remove_on_load: bool,
    }

    impl MockEntityBackend {
        fn new() -> MockEntityBackend {
            MockEntityBackend {
                data: RwLock::new(HashMap::new()),
                remove_on_load: false,
            }
        }

        fn set_remove_on_load(&mut self, flag: bool) {
            self.remove_on_load = flag;
        }
    }
    impl EntityBackend<MockStoredData> for MockEntityBackend {
        fn exists(&self, id: Snowflake) -> Result<bool> {
            let map = self.data.read().unwrap();
            Ok(map.contains_key(&id))
        }

        fn load(
            &self,
            id: Snowflake,
            _cm: Arc<ComponentManager<MockStoredData>>,
        ) -> Result<Option<MockStoredData>> {
            if !self.remove_on_load {
                let map = self.data.read().unwrap();
                Ok(map.get(&id).map(|pl| pl.clone()))
            } else {
                let mut map = self.data.write().unwrap();
                let res = Ok(map.get(&id).map(|pl| pl.clone()));
                map.remove(&id);
                res
            }
        }

        fn store(&self, id: Snowflake, data: &MockStoredData) -> Result<()> {
            let mut map = self.data.write().unwrap();
            map.insert(id, data.clone());

            Ok(())
        }

        fn delete(&self, id: Snowflake) -> Result<()> {
            let mut map = self.data.write().unwrap();
            map.remove(&id);

            Ok(())
        }

        fn keys(&self, page: u64, limit: u64) -> Result<Vec<Snowflake>> {
            let ids: Vec<Snowflake>;
            let start_index = page * limit;

            let data = self.data.read().unwrap();
            ids = data
                .keys()
                .skip(start_index as usize)
                .take(limit as usize)
                .map(|x| *x)
                .collect();

            Ok(ids)
        }
    }

    type MockStore = Store<MockStoredData, MockEntityBackend>;

    #[test]
    fn test_exists() {
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let backend = Arc::new(MockEntityBackend::new());
        let data = MockStoredData::new(
            snowflake_gen.generate(),
            "foo".to_owned(),
            1,
            Arc::new(ComponentManager::new()),
        );

        backend.store(*data.id(), &data).unwrap();
        let store = MockStore::new(backend);

        let id2 = snowflake_gen.generate();
        assert!(store.exists(*data.id()).unwrap());
        assert!(!store.exists(id2).unwrap());
    }

    #[test]
    fn test_load_nonexistent() {
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let backend = Arc::new(MockEntityBackend::new());
        let store = MockStore::new(backend);
        let handle = store
            .load(snowflake_gen.generate(), Arc::new(ComponentManager::new()))
            .unwrap();

        assert!(!handle.exists());
    }

    #[test]
    fn test_load() {
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let backend = Arc::new(MockEntityBackend::new());
        let data = MockStoredData::new(
            snowflake_gen.generate(),
            "foo".to_owned(),
            1,
            Arc::new(ComponentManager::new()),
        );

        backend.store(*data.id(), &data).unwrap();
        let store = MockStore::new(backend);

        let handle = store
            .load(*data.id(), Arc::new(ComponentManager::new()))
            .unwrap();

        assert!(handle.exists());
        let data_copy = handle.get().unwrap();

        assert_eq!(*data.id(), *data_copy.id());
        assert_eq!(data.field_a, data_copy.field_a);
        assert_eq!(data.field_b, data_copy.field_b);
    }

    #[test]
    fn test_concurrent_load() {
        // Create some test data to load.
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let backend = Arc::new(MockEntityBackend::new());
        let id = snowflake_gen.generate();
        let data = MockStoredData::new(id, "foo".to_owned(), 1, Arc::new(ComponentManager::new()));
        backend.store(id, &data).unwrap();

        // Create a bunch of threads.
        // These threads will all try to access the same data at the same
        // time.
        let store = Arc::new(MockStore::new(backend));
        let mut threads = Vec::with_capacity(9);
        let barrier = Arc::new(Barrier::new(10));

        for _ in 0..9 {
            let b_clone = barrier.clone();
            let s_clone = store.clone();

            let handle = thread::spawn(move || {
                b_clone.wait();
                let wrapper = s_clone.get_handle(id);
                wrapper
            });

            threads.push(handle);
        }

        barrier.wait();
        let our_wrapper = store.get_handle(id);

        for thread in threads {
            // Check what the other threads got for a handle.
            // Both wrapper objects should contain Arcs pointing to the
            // same data.
            let their_wrapper = thread.join().unwrap();
            assert!(Arc::ptr_eq(&our_wrapper.handle, &their_wrapper.handle));
        }
    }

    #[test]
    fn test_concurrent_access() {
        // Create some test data to load.
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let mut backend = MockEntityBackend::new();
        let id = snowflake_gen.generate();
        let data = MockStoredData::new(id, "foo".to_owned(), 1, Arc::new(ComponentManager::new()));

        // Detect if and when we end up performing multiple backend loads.
        backend.set_remove_on_load(true);
        backend.store(id, &data).unwrap();

        // Like in test_concurrent_load, create a bunch of threads primed
        // to access the data simultaneously.
        //
        // Unlike in test_concurrent_load, however, these threads will attempt
        // a full retrieval from the backend.
        let store = Arc::new(MockStore::new(Arc::new(backend)));
        let barrier = Arc::new(Barrier::new(10));
        let mut threads = Vec::with_capacity(9);
        let (tx, rx) = mpsc::channel();

        for _ in 0..9 {
            let b_clone = barrier.clone();
            let s_clone = store.clone();
            let tx_clone = tx.clone();

            let handle = thread::spawn(move || {
                b_clone.wait();
                let handle = s_clone.load(id, Arc::new(ComponentManager::new())).unwrap();
                let data = handle.get().unwrap();

                tx_clone
                    .send((data.id, data.field_a.clone(), data.field_b))
                    .unwrap();

                // Threads need to hang around to ensure that at least one
                // Arc to the handle exists at all times.
                b_clone.wait();
                assert_eq!(data.id, id);
            });

            threads.push(handle);
        }

        // Make sure our handle to the data is dropped before telling the
        // other threads to exit.
        {
            barrier.wait();
            let handle = store.load(id, Arc::new(ComponentManager::new())).unwrap();
            let data = handle.get().unwrap();

            // Get the data as seen by all threads.
            for _ in 0..9 {
                let their_data = rx.recv().unwrap();

                assert_eq!(data.id, their_data.0);
                assert_eq!(data.field_a, their_data.1);
                assert_eq!(data.field_b, their_data.2);
            }
        }

        // Tell all other threads to exit.
        // Once they all drop their handles, the underlying MockStoreData
        // should get dropped as well.
        barrier.wait();
        for thread in threads {
            thread.join().unwrap();
        }

        // Now make sure that the MockStoreData actually _did_ get dropped.
        // Since we did `backend.set_remove_on_load`, this should now load
        // None into the handle.
        let handle = store.load(id, Arc::new(ComponentManager::new())).unwrap();
        let data = handle.get();
        assert!(data.is_none());
    }

    #[test]
    fn test_multiple_single_thread_access() {
        // Create some test data to load.
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let backend = MockEntityBackend::new();
        let id = snowflake_gen.generate();
        let data = MockStoredData::new(id, "foo".to_owned(), 1, Arc::new(ComponentManager::new()));
        backend.store(id, &data).unwrap();

        let store = MockStore::new(Arc::new(backend));

        // Try to load two read handles to the same Entity at once on
        // the same thread.
        //
        // The main failure mode we want to check for here is deadlocking
        // (due to trying to grab write access to the handle for
        // initialization, say)
        let handle_1 = store.load(id, Arc::new(ComponentManager::new())).unwrap();
        let data_1 = handle_1.get().unwrap();

        let handle_2 = store.load(id, Arc::new(ComponentManager::new())).unwrap();
        let data_2 = handle_2.get().unwrap();

        assert_eq!(data_1.id, data_2.id);
        assert_eq!(data_1.field_a, data_2.field_a);
        assert_eq!(data_1.field_b, data_2.field_b);

        assert_eq!(data_1.id, data.id);
        assert_eq!(data_1.field_a, data.field_a);
        assert_eq!(data_1.field_b, data.field_b);
    }

    #[test]
    fn test_store() {
        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let id = snowflake_gen.generate();
        let cm = Arc::new(ComponentManager::new());
        let data = MockStoredData::new(id, "foo".to_owned(), 1, cm.clone());

        let backend = Arc::new(MockEntityBackend::new());
        let store = MockStore::new(backend);

        {
            let mut handle = store.load_mut(*data.id(), cm.clone()).unwrap();
            assert!(!handle.exists());

            handle.replace(data.clone());
            handle.store().unwrap();
        }

        let handle = store.load(*data.id(), cm).unwrap();
        let data_copy = handle.get().unwrap();

        assert_eq!(*data_copy.id(), id);
        assert_eq!(data.field_a, data_copy.field_a);
        assert_eq!(data.field_b, data_copy.field_b);
    }

    #[test]
    fn test_handle_drop() {
        use super::ComponentManager;
        use crate::local_storage::LocalComponentStorage;
        use crate::Component;

        #[derive(Clone)]
        struct TestComponent(u64);
        impl Component<MockStoredData> for TestComponent {};

        let backend = Arc::new(MockEntityBackend::new());
        let store = MockStore::new(backend);
        let mut cm: ComponentManager<MockStoredData> = ComponentManager::new();

        cm.register_component(
            "TestComponent",
            LocalComponentStorage::<MockStoredData, TestComponent>::new(),
        )
        .unwrap();

        let cm = Arc::new(cm);

        let mut snowflake_gen = SnowflakeGenerator::new(0, 0);
        let id = snowflake_gen.generate();

        {
            let data = MockStoredData::new(id, "foo".to_owned(), 1, cm.clone());

            let mut handle = store.insert(data);
            let data = handle.get_mut().unwrap();

            data.set_component(TestComponent(50)).unwrap();
        }

        let handle = store.load(id, cm.clone()).unwrap();
        let data = handle.get().unwrap();
        let component: TestComponent = data.get_component().unwrap().unwrap();

        assert_eq!(component.0, 50);
    }
}