[][src]Crate ruspiro_singleton

Singleton pattern implementation

Provide a cross core synchronisation safe singleton implementation pattern

Example

static MY_SINGLETON: Singleton<MySingleton> = Singleton::new(MySingleton::new(0));
 
struct MySingleton {
    count: u32,
}
 
impl MySingleton {
    pub fn new(initial_count: u32) -> Self {
        MySingleton {
            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 some_function () {
    let counter = MY_SINGLETON.take_for( |singleton| {
        println!("secure access to the singleton");
        // do something with the singleton, it is mutable inside 'take_for'
        let c = singleton.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 some_other_function() {
    let counter = MY_SINGLETON.use_for( |s| {
            s.count()
        });
 
    println!("current counter: {}", counter);
}

Structs

Singleton

The Singleton wrapper stores any type