async_ecs/storage/
storage_wrapper.rs

1use std::marker::PhantomData;
2use std::ops::{Deref, DerefMut, Not};
3
4use hibitset::{BitSet, BitSetLike};
5
6use crate::{
7    component::Component,
8    entity::{Entities, Entity, Index},
9    error::Error,
10    join::{Join, ParJoin},
11    resource::Ref,
12    storage::MaskedStorage,
13};
14
15use super::{AntiStorage, DistinctStorage, Drain, Storage};
16
17/// A wrapper around the masked storage and the generations vector.
18/// Can be used for safe lookup of components, insertions and removes.
19/// This is what `World::read/write` fetches for the user.
20pub struct StorageWrapper<'a, T, D> {
21    data: D,
22    entities: Ref<'a, Entities>,
23    phantom: PhantomData<T>,
24}
25
26impl<'a, T, D> StorageWrapper<'a, T, D> {
27    pub fn new(data: D, entities: Ref<'a, Entities>) -> Self {
28        Self {
29            data,
30            entities,
31            phantom: PhantomData,
32        }
33    }
34}
35
36impl<'a, T, D> StorageWrapper<'a, T, D>
37where
38    T: Component,
39    D: Deref<Target = MaskedStorage<T>>,
40{
41    /// Returns the `Entities` resource fetched by this storage.
42    /// **This does not have anything to do with the components inside.**
43    /// You only want to use this when implementing additional methods
44    /// for `Storage` via an extension trait.
45    pub fn fetched_entities(&self) -> &Entities {
46        &self.entities
47    }
48
49    /// Tries to read the data associated with an `Entity`.
50    pub fn get(&self, e: Entity) -> Option<&T> {
51        let index = e.index();
52
53        if self.data.mask().contains(index) && self.entities.is_alive(e) {
54            Some(unsafe { self.data.storage().get(index) })
55        } else {
56            None
57        }
58    }
59
60    /// Computes the number of elements this `Storage` contains by counting the
61    /// bits in the bit set. This operation will never be performed in
62    /// constant time.
63    pub fn count(&self) -> usize {
64        self.mask().iter().count()
65    }
66
67    /// Checks whether this `Storage` is empty. This operation is very cheap.
68    pub fn is_empty(&self) -> bool {
69        self.mask().is_empty()
70    }
71
72    /// Returns true if the storage has a component for this entity, and that
73    /// entity is alive.
74    pub fn contains(&self, e: Entity) -> bool {
75        let index = e.index();
76
77        self.data.mask().contains(index) && self.entities.is_alive(e)
78    }
79
80    /// Returns a reference to the bitset of this storage which allows filtering
81    /// by the component type without actually getting the component.
82    pub fn mask(&self) -> &BitSet {
83        &self.data.mask()
84    }
85
86    pub fn not(&self) -> AntiStorage<'_> {
87        AntiStorage(&self.data.mask())
88    }
89}
90
91impl<'a, T, D> StorageWrapper<'a, T, D>
92where
93    T: Component,
94    D: DerefMut<Target = MaskedStorage<T>>,
95{
96    /// Tries to mutate the data associated with an `Entity`.
97    pub fn get_mut(&mut self, e: Entity) -> Option<&mut T> {
98        let index = e.index();
99
100        if self.data.mask().contains(index) && self.entities.is_alive(e) {
101            Some(unsafe { self.data.storage_mut().get_mut(index) })
102        } else {
103            None
104        }
105    }
106
107    /// Inserts new data for a given `Entity`.
108    /// Returns the result of the operation as a `InsertResult<T>`
109    ///
110    /// If a component already existed for the given `Entity`, then it will
111    /// be overwritten with the new component. If it did overwrite, then the
112    /// result will contain `Some(T)` where `T` is the previous component.
113    pub fn insert(&mut self, entity: Entity, component: T) -> Result<Option<T>, Error> {
114        if !self.entities.is_alive(entity) {
115            return Err(Error::EntityIsNotAlive(entity));
116        }
117
118        Ok(self.data.insert(entity, component))
119    }
120
121    /// Removes the data associated with an `Entity`.
122    pub fn remove(&mut self, e: Entity) -> Option<T> {
123        let index = e.index();
124        if self.entities.is_alive(e) {
125            self.data.remove(index)
126        } else {
127            None
128        }
129    }
130
131    /// Clears the contents of the storage.
132    pub fn clear(&mut self) {
133        self.data.clear();
134    }
135
136    /// Creates a draining storage wrapper which can be `.join`ed
137    /// to get a draining iterator.
138    pub fn drain(&mut self) -> Drain<T> {
139        Drain {
140            data: &mut self.data,
141        }
142    }
143}
144
145impl<'a, T: Component, D> DistinctStorage for StorageWrapper<'a, T, D> where
146    T::Storage: DistinctStorage
147{
148}
149
150impl<'a, 'e, T, D> Not for &'a StorageWrapper<'e, T, D>
151where
152    T: Component,
153    D: Deref<Target = MaskedStorage<T>>,
154{
155    type Output = AntiStorage<'a>;
156
157    fn not(self) -> Self::Output {
158        AntiStorage(&self.data.mask())
159    }
160}
161
162impl<'a, 'e, T, D> Join for &'a StorageWrapper<'e, T, D>
163where
164    T: Component,
165    D: Deref<Target = MaskedStorage<T>>,
166{
167    type Mask = &'a BitSet;
168    type Type = &'a T;
169    type Value = &'a T::Storage;
170
171    unsafe fn open(self) -> (Self::Mask, Self::Value) {
172        (self.data.mask(), self.data.storage())
173    }
174
175    unsafe fn get(v: &mut Self::Value, i: Index) -> &'a T {
176        (**v).get(i)
177    }
178}
179
180impl<'a, 'e, T, D> Join for &'a mut StorageWrapper<'e, T, D>
181where
182    T: Component,
183    D: DerefMut<Target = MaskedStorage<T>>,
184{
185    type Mask = &'a BitSet;
186    type Type = &'a mut T;
187    type Value = &'a T::Storage;
188
189    unsafe fn open(self) -> (Self::Mask, Self::Value) {
190        (self.data.mask(), self.data.storage())
191    }
192
193    unsafe fn get(v: &mut Self::Value, i: Index) -> &'a mut T {
194        let value: *mut T::Storage = *v as *const T::Storage as *mut T::Storage;
195
196        (*value).get_mut(i)
197    }
198}
199
200impl<'a, 'e, T, D> ParJoin for &'a StorageWrapper<'e, T, D>
201where
202    T: Component,
203    D: Deref<Target = MaskedStorage<T>>,
204    T::Storage: Sync,
205{
206}
207
208impl<'a, 'e, T, D> ParJoin for &'a mut StorageWrapper<'e, T, D>
209where
210    T: Component,
211    D: DerefMut<Target = MaskedStorage<T>>,
212    T::Storage: Sync + DistinctStorage,
213{
214}