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
use crate::prelude::v1::*;
use crate::base::*;
use crate::shim::*;

pub struct CriticalRegion;
impl CriticalRegion {
    pub fn enter() -> Self {
        unsafe { freertos_rs_enter_critical(); }

        CriticalRegion
    }
}

impl Drop for CriticalRegion {
    fn drop(&mut self) {
        unsafe { freertos_rs_exit_critical(); }
    }
}

unsafe impl<T: Sync + Send> Send for ExclusiveData<T> {}
unsafe impl<T: Sync + Send> Sync for ExclusiveData<T> {}

/// Data protected with a critical region. Lightweight version of a mutex,
/// intended for simple data structures.
pub struct ExclusiveData<T: ?Sized> {
    data: UnsafeCell<T>
}

impl<T> ExclusiveData<T> {
    pub fn new(data: T) -> Self {
        ExclusiveData {
            data: UnsafeCell::new(data)
        }
    }

    pub fn lock(&self) -> Result<ExclusiveDataGuard<T>, FreeRtosError> {
        Ok(ExclusiveDataGuard {
            __data: &self.data,
            __lock: CriticalRegion::enter()
        })
    }

    pub fn lock_from_isr(&self, _context: &mut crate::isr::InterruptContext) -> Result<ExclusiveDataGuardIsr<T>, FreeRtosError> {
        Ok(ExclusiveDataGuardIsr {
            __data: &self.data            
        })
    }
}

/// Holds the mutex until we are dropped
pub struct ExclusiveDataGuard<'a, T: ?Sized + 'a> {
    __data: &'a UnsafeCell<T>,
    __lock: CriticalRegion
}

impl<'mutex, T: ?Sized> Deref for ExclusiveDataGuard<'mutex, T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        unsafe { &*self.__data.get() }
    }
}

impl<'mutex, T: ?Sized> DerefMut for ExclusiveDataGuard<'mutex, T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { &mut *self.__data.get() }
    }
}


pub struct ExclusiveDataGuardIsr<'a, T: ?Sized + 'a> {
    __data: &'a UnsafeCell<T>
}

impl<'mutex, T: ?Sized> Deref for ExclusiveDataGuardIsr<'mutex, T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        unsafe { &*self.__data.get() }
    }
}

impl<'mutex, T: ?Sized> DerefMut for ExclusiveDataGuardIsr<'mutex, T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { &mut *self.__data.get() }
    }
}