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
use std::borrow::{Borrow, BorrowMut};
use std::fmt;
use std::marker::PhantomData;
use std::ops::DerefMut;

use hibitset::BitSet;

use {Component, Entities, Entity, Index, Join, ParJoin, Storage, UnprotectedStorage};
use storage::MaskedStorage;
use world::EntityIndex;

/// Specifies that the `RestrictedStorage` cannot run in parallel.
pub enum NormalRestriction { }
/// Specifies that the `RestrictedStorage` can run in parallel.
pub enum ParallelRestriction { }

/// Similar to a `MaskedStorage` and a `Storage` combined, but restricts usage
/// to only getting and modifying the components. That means nothing that would
/// modify the inner bitset so the iteration cannot be invalidated. For example,
/// no insertion or removal is allowed.
///
/// Example Usage:
///
/// ```rust
/// # use specs::{Join, System, Component, RestrictedStorage, WriteStorage, VecStorage, Entities};
/// struct SomeComp(u32);
/// impl Component for SomeComp {
///     type Storage = VecStorage<Self>;
/// }
///
/// struct RestrictedSystem;
/// impl<'a> System<'a> for RestrictedSystem {
///     type SystemData = (
///         Entities<'a>,
///         WriteStorage<'a, SomeComp>,
///     );
///     fn run(&mut self, (entities, mut some_comps): Self::SystemData) {
///         for (entity, (mut entry, restricted)) in (
///             &*entities,
///             &mut some_comps.restrict()
///         ).join() {
///             // Check if the reference is fine to mutate.
///             if restricted.get_unchecked(&entry).0 < 5 {
///                 // Get a mutable reference now.
///                 let mut mutable = restricted.get_mut_unchecked(&mut entry);
///                 mutable.0 += 1;
///             }
///         }
///     }
/// }
/// ```
pub struct RestrictedStorage<'rf, 'st: 'rf, B, T, R, RT>
where
    T: Component,
    R: Borrow<T::Storage> + 'rf,
    B: Borrow<BitSet> + 'rf,
{
    bitset: B,
    data: R,
    entities: &'rf Entities<'st>,
    phantom: PhantomData<(T, RT)>,
}

unsafe impl<'rf, 'st: 'rf, B, T, R> ParJoin
    for &'rf mut RestrictedStorage<'rf, 'st, B, T, R, ParallelRestriction>
where
    T: Component,
    R: BorrowMut<T::Storage> + 'rf,
    B: Borrow<BitSet> + 'rf,
{
}

impl<'rf, 'st, B, T, R, RT> RestrictedStorage<'rf, 'st, B, T, R, RT>
where
    T: Component,
    R: Borrow<T::Storage>,
    B: Borrow<BitSet>,
{
    /// Attempts to get the component related to the entity.
    ///
    /// Functions similar to the normal `Storage::get` implementation.
    pub fn get(&self, entity: Entity) -> Option<&T> {
        if self.bitset.borrow().contains(entity.id()) && self.entities.is_alive(entity) {
            Some(unsafe { self.data.borrow().get(entity.id()) })
        } else {
            None
        }
    }

    /// Gets the component related to the current entry without checking whether
    /// the storage has it or not.
    pub fn get_unchecked(&self, entry: &Entry<'rf, T>) -> &T {
        entry.assert_same_storage(self.data.borrow());
        unsafe { self.data.borrow().get(entry.index()) }
    }
}

impl<'rf, 'st, B, T, R, RT> RestrictedStorage<'rf, 'st, B, T, R, RT>
where
    T: Component,
    R: BorrowMut<T::Storage>,
    B: Borrow<BitSet>,
{
    /// Gets the component related to the current entry without checking whether
    /// the storage has it or not.
    pub fn get_mut_unchecked(&mut self, entry: &Entry<'rf, T>) -> &mut T {
        entry.assert_same_storage(self.data.borrow());
        unsafe { self.data.borrow_mut().get_mut(entry.index()) }
    }
}

impl<'rf, 'st, B, T, R> RestrictedStorage<'rf, 'st, B, T, R, NormalRestriction>
where
    T: Component,
    R: BorrowMut<T::Storage>,
    B: Borrow<BitSet>,
{
    /// Attempts to get the component related to the entity mutably.
    ///
    /// Functions similar to the normal `Storage::get_mut` implementation.
    ///
    /// Note: This only works if this is a non-parallel `RestrictedStorage`.
    pub fn get_mut(&mut self, entity: Entity) -> Option<&mut T> {
        if self.bitset.borrow().contains(entity.id()) && self.entities.is_alive(entity) {
            Some(unsafe { self.data.borrow_mut().get_mut(entity.id()) })
        } else {
            None
        }
    }
}

