Created
August 20, 2019 06:46
-
-
Save pacmancoder/af0494bb2c57abe57f1ba4491feac083 to your computer and use it in GitHub Desktop.
Rust Discovery Initiative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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