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
//! Allows placing resources (i.e. "global" data) in a dictionary and looking it up by type. The data
//! could be "global" systems, component storages, component factories, etc.
//!
//! This implements a type system for expressing read/write dependencies. Many readers and single
//! writers are allowed, but not both at the same time. This is checked at runtime, not compile time.
//!
//! Lots of inspiration taken from `shred` for how to create a type system
//! to express read/write dependencies

//
// ResourceId
//
use std::any::TypeId;
use std::marker::PhantomData;
use std::prelude::v1::*;

use downcast_rs::Downcast;
use fnv::FnvHashMap as HashMap;

use crate::trust_cell::{Ref, RefMut, TrustCell};

/// Every type can be converted to a `ResourceId`. The ResourceId is used to look up the type's value
/// in the `ResourceMap`
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ResourceId {
    type_id: TypeId,
}

impl ResourceId {
    /// Creates a new resource id from a given type.
    #[inline]
    pub fn new<T: 'static>() -> Self {
        ResourceId {
            type_id: std::any::TypeId::of::<T>(),
        }
    }
}

/// Any data that can be stored in the ResourceMap must implement this trait. There is a blanket
/// implementation provided for all compatible types
pub trait Resource: Downcast + Send + Sync + 'static {}

impl<T> Resource for T where T: Downcast + Send + Sync {}

// Used for downcastic
mod __resource_mopafy_scope {
    #![allow(clippy::all)]

    use super::Resource;

    downcast_rs::impl_downcast!(Resource);
}

/// Builder for creating a ResourceMap
pub struct ResourceMapBuilder {
    /// The ResourceMap being built
    resource_map: ResourceMap,
}

impl ResourceMapBuilder {
    /// Creates an empty builder
    pub fn new() -> Self {
        ResourceMapBuilder {
            resource_map: ResourceMap::new(),
        }
    }

    /// Builder-style API that adds the resource to the map
    pub fn with_resource<R>(
        mut self,
        r: R,
    ) -> Self
    where
        R: Resource,
    {
        self.resource_map.insert(r);
        self
    }

    /// Adds the resource to the map
    pub fn insert<R>(
        &mut self,
        r: R,
    ) where
        R: Resource,
    {
        self.resource_map.insert(r);
    }

    /// Consume this builder, returning the resource map
    pub fn build(self) -> ResourceMap {
        self.resource_map
    }
}

/// A key-value structure. The key is a type, and the value is a single object of that type
#[derive(Default)]
pub struct ResourceMap {
    resources: HashMap<ResourceId, TrustCell<Box<dyn Resource>>>,
}

impl ResourceMap {
    /// Creates an empty resource map
    pub fn new() -> Self {
        ResourceMap {
            resources: HashMap::default(),
        }
    }

    /// Add a type/resource instance to the map
    pub fn insert<R>(
        &mut self,
        r: R,
    ) where
        R: Resource,
    {
        self.insert_by_id(ResourceId::new::<R>(), r);
    }

    /// Remove a type/resource instance from the map
    pub fn remove<R>(&mut self) -> Option<R>
    where
        R: Resource,
    {
        self.remove_by_id(ResourceId::new::<R>())
    }

    fn insert_by_id<R>(
        &mut self,
        id: ResourceId,
        r: R,
    ) where
        R: Resource,
    {
        self.resources.insert(id, TrustCell::new(Box::new(r)));
    }

    fn remove_by_id<R>(
        &mut self,
        id: ResourceId,
    ) -> Option<R>
    where
        R: Resource,
    {
        self.resources
            .remove(&id)
            .map(TrustCell::into_inner)
            .map(|x: Box<dyn Resource>| x.downcast())
            .map(|x: Result<Box<R>, _>| x.ok().unwrap())
            .map(|x| *x)
    }

    // Use optional nightly support for access to std::intrinsics::type_name
    #[cfg(feature = "nightly")]
    fn unwrap_resource<R>(resource: Option<R>) -> R {
        if resource.is_none() {
            let name = core::any::type_name::<R>();
            // Tried to fetch or fetch_mut on a resource that is not registered.
            panic!("Resource not found: {}", name);
        }

        resource.unwrap()
    }

