14 releases (6 stable)

1.0.5 Dec 21, 2022
1.0.4 Jul 16, 2022
1.0.2 Nov 13, 2020
1.0.1 Nov 12, 2019
0.0.4 Mar 20, 2019

#290 in Rust patterns

Download history 5/week @ 2023-12-15 2/week @ 2023-12-22 25/week @ 2024-01-05 48/week @ 2024-01-12 24/week @ 2024-01-19 1/week @ 2024-01-26 4/week @ 2024-02-09 16/week @ 2024-02-16 40/week @ 2024-02-23 28/week @ 2024-03-01 25/week @ 2024-03-08 22/week @ 2024-03-15 25/week @ 2024-03-22 142/week @ 2024-03-29

217 downloads per month
Used in 8 crates (6 directly)

MIT/Apache

6KB
70 lines

🌍 Globals

docs.rs docs

Painless globals in Rust. Works with any type that implements Default trait.

When I first started studying Rust, getting a simple global variable was oddly difficult. As I became more experienced, I got tired of these weird macros hanging around my code. This is a library for people who like the simplicity of global singleton in a single one liner and instantiation with standard Default trait. This library also uses no standard library by default so it's great for web assembly and embedded development where you want as little extra as possible. Enjoy.

Edit as per Rust 1.63 - This library is less necessary thanks to static mutexes now being supported more broadly, but this library is still useful for lazy globals.

[dependencies]
globals = "1"
  • #![no_std] + alloc
  • leaves your code nice and clean

Example

struct Foo {
  v:u32
}

impl Default for Foo {
  fn default() -> Self {
    Foo {v:42}
  }
}

fn main() {
  let f = globals::get::<Foo>();
  assert_eq!(f.v,42);
}

How this works

Rust is a language that values memory safety. When it comes to globals, this means making sure there's exclusive access to things that can be written to. The primary mechanism for protecting globals which could potentially have multiple threads interacting with it is the Mutex. globals has a HashMap of singletons of various types stored in a Mutex. When you call get() it looks up your singleton, if it doesn't exist, it calls the Default trait method default() implementation of type to create the singleton instance and stores it in the hashmap. When get() is called, this Mutex wrapped singleton is locked and a handle is given to safely interact with this mutex wrapped value called a MutexGaurd<T>. You can interact with the mutex guard as if it were your singleton type (this why it magically looks like you are just interacting with a global). Once your mutex gaurd is dropped, your mutex is unlocked for other threads to interact with your singleton.

License

This project is licensed under either of

at your option.

Contribution

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

Dependencies

~150KB