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
use atomic_refcell::{AtomicRef, AtomicRefMut};
use std::fmt;
use std::ops::{Deref, DerefMut};

/// Shared view over a [`Resource`](crate::resources::Resource).
pub struct Res<'a, T>(AtomicRef<'a, T>);

impl<'a, T> Res<'a, T> {
    pub(crate) fn new(resource: AtomicRef<'a, T>) -> Self {
        Self(resource)
    }
}

/// Exclusive view over a [`Resource`](crate::resources::Resource).
pub struct ResMut<'a, T>(AtomicRefMut<'a, T>);

impl<'a, T> ResMut<'a, T> {
    pub(crate) fn new(resource: AtomicRefMut<'a, T>) -> Self {
        Self(resource)
    }
}

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

macro_rules! impl_res_common {
    ($Res:ident) => {
        impl<T> Deref for $Res<'_, T> {
            type Target = T;

            fn deref(&self) -> &Self::Target {
                self.0.deref()
            }
        }

        impl<T> fmt::Debug for $Res<'_, T>
        where
            T: fmt::Debug,
        {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_tuple(stringify!($Res))
                    .field(self.0.deref())
                    .finish()
            }
        }

        impl<T> fmt::Display for $Res<'_, T>
        where
            T: fmt::Display,
        {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Display::fmt(self.0.deref(), f)
            }
        }
    };
}

impl_res_common!(Res);
impl_res_common!(ResMut);