1 unstable release

Uses old Rust 2015

0.1.0 Nov 1, 2018

#407 in No standard library

Download history 69/week @ 2024-03-14 83/week @ 2024-03-21 103/week @ 2024-03-28 72/week @ 2024-04-04 76/week @ 2024-04-11 106/week @ 2024-04-18 87/week @ 2024-04-25 67/week @ 2024-05-02 64/week @ 2024-05-09 71/week @ 2024-05-16 71/week @ 2024-05-23 70/week @ 2024-05-30 46/week @ 2024-06-06 51/week @ 2024-06-13 66/week @ 2024-06-20 32/week @ 2024-06-27

200 downloads per month
Used in 6 crates (via alloc-singleton)

MIT/Apache

8KB

owned-singleton

Owned singletons

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


lib.rs:

Owned singletons

An owned singleton is a proxy (struct) that grants exclusive access to a static mut variable.

Features

Owned singletons are smaller than &'static mut references; they are zero sized types.

Doesn't sound useful enough to you? The Singleton abstraction can be used to implement statically allocated memory pools whose handles are a single byte in size and are automatically deallocated on drop.

Examples

The Singleton attribute creates a proxy (struct) for the given static mut variable and implements the Singleton, Deref, DerefMut and StableDerefs traits for it.

use owned_singleton::Singleton;

#[Singleton]
static mut FOO: u32 = 0;

let mut foo = unsafe { FOO::new() };
assert_eq!(*foo, 0);
*foo += 1;
assert_eq!(*foo, 1);

let bar: &'static mut u32 = foo.unwrap();
assert_eq!(*bar, 1);

The Singleton attribute doesn't implement the Send or Sync traits by default; this results in a proxy struct that does not implement Send or Sync. To opt into the Send and Sync traits add the Send and Sync arguments to the Singleton attribute.

use owned_singleton::Singleton;

#[Singleton(Send, Sync)]
static mut FOO: u32 = 0;

fn is_send<T>() where T: Send {}
fn is_sync<T>() where T: Sync {}

is_send::<FOO>();
is_sync::<FOO>();

Using Singleton on a static variable results in DerefMut not being implemented for the proxy struct. However, the proxy struct will still be a handle to a static mut variable so there's no Sync requirement on the type of the static mut variable.

use std::marker::PhantomData;

use owned_singleton::Singleton;

// `PhantomData<*const ()>` does not implement `Send` or `Sync`
#[Singleton]
static FOO: PhantomData<*const ()> = PhantomData;

Dependencies

~2.5MB
~52K SLoC