Singlyton
Safe, single-threaded global state in Rust.
Debug assertions are present to ensure:
- Borrow checking (see
RefCell
) - Thread safety (two threads cannot access the same singleton)
- Sound usage of uninitialized memory
Why?
Single-threaded global state is a bit of a boogeyman in Rust:
static mut
is heavily discouraged due to its easy ability to cause UB through aliasing.- Thread locals can be slow for performance critical contexts, are nonsense to use in a single-threaded environment, and may not be available on all platforms
- Working around Rust's thread-safety mechanisms in single-threaded contexts can be ugly, annoying and unnecessary
Usage
First, add singlyton
as a dependency of your project in your Cargo.toml
file:
[]
= "*"
Singleton
use Singleton;
static SINGLETON: = new;
debug_assert_eq!;
SINGLETON.replace;
debug_assert_eq!;
*SINGLETON.get_mut = "Test 2";
debug_assert_eq!;
SingletonUninit
use SingletonUninit;
static SINGLETON: = uninit;
SINGLETON.init;
debug_assert_eq!;
SINGLETON.replace;
debug_assert_eq!;
*SINGLETON.get_mut = "Test 2".to_string;
debug_assert_eq!;