    #[cfg(not(feature = "nightly"))]
    fn unwrap_resource<R>(resource: Option<R>) -> R {
        // Tried to fetch or fetch_mut on a resource that is not registered. (Nightly will give better error message)
        resource.unwrap()
    }

    /// Read-only fetch of a resource. Trying to get a resource that is not in the map is fatal. Use
    /// try_fetch if unsure whether the resource exists. Requesting read access to a resource that
    /// has any concurrently active writer is fatal.
    pub fn fetch<R: Resource>(&self) -> ReadBorrow<R> {
        let result = self.try_fetch();
        Self::unwrap_resource(result)
    }

    /// Read-only fetch of a resource. Requesting read access to a resource that has a concurrently
    /// active writer is fatal. Returns None if the type is not registered.
    pub fn try_fetch<R: Resource>(&self) -> Option<ReadBorrow<R>> {
        let res_id = ResourceId::new::<R>();

        self.resources.get(&res_id).map(|r| ReadBorrow {
            inner: Ref::map(r.borrow(), Box::as_ref),
            phantom: PhantomData,
        })
    }

    /// Read/Write fetch of a resource. Trying to get a resource that is not in the map is fatal. Use
    /// try_fetch if unsure whether the resource exists. Requesting write access to a resource with
    /// any concurrently active read/write is fatal
    pub fn fetch_mut<R: Resource>(&self) -> WriteBorrow<R> {
        let result = self.try_fetch_mut();
        Self::unwrap_resource(result)
    }

    /// Read/Write fetch of a resource. Requesting write access to a resource with
    /// any concurrently active read/write is fatal. Returns None if the type is not registered.
    pub fn try_fetch_mut<R: Resource>(&self) -> Option<WriteBorrow<R>> {
        let res_id = ResourceId::new::<R>();

        self.resources.get(&res_id).map(|r| WriteBorrow::<R> {
            inner: RefMut::map(r.borrow_mut(), Box::as_mut),
            phantom: PhantomData,
        })
    }

    /// Returns true if the resource is registered.
    pub fn has_value<R>(&self) -> bool
    where
        R: Resource,
    {
        self.has_value_raw(ResourceId::new::<R>())
    }

    fn has_value_raw(
        &self,
        id: ResourceId,
    ) -> bool {
        self.resources.contains_key(&id)
    }

    /// Iterate all ResourceIds within the dictionary
    pub fn keys(&self) -> impl Iterator<Item = &ResourceId> {
        self.resources.iter().map(|x| x.0)
    }
}

/// DataRequirement base trait, which underlies Read<T> and Write<T> requests
pub trait DataRequirement<'a> {
    type Borrow: DataBorrow;

    fn fetch(resource_map: &'a ResourceMap) -> Self::Borrow;
}

// Implementation for () required because we build support for (), (A), (A, B), (A, B, ...) inductively
impl<'a> DataRequirement<'a> for () {
    type Borrow = ();

    fn fetch(_: &'a ResourceMap) -> Self::Borrow {}
}

/// This type represents requesting read access to T. If T is not registered, trying to fill this
/// request will be fatal
pub struct Read<T: Resource> {
    phantom_data: PhantomData<T>,
}

/// Same as `Read`, but will return None rather than being fatal
pub type ReadOption<T> = Option<Read<T>>;

impl<'a, T: Resource> DataRequirement<'a> for Read<T> {
    type Borrow = ReadBorrow<'a, T>;

    fn fetch(resource_map: &'a ResourceMap) -> Self::Borrow {
        resource_map.fetch::<T>()
    }
}

impl<'a, T: Resource> DataRequirement<'a> for Option<Read<T>> {
    type Borrow = Option<ReadBorrow<'a, T>>;

    fn fetch(resource_map: &'a ResourceMap) -> Self::Borrow {
        resource_map.try_fetch::<T>()
    }
}

/// This type represents requesting write access to T. If T is not registered, trying to fill this
/// request will be fatal
pub struct Write<T: Resource> {
    phantom_data: PhantomData<T>,
}

/// Same as `Write`, but will return None rather than being fatal
pub type WriteOption<T> = Option<Write<T>>;

impl<'a, T: Resource> DataRequirement<'a> for Write<T> {
    type Borrow = WriteBorrow<'a, T>;