impl<'rf, 'st: 'rf, B, T, R, RT> Join for &'rf RestrictedStorage<'rf, 'st, B, T, R, RT>
where
    T: Component,
    R: Borrow<T::Storage>,
    B: Borrow<BitSet>,
{
    type Type = (Entry<'rf, T>, Self);
    type Value = Self;
    type Mask = &'rf BitSet;
    fn open(self) -> (Self::Mask, Self::Value) {
        (self.bitset.borrow(), self)
    }
    unsafe fn get(value: &mut Self::Value, id: Index) -> Self::Type {
        let entry = Entry {
            id,
            pointer: value.data.borrow() as *const T::Storage,
            phantom: PhantomData,
        };

        (entry, value)
    }
}

impl<'rf, 'st: 'rf, B, T, R, RT> Join for &'rf mut RestrictedStorage<'rf, 'st, B, T, R, RT>
where
    T: Component,
    R: BorrowMut<T::Storage>,
    B: Borrow<BitSet>,
{
    type Type = (Entry<'rf, T>, Self);
    type Value = Self;
    type Mask = BitSet;
    fn open(self) -> (Self::Mask, Self::Value) {
        (self.bitset.borrow().clone(), self)
    }
    unsafe fn get(value: &mut Self::Value, id: Index) -> Self::Type {
        use std::mem;
        let entry = Entry {
            id,
            pointer: value.data.borrow() as *const T::Storage,
            phantom: PhantomData,
        };

        let value: &'rf mut Self::Value = mem::transmute(value);
        (entry, value)
    }
}

impl<'st, T, D> Storage<'st, T, D>
where
    T: Component,
    D: DerefMut<Target = MaskedStorage<T>>,
{
    /// Builds a mutable `RestrictedStorage` out of a `Storage`. Allows restricted
    /// access to the inner components without allowing invalidating the
    /// bitset for iteration in `Join`.
    pub fn restrict<'rf>(
        &'rf mut self,
    ) -> RestrictedStorage<'rf, 'st, &BitSet, T, &mut T::Storage, NormalRestriction> {
        let (mask, data) = self.data.open_mut();
        RestrictedStorage {
            bitset: mask,
            data,
            entities: &self.entities,
            phantom: PhantomData,
        }
    }

    /// Builds a mutable, parallel `RestrictedStorage`,
    /// does not allow mutably getting other components
    /// aside from the current iteration.
    pub fn par_restrict<'rf>(
        &'rf mut self,
    ) -> RestrictedStorage<'rf, 'st, &BitSet, T, &mut T::Storage, ParallelRestriction> {
        let (mask, data) = self.data.open_mut();
        RestrictedStorage {
            bitset: mask,
            data,
            entities: &self.entities,
            phantom: PhantomData,
        }
    }
}

/// An entry to a storage.
pub struct Entry<'rf, T>
where
    T: Component,
{
    id: Index,
    // Pointer for comparison when attempting to check against a storage.
    pointer: *const T::Storage,
    phantom: PhantomData<&'rf ()>,
}

unsafe impl<'rf, T: Component> Send for Entry<'rf, T> {}
unsafe impl<'rf, T: Component> Sync for Entry<'rf, T> {}

impl<'rf, T> fmt::Debug for Entry<'rf, T>
where
    T: Component,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "Entry {{ id: {}, pointer: {:?} }}",
            self.id,
            self.pointer
        )
    }
}

impl<'rf, T> Entry<'rf, T>
where
    T: Component,
{
    #[inline]
    fn assert_same_storage(&self, storage: &T::Storage) {
        assert_eq!(
            self.pointer,
            storage as *const T::Storage,
            "Attempt to get an unchecked entry from a storage: {:?} {:?}",
            self.pointer,
            storage as *const T::Storage
        );
    }
}

impl<'rf, T> EntityIndex for Entry<'rf, T>
where
    T: Component,
{
    fn index(&self) -> Index {
        self.id
    }
}

impl<'a, 'rf, T> EntityIndex for &'a Entry<'rf, T>
where
    T: Component,
{
    fn index(&self) -> Index {
        (*self).index()
    }
}