Skip to content

Commit

Permalink
Make the crate no_std (#1)
Browse files Browse the repository at this point in the history
* Implement an alternative solution for the variance issue not involving `Mutex`

* Get rid of dependency on `std`
  • Loading branch information
yvt authored Jun 7, 2020
1 parent ce09654 commit 5877e23
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,19 @@
//! assert!(res);
//! }
//! ```
#![no_std]

use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::marker::PhantomData;
use std::fmt;
use std::default::Default;
use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use core::marker::PhantomData;
use core::fmt;
use core::default::Default;

/// A mutable Option<&'a, T> type which can be safely shared between threads.
#[repr(C)]
pub struct AtomicRef<'a, T: 'a> {
data: AtomicUsize,
_marker: PhantomData<Mutex<&'a T>>,
// Make `AtomicRef` invariant over `'a` and `T`
_marker: PhantomData<&'a mut &'a mut T>,
}

/// You will probably never need to use this type. It exists mostly for internal
Expand All @@ -104,6 +105,11 @@ pub const ATOMIC_U8_REF_INIT: AtomicRef<'static, u8> = AtomicRef {
_marker: PhantomData,
};

/// Re-export `core` for `static_atomic_ref!` (which may be used in a
/// non-`no_std` crate, where `core` is unavailable).
#[doc(hidden)]
pub use core::{mem as core_mem, ops as core_ops};

/// A macro to define a statically allocated `AtomicRef<'static, T>` which is
/// initialized to `None`.
///
Expand Down Expand Up @@ -134,12 +140,12 @@ macro_rules! static_atomic_ref {
};
(@$VIS:ident, $(#[$attr:meta])* static $N:ident : $T:ty; $($t:tt)*) => {
static_atomic_ref!(@MAKE TY, $VIS, $(#[$attr])*, $N);
impl ::std::ops::Deref for $N {
impl $crate::core_ops::Deref for $N {
type Target = $crate::AtomicRef<'static, $T>;
#[allow(unsafe_code)]
fn deref<'a>(&'a self) -> &'a $crate::AtomicRef<'static, $T> {
static STORAGE: $crate::AtomicRef<'static, u8> = $crate::ATOMIC_U8_REF_INIT;
unsafe { ::std::mem::transmute(&STORAGE) }
unsafe { $crate::core_mem::transmute(&STORAGE) }
}
}
static_atomic_ref!($($t)*);
Expand Down Expand Up @@ -403,7 +409,7 @@ impl<'a, T> Default for AtomicRef<'a, T> {

#[cfg(test)]
mod tests {
use std::sync::atomic::Ordering;
use core::sync::atomic::Ordering;

static_atomic_ref! {
static FOO: AtomicRef<i32>;
Expand Down

0 comments on commit 5877e23

Please sign in to comment.