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
use std::{
    any::{type_name, TypeId},
    cell::{Ref, RefCell, RefMut},
    iter,
    ops::{Deref, DerefMut},
};

use anymap::{any::Any, Map};

use crate::{
    fetch_resources::FetchResources,
    resources::{ResourceConflict, RwResources},
};

/// Store a set of arbitrary types inside `AtomicRefCell`s, and then access them for either reading
/// or writing.
pub struct ResourceSet {
    resources: Map<dyn Any>,
}

impl Default for ResourceSet {
    fn default() -> Self {
        ResourceSet {
            resources: Map::new(),
        }
    }
}

impl ResourceSet {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert<T>(&mut self, r: T) -> Option<T>
    where
        T: 'static,
    {
        self.resources
            .insert::<RefCell<T>>(RefCell::new(r))
            .map(|r| r.into_inner())
    }

    pub fn remove<T>(&mut self) -> Option<T>
    where
        T: 'static,
    {
        self.resources
            .remove::<RefCell<T>>()
            .map(|r| r.into_inner())
    }

    pub fn contains<T>(&self) -> bool
    where
        T: 'static,
    {
        self.resources.contains::<RefCell<T>>()
    }

    /// Borrow the given resource immutably.
    ///
    /// # Panics
    /// Panics if the resource has not been inserted or is already borrowed mutably.
    pub fn borrow<T>(&self) -> Ref<T>
    where
        T: 'static,
    {
        if let Some(r) = self.resources.get::<RefCell<T>>() {
            r.borrow()
        } else {
            panic!("no such resource {:?}", type_name::<T>());
        }
    }

    /// Borrow the given resource mutably.
    ///
    /// # Panics
    /// Panics if the resource has not been inserted or is already borrowed.
    pub fn borrow_mut<T>(&self) -> RefMut<T>
    where
        T: 'static,
    {
        if let Some(r) = self.resources.get::<RefCell<T>>() {
            r.borrow_mut()
        } else {
            panic!("no such resource {:?}", type_name::<T>());
        }
    }

    /// # Panics
    /// Panics if the resource has not been inserted.
    pub fn get_mut<T>(&mut self) -> &mut T
    where
        T: 'static,
    {
        if let Some(r) = self.resources.get_mut::<RefCell<T>>() {
            r.get_mut()
        } else {
            panic!("no such resource {:?}", type_name::<T>());
        }
    }

    /// Fetch the given `FetchResources`.
    pub fn fetch<'a, F>(&'a self) -> F
    where
        F: FetchResources<'a, Source = ResourceSet, Resources = RwResources<ResourceId>>,
    {
        F::fetch(self)
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct ResourceId(TypeId);

impl ResourceId {
    pub fn of<C: 'static>() -> ResourceId {
        ResourceId(TypeId::of::<C>())
    }
}

/// `SystemData` type that reads the given resource.
///
/// # Panics
/// Panics if the resource does not exist or has already been borrowed for writing.
pub struct Read<'a, T>(Ref<'a, T>);

impl<'a, T> FetchResources<'a> for Read<'a, T>
where
    T: 'static,
{
    type Source = ResourceSet;
    type Resources = RwResources<ResourceId>;

    fn check_resources() -> Result<RwResources<ResourceId>, ResourceConflict> {
        Ok(RwResources::from_iters(
            iter::once(ResourceId::of::<T>()),
            iter::empty(),
        ))
    }

    fn fetch(set: &'a ResourceSet) -> Self {
        Read(set.borrow())
    }
}

impl<'a, T> Deref for Read<'a, T> {
    type Target = T;

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

/// `SystemData` type that writes the given resource.
///
/// # Panics
/// Panics if the resource does not exist or has already been borrowed for writing.
pub struct Write<'a, T>(RefMut<'a, T>);

impl<'a, T> FetchResources<'a> for Write<'a, T>
where
    T: 'static,
{
    type Source = ResourceSet;
    type Resources = RwResources<ResourceId>;

    fn check_resources() -> Result<RwResources<ResourceId>, ResourceConflict> {
        Ok(RwResources::from_iters(
            iter::empty(),
            iter::once(ResourceId::of::<T>()),
        ))
    }

    fn fetch(set: &'a ResourceSet) -> Self {
        Write(set.borrow_mut())
    }
}

impl<'a, T> Deref for Write<'a, T> {
    type Target = T;

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

impl<'a, T> DerefMut for Write<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut *self.0
    }
}