Skip to content

Commit 37bed90

Browse files
bors[bot]m-ou-se
andauthored
Merge #20
20: Use CriticalSection<'cs> instead of &'cs CriticalSection. r=jonas-schievink a=m-ou-se Fixes #7. A `CriticalSection<'cs>` has a size of zero unlike a `&'cs CriticalSection`, which has the size of a pointer. Co-authored-by: Mara Bos <[email protected]>
2 parents 8010da7 + 23156b0 commit 37bed90

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/lib.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![no_std]
66

77
use core::cell::UnsafeCell;
8+
use core::marker::PhantomData;
89

910
/// A peripheral
1011
#[derive(Debug)]
@@ -26,7 +27,7 @@ impl<T> Peripheral<T> {
2627
}
2728

2829
/// Borrows the peripheral for the duration of a critical section
29-
pub fn borrow<'cs>(&self, _ctxt: &'cs CriticalSection) -> &'cs T {
30+
pub fn borrow<'cs>(&self, _ctxt: CriticalSection<'cs>) -> &'cs T {
3031
unsafe { &*self.get() }
3132
}
3233

@@ -39,18 +40,19 @@ impl<T> Peripheral<T> {
3940
/// Critical section token
4041
///
4142
/// Indicates that you are executing code within a critical section
42-
pub struct CriticalSection {
43-
_0: (),
43+
#[derive(Clone, Copy)]
44+
pub struct CriticalSection<'cs> {
45+
_0: PhantomData<&'cs ()>,
4446
}
4547

46-
impl CriticalSection {
48+
impl<'cs> CriticalSection<'cs> {
4749
/// Creates a critical section token
4850
///
4951
/// This method is meant to be used to create safe abstractions rather than
5052
/// meant to be directly used in applications.
5153
#[inline(always)]
5254
pub unsafe fn new() -> Self {
53-
CriticalSection { _0: () }
55+
CriticalSection { _0: PhantomData }
5456
}
5557
}
5658

@@ -76,13 +78,13 @@ impl<T> Mutex<T> {
7678

7779
impl<T> Mutex<T> {
7880
/// Borrows the data for the duration of the critical section
79-
pub fn borrow<'cs>(&'cs self, _cs: &'cs CriticalSection) -> &'cs T {
81+
pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T {
8082
unsafe { &*self.inner.get() }
8183
}
8284
}
8385

8486
/// ``` compile_fail
85-
/// fn bad(cs: &bare_metal::CriticalSection) -> &u32 {
87+
/// fn bad(cs: bare_metal::CriticalSection) -> &u32 {
8688
/// let x = bare_metal::Mutex::new(42u32);
8789
/// x.borrow(cs)
8890
/// }

0 commit comments

Comments
 (0)