9 stable releases (3 major)

4.1.1 Nov 25, 2021
4.0.0 Nov 25, 2021
3.0.0 Nov 24, 2021
2.0.0 Nov 21, 2021
1.2.1 Nov 21, 2021

#481 in Concurrency

Download history 20/week @ 2023-10-24 26/week @ 2023-10-31 45/week @ 2023-11-07 44/week @ 2023-11-14 31/week @ 2023-11-21 51/week @ 2023-11-28 19/week @ 2023-12-05 16/week @ 2023-12-12 8/week @ 2023-12-19 29/week @ 2023-12-26 38/week @ 2024-01-02 52/week @ 2024-01-09 44/week @ 2024-01-16 221/week @ 2024-01-23 227/week @ 2024-01-30 52/week @ 2024-02-06

552 downloads per month

MIT license

26KB
426 lines

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:

[dependencies]
singlyton = "*"

Singleton

use singlyton::Singleton;

static SINGLETON: Singleton<&'static str> = Singleton::new("Hello");
debug_assert_eq!(*SINGLETON.get(), "Hello");

SINGLETON.replace("Test");
debug_assert_eq!(*SINGLETON.get(), "Test");

*SINGLETON.get_mut() = "Test 2";
debug_assert_eq!(*SINGLETON.get(), "Test 2");

SingletonUninit

use singlyton::SingletonUninit;

static SINGLETON: SingletonUninit<String> = SingletonUninit::uninit();

SINGLETON.init("Hello".to_string());
debug_assert_eq!(SINGLETON.get().as_str(), "Hello");

SINGLETON.replace("Test".to_string());
debug_assert_eq!(SINGLETON.get().as_str(), "Test");

*SINGLETON.get_mut() = "Test 2".to_string();
debug_assert_eq!(SINGLETON.get().as_str(), "Test 2");

Dependencies

~20KB