[][src]Crate ruspiro_singleton

Singleton pattern implementation

Provide a cross core synchronisation safe singleton implementation pattern

Example

use ruspiro_singleton::*;

static FOO: Singleton<Foo> = Singleton::new(Foo::new(0));

struct Foo {
    count: u32,
}

impl Foo {
    pub const fn new(initial_count: u32) -> Self {
        Foo {
            count: initial_count,
        }
    }

    pub fn count(&self) -> u32 {
        self.count    
    }

    pub fn add_count(&mut self, value: u32) -> u32 {
        self.count += value;
        self.count
    }
}

fn main () {
    let counter = FOO.take_for( |foo| {
        println!("secure access to the singleton");
        // do something with the singleton, it is mutable inside 'take_for'
        let c = foo.add_count(1);
        // and return any value, the return value of take_for is inferred from the return
        // value of the closure given to this function.
        c
    });

    println!("successfull {}", counter);
}

In case only immutable access to the contents of the singleton is required the use_for function can be used.


fn main () {
    let counter = FOO.use_for( |foo| {
            foo.count()
        });

    println!("current counter: {}", counter);
}

Structs

Singleton

The Singleton wrapper stores any type