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
use std::any::{type_name, Any, TypeId};
use std::cell::{Ref, RefCell, RefMut};
use std::collections::hash_map::{Entry, HashMap};
use std::hash::{BuildHasherDefault, Hasher};
use std::ops::{Deref, DerefMut};

/// A type map for holding resources.
///
/// Resources replace global variables and my be accessed by systems that know their type.
///
/// # Examples
///
/// ```
/// # use rs_ecs::*;
/// struct WrapperType(u32);
///
/// let mut resources = Resources::new();
///
/// // Insert multiple resources
/// resources.insert(42_u32);
/// resources.insert(WrapperType(23));
///
/// // Borrow a resource immutably
/// let wrapped_res = resources.get::<WrapperType>();
///
/// // Borrow a resource mutably
/// let mut u32_res = resources.get_mut::<u32>();
/// *u32_res += 1;
/// ```
pub struct Resources(HashMap<TypeId, RefCell<Box<dyn Any>>, BuildHasherDefault<TypeIdHasher>>);

impl Default for Resources {
    /// Create an empty resources map.
    fn default() -> Self {
        Self::new()
    }
}

impl Resources {
    /// Create an empty resources map.
    pub fn new() -> Self {
        Self(Default::default())
    }
}

impl Resources {
    /// Insert a resource.
    ///
    /// # Panics
    ///
    /// Panics if a resource of the same type is already present.
    pub fn insert<R>(&mut self, res: R)
    where
        R: 'static,
    {
        match self.0.entry(TypeId::of::<R>()) {
            Entry::Vacant(entry) => entry.insert(RefCell::new(Box::new(res))),
            Entry::Occupied(_) => panic!("Resource {} already present", type_name::<R>()),
        };
    }
}

impl Resources {
    /// Borrow a resource immutably
    ///
    /// # Panics
    ///
    /// Panics if the resource is not present.
    pub fn get<R>(&self) -> Res<'_, R>
    where
        R: 'static,
    {
        let ref_ = self
            .0
            .get(&TypeId::of::<R>())
            .unwrap_or_else(|| panic!("Resource {} not present", type_name::<R>()))
            .try_borrow()
            .unwrap_or_else(|_err| panic!("Resource {} already borrwed", type_name::<R>()));

        Res(Ref::map(ref_, |ref_| unsafe {
            &*(ref_.deref() as *const dyn Any as *const R)
        }))
    }

    /// Borrow a resource mutably
    ///
    /// # Panics
    ///
    /// Panics if the resource is not present.
    pub fn get_mut<R>(&self) -> ResMut<'_, R>
    where
        R: 'static,
    {
        let ref_ = self
            .0
            .get(&TypeId::of::<R>())
            .unwrap_or_else(|| panic!("Resource {} not present", type_name::<R>()))
            .try_borrow_mut()
            .unwrap_or_else(|_err| panic!("Resource {} already borrwed", type_name::<R>()));

        ResMut(RefMut::map(ref_, |ref_| unsafe {
            &mut *(ref_.deref_mut() as *mut dyn Any as *mut R)
        }))
    }
}

/// An immutable borrow of a resource.
pub struct Res<'a, R>(Ref<'a, R>);

impl<R> Deref for Res<'_, R> {
    type Target = R;

    fn deref(&self) -> &R {
        self.0.deref()
    }
}

/// A mutable borrow of a resource.
pub struct ResMut<'a, R>(RefMut<'a, R>);

impl<R> Deref for ResMut<'_, R> {
    type Target = R;

    fn deref(&self) -> &R {
        self.0.deref()
    }
}

impl<R> DerefMut for ResMut<'_, R> {
    fn deref_mut(&mut self) -> &mut R {
        self.0.deref_mut()
    }
}

#[derive(Default)]
struct TypeIdHasher(u64);

impl Hasher for TypeIdHasher {
    fn write_u64(&mut self, val: u64) {
        self.0 = val;
    }

    fn write(&mut self, _val: &[u8]) {
        unreachable!();
    }

    fn finish(&self) -> u64 {
        self.0
    }
}

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

    #[test]
    fn insert_then_get() {
        let mut resources = Resources::new();

        resources.insert(42_u64);

        let res = resources.get::<u64>();
        assert_eq!(*res, 42);
    }

    #[test]
    fn get_mut_then_get() {
        let mut resources = Resources::new();

        resources.insert(42_u64);

        {
            let mut res = resources.get_mut::<u64>();
            *res = 23;
        }

        let res = resources.get::<u64>();
        assert_eq!(*res, 23);
    }

    #[test]
    #[should_panic]
    fn insert_does_not_replace() {
        let mut resources = Resources::new();

        resources.insert(23_i32);
        resources.insert(42_i32);
    }

    #[test]
    fn borrows_can_be_shared() {
        let mut resources = Resources::new();

        resources.insert(23_i32);

        let _res = resources.get::<i32>();
        let _res = resources.get::<i32>();
    }

    #[test]
    #[should_panic]
    fn mutable_borrows_are_exclusive() {
        let mut resources = Resources::new();

        resources.insert(23_i32);

        let _res = resources.get_mut::<i32>();
        let _res = resources.get_mut::<i32>();
    }
}