    fn fetch(resource_map: &'a ResourceMap) -> Self::Borrow {
        resource_map.fetch_mut::<T>()
    }
}

impl<'a, T: Resource> DataRequirement<'a> for Option<Write<T>> {
    type Borrow = Option<WriteBorrow<'a, T>>;

    fn fetch(resource_map: &'a ResourceMap) -> Self::Borrow {
        resource_map.try_fetch_mut::<T>()
    }
}

/// Borrow base trait. This base trait is required to allow inductively composing tuples of ReadBorrow/WriteBorrow
/// i.e. (), (A), (A, B), (A, B, ...) inductively
pub trait DataBorrow {}

// Implementation for () required because we build support for (), (A), (A, B), (A, B, ...) inductively
impl DataBorrow for () {}

/// Represents a filled read-only request for T
pub struct ReadBorrow<'a, T> {
    inner: Ref<'a, dyn Resource>,
    phantom: PhantomData<&'a T>,
}

impl<'a, T> DataBorrow for ReadBorrow<'a, T> {}
impl<'a, T> DataBorrow for Option<ReadBorrow<'a, T>> {}

impl<'a, T> std::ops::Deref for ReadBorrow<'a, T>
where
    T: Resource,
{
    type Target = T;

    fn deref(&self) -> &T {
        self.inner.downcast_ref().unwrap()
    }
}

impl<'a, T> Clone for ReadBorrow<'a, T> {
    fn clone(&self) -> Self {
        ReadBorrow {
            inner: self.inner.clone(),
            phantom: PhantomData,
        }
    }
}

/// Represents a filled read/write request for T
pub struct WriteBorrow<'a, T> {
    inner: RefMut<'a, dyn Resource>,
    phantom: PhantomData<&'a mut T>,
}

impl<'a, T> DataBorrow for WriteBorrow<'a, T> {}
impl<'a, T> DataBorrow for Option<WriteBorrow<'a, T>> {}

impl<'a, T> std::ops::Deref for WriteBorrow<'a, T>
where
    T: Resource,
{
    type Target = T;

    fn deref(&self) -> &T {
        self.inner.downcast_ref().unwrap()
    }
}

impl<'a, T> std::ops::DerefMut for WriteBorrow<'a, T>
where
    T: Resource,
{
    fn deref_mut(&mut self) -> &mut T {
        self.inner.downcast_mut().unwrap()
    }
}

// This macro is used to inductively build tuples i.e. (), (A), (A, B), (A, B, ...) inductively
macro_rules! impl_data {
    ( $($ty:ident),* ) => {

        //
        // Make tuples containing DataBorrow types implement DataBorrow
        //
        impl<$($ty),*> DataBorrow for ( $( $ty , )* )
        where $( $ty : DataBorrow ),*
        {

        }

        //
        // Make tuples containing DataRequirement types implement DataBorrow. Additionally implement
        // fetch
        //
        impl<'a, $($ty),*> DataRequirement<'a> for ( $( $ty , )* )
        where $( $ty : DataRequirement<'a> ),*
        {
            type Borrow = ( $( <$ty as DataRequirement<'a>>::Borrow, )* );

            fn fetch(resource_map: &'a ResourceMap) -> Self::Borrow {
                #![allow(unused_variables)]
                ( $( <$ty as DataRequirement<'a>>::fetch(resource_map), )* )
            }
        }
    };
}

mod impl_data {
    #![cfg_attr(rustfmt, rustfmt_skip)]

    use super::*;

    // Build tuples for DataBorrow/DataRequirement i.e. (), (A), (A, B), (A, B, ...) inductively
    impl_data!(A);
    impl_data!(A, B);
    impl_data!(A, B, C);
    impl_data!(A, B, C, D);
    impl_data!(A, B, C, D, E);
    impl_data!(A, B, C, D, E, F);
    impl_data!(A, B, C, D, E, F, G);
    impl_data!(A, B, C, D, E, F, G, H);
    impl_data!(A, B, C, D, E, F, G, H, I);
    impl_data!(A, B, C, D, E, F, G, H, I, J);
    // May be extended as needed, but this seems like enough
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y);
    // impl_data!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
}