-
-
Save pzol/8903534 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#[feature(macro_rules)]; | |
use std::hashmap::HashMap; | |
macro_rules! lazy_init( | |
($(static ref $n:ident : $t:ty = $e:expr;)*) => ( | |
$( | |
struct $n; | |
impl $n { | |
#[allow(dead_code)] | |
fn get(&self) -> &'static $t { | |
use std::unstable::mutex::{Once, ONCE_INIT}; | |
use std::cast::transmute; | |
unsafe { | |
static mut s: *$t = 0 as *$t; | |
static mut ONCE: Once = ONCE_INIT; | |
ONCE.doit(|| { | |
s = transmute::<~$t, *$t>(~($e)); | |
}); | |
&*s | |
} | |
} | |
} | |
)* | |
) | |
) | |
lazy_init!( | |
static ref NUMBER: uint = times_two(3); | |
static ref VEC: [uint, ..3] = [1, 2, 3]; | |
static ref OWNED_STRING: ~str = ~"hello"; | |
static ref HASHMAP: HashMap<uint, &'static str> = { | |
let mut m = HashMap::new(); | |
m.insert(0u, "abc"); | |
m.insert(1, "def"); | |
m.insert(2, "ghi"); | |
m | |
}; | |
) | |
fn times_two(n: uint) -> uint { | |
n * 2 | |
} | |
#[test] | |
fn test_basic() { | |
assert_eq!(OWNED_STRING.get(), &~"hello"); | |
assert_eq!(NUMBER.get(), &6); | |
assert!(HASHMAP.get().find(&1).is_some()); | |
assert!(HASHMAP.get().find(&3).is_none()); | |
assert_eq!(VEC.get().as_slice(), &[1, 2, 3]); | |
} | |
#[test] | |
fn test_repeat() { | |
assert_eq!(NUMBER.get(), &6); | |
assert_eq!(NUMBER.get(), &6); | |
assert_eq!(NUMBER.get(), &6); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment