Skip to content

Instantly share code, notes, and snippets.

@pacmancoder
Created August 20, 2019 06:46
Show Gist options
  • Save pacmancoder/af0494bb2c57abe57f1ba4491feac083 to your computer and use it in GitHub Desktop.
Save pacmancoder/af0494bb2c57abe57f1ba4491feac083 to your computer and use it in GitHub Desktop.
Rust Discovery Initiative
use core::sync::atomic::{ AtomicU32, Ordering };
struct Part {
val: u32,
}
struct Data {
a: Part,
b: Part,
}
impl Data {
const fn new() -> Data {
Data {
a: Part { val: 1 },
b: Part { val: 2 },
}
}
}
struct Singleton {
lock: AtomicU32,
data: Option<Data>,
}
static mut SINGLETON : Singleton = Singleton::new();
impl Singleton {
const fn new() -> Singleton {
Singleton {
lock: AtomicU32::new(0),
data: Some(Data::new()),
}
}
pub fn take() -> Option<Data> {
unsafe {
if SINGLETON.lock.compare_and_swap(0, 1, Ordering::SeqCst) == 0 {
Some(SINGLETON.data.take().unwrap())
} else {
None
}
}
}
}
fn print_part(val: Part) {
println!("\tPart: {}", val.val)
}
fn validate_singleton() {
let val = Singleton::take();
match val {
Some(data) => {
println!("\tI've got singletone!");
print_part(data.a);
print_part(data.b);
// the following should not compile:
//print_part(data.a);
}
None => println!("\tNah... No signletone for me..."),
}
}
fn main() {
println!("First try...");
validate_singleton();
println!("Second try...");
validate_singleton();
}
// Output:
// ====================================
// First try...
// I've got singletone!
// Part: 1
// Part: 2
// Second try...
// Nah... No signletone for me...
// ====================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment