Skip to content

Instantly share code, notes, and snippets.

@tjpalmer
Last active July 15, 2024 22:26
Show Gist options
  • Save tjpalmer/98896c66fe43705b470c392fe6cf872e to your computer and use it in GitHub Desktop.
Save tjpalmer/98896c66fe43705b470c392fe6cf872e to your computer and use it in GitHub Desktop.
Rust 1.63-compatible RwLock static init example
pub fn init() {
static INIT_ONCE: std::sync::Once = std::sync::Once::new();
INIT_ONCE.call_once(|| {
let mut zero__2 = 0;
{
*ZERO__2.write().unwrap() = Some(zero__2);
}
zero__2 = zero__2;
{
*ZERO__2.write().unwrap() = Some(zero__2);
}
println!(
"{}",
format!("{}{}", "fib(1)=", fib__1(self::zero__2() + 1).to_string())
);
println!(
"{}",
format!("{}{}", "fib(10)=", fib__1(self::zero__2() + 10).to_string())
);
println!(
"{}",
format!("{}{}", "fib(20)=", fib__1(self::zero__2() + 20).to_string())
);
});
}
static ZERO__2: std::sync::RwLock<Option<i32>> = std::sync::RwLock::new(None);
// The idea is that pub things ensure init.
pub fn zero() -> i32 {
init();
zero__2()
}
// And internal things should only call internal, never the pub version.
fn zero__2() -> i32 {
ZERO__2.read().unwrap().unwrap()
}
fn fib__1(mut i__3: i32) -> i32 {
let mut a__5: i32 = 0;
let mut b__6: i32 = 1;
while i__3 > 0 {
let c__7: i32 = a__5 + b__6;
a__5 = b__6;
b__6 = c__7;
i__3 = i__3 - 1;
}
return a__5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment