From 23156b0c5107b7a84bc27f35130094a7833b8d15 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 30 Oct 2019 09:56:18 +0100 Subject: [PATCH] Use CriticalSection<'cs> instead of &'cs CriticalSection. Fixes #7. A `CriticalSection<'cs>` has a size of zero unlike a `&'cs CriticalSection`, which has the size of a pointer. --- src/lib.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 47a6b8e..d76da36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ #![no_std] use core::cell::UnsafeCell; +use core::marker::PhantomData; /// A peripheral #[derive(Debug)] @@ -26,7 +27,7 @@ impl Peripheral { } /// 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() } } @@ -39,17 +40,18 @@ impl Peripheral { /// 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. pub unsafe fn new() -> Self { - CriticalSection { _0: () } + CriticalSection { _0: PhantomData } } } @@ -75,13 +77,13 @@ impl Mutex { impl Mutex { /// 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) /// }