Skip to content

Commit

Permalink
Merge #20
Browse files Browse the repository at this point in the history
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 <m-ou.se@m-ou.se>
  • Loading branch information
bors[bot] and m-ou-se committed Jan 28, 2020
2 parents 8010da7 + 23156b0 commit 37bed90
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#![no_std]

use core::cell::UnsafeCell;
use core::marker::PhantomData;

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

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

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

impl CriticalSection {
impl<'cs> CriticalSection<'cs> {
/// Creates a critical section token
///
/// This method is meant to be used to create safe abstractions rather than
/// meant to be directly used in applications.
#[inline(always)]
pub unsafe fn new() -> Self {
CriticalSection { _0: () }
CriticalSection { _0: PhantomData }
}
}

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

impl<T> Mutex<T> {
/// Borrows the data for the duration of the critical section
pub fn borrow<'cs>(&'cs self, _cs: &'cs CriticalSection) -> &'cs T {
pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T {
unsafe { &*self.inner.get() }
}
}

/// ``` compile_fail
/// fn bad(cs: &bare_metal::CriticalSection) -> &u32 {
/// fn bad(cs: bare_metal::CriticalSection) -> &u32 {
/// let x = bare_metal::Mutex::new(42u32);
/// x.borrow(cs)
/// }
Expand Down

0 comments on commit 37bed90

Please sign in to comment.