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
use std::{
    any::type_name,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::NonNull,
};

/// Type alias for list of borrows
pub type Borrows = SmallVec<[Access; 8]>;

use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
use smallvec::{smallvec, SmallVec};

use crate::{Access, Context, Error, Result};

use super::ComponentBorrow;

/// Wrapper type for an immutably borrowed value from schedule context
#[repr(transparent)]
#[derive(Debug)]
pub struct Read<'a, T>(pub(crate) AtomicRef<'a, T>);

impl<'a, T> Clone for Read<'a, T> {
    fn clone(&self) -> Self {
        Self(AtomicRef::<'a, T>::clone(&self.0))
    }
}

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

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

impl<'a, T> Read<'a, T> {
    /// Creates a new Read borrow from an atomic ref
    pub fn new(borrow: AtomicRef<'a, T>) -> Self {
        Self(borrow)
    }
}

impl<'a, T: 'static> Read<'a, T> {
    pub(crate) fn try_from_untyped(cell: &'a AtomicRefCell<NonNull<u8>>) -> Result<Self> {
        cell.try_borrow()
            .map_err(|_| Error::Borrow(type_name::<T>()))
            .map(|cell| Self(AtomicRef::map(cell, |val| unsafe { val.cast().as_ref() })))
    }
}

#[repr(transparent)]
/// Wrapper type for an exclusively borrowed value
pub struct Write<'a, T>(pub(crate) AtomicRefMut<'a, T>);

impl<'a, T> Write<'a, T> {
    /// Creates a new Write borrow from an atomic ref
    pub fn new(borrow: AtomicRefMut<'a, T>) -> Self {
        Self(borrow)
    }
}

impl<'a, T: 'static> Write<'a, T> {
    pub(crate) fn try_from_untyped(cell: &'a AtomicRefCell<NonNull<u8>>) -> Result<Self> {
        cell.try_borrow_mut()
            .map_err(|_| Error::BorrowMut(type_name::<T>()))
            .map(|cell| {
                Self(AtomicRefMut::map(cell, |val| unsafe {
                    val.cast().as_mut()
                }))
            })
    }
}

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

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

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

struct BorrowMarker<T> {
    marker: PhantomData<T>,
}

/// Helper trait for borrowing either immutably or mutably from context
pub trait ContextBorrow<'a> {
    /// The resulting type after borrowing from context
    type Target;

    /// Borrow type from context
    fn borrow(context: &'a Context) -> Result<Self::Target>;
}

impl<'a, T: 'static> ContextBorrow<'a> for &'a T {
    type Target = Read<'a, T>;

    fn borrow(context: &'a Context) -> Result<Self::Target> {
        Read::try_from_untyped(context.cell::<&T>()?)
    }
}

impl<'a, T: 'static> ContextBorrow<'a> for &'a mut T {
    type Target = Write<'a, T>;

    fn borrow(context: &'a Context) -> Result<Self::Target> {
        Write::try_from_untyped(context.cell::<&mut T>()?)
    }
}

impl<'a, T: 'static> ContextBorrow<'a> for Read<'a, T> {
    type Target = Self;

    fn borrow(context: &'a Context) -> Result<Self::Target> {
        Read::try_from_untyped(context.cell::<&T>()?)
    }
}

impl<'a, T: 'static> ContextBorrow<'a> for Write<'a, T> {
    type Target = Self;

    fn borrow(context: &'a Context) -> Result<Self::Target> {
        Write::try_from_untyped(context.cell::<&mut T>()?)
    }
}

impl<'a, T: 'static> ComponentBorrow for Read<'a, T> {
    fn borrows() -> Borrows {
        smallvec![Access::of::<&BorrowMarker<T>>()]
    }

    fn has<U: crate::IntoAccess>() -> bool {
        Access::of::<&T>() == U::access()
    }

    fn has_dynamic(id: std::any::TypeId, exclusive: bool) -> bool {
        let l = Access::of::<&T>();

        l.id == id && !exclusive
    }
}

impl<'a, T: 'static> ComponentBorrow for Write<'a, T> {
    fn borrows() -> Borrows {
        smallvec![Access::of::<&mut BorrowMarker<T>>()]
    }

    fn has<U: crate::IntoAccess>() -> bool {
        Access::of::<&mut T>().id == U::access().id
    }

    fn has_dynamic(id: std::any::TypeId, _: bool) -> bool {
        let l = Access::of::<&mut T>();

        l.id == id
    }
}