use std::collections::HashMap;
use std::fmt::Write as _;
use mutate_once::MutOnce;
struct Single {
attr: MutOnce<Vec<u32>>,
}
impl Single {
fn new() -> Self {
Self { attr: MutOnce::new(Vec::new()) }
}
fn attr(&self) -> &[u32] {
if !self.attr.is_fixed() {
let mut v = self.attr.get_mut();
(0..5).for_each(|x| v.push(x * 2));
}
self.attr.get_ref()
}
}
#[test]
fn single() {
let x = Single::new();
assert_eq!(x.attr(), &[0, 2, 4, 6, 8]);
}
struct Collection {
hash_map: HashMap<u32, MutOnce<String>>,
}
impl Collection {
fn new() -> Self {
let mut hash_map = HashMap::new();
(0..10).for_each(|x| {
hash_map.insert(x, MutOnce::new(String::new()));
});
Self { hash_map }
}
fn get(&self, key: u32) -> Option<&str> {
self.hash_map.get(&key).map(|mo| {
if !mo.is_fixed() {
let mut v = mo.get_mut();
write!(v, "value at {}", key).unwrap();
}
mo.get_ref().as_str()
})
}
}
#[test]
fn collection() {
let x = Collection::new();
assert_eq!(x.get(0), Some("value at 0"));
assert_eq!(x.get(9), Some("value at 9"));
assert_eq!(x.get(10), None);
}