[][src]Crate freezebox

Rust FreezeBox: a deref'able lazy-initialized container.

FreezeBox<T> is a container that can have two possible states:

  • uninitialized: deref is not allowed.
  • initialized: deref to a &T is possible.

To upgrade a FreezeBox to the initialized state, call lazy_init. lazy_init does not require a mutable reference, making FreezeBox suitable for sharing objects first and initializing them later.

Attempting to lazy_init more than once, or deref while uninitialized will cause a panic.

Examples

This example creates a shared data structure, then circles back to initialize one member.

use freezebox::FreezeBox;
use std::sync::Arc;

#[derive(Default)]
struct Resources {
    name: FreezeBox<String>
}

let resources = Arc::new(Resources::default());
let res2 = resources.clone();

let func = move || {
    // explicit deref
    assert_eq!(*res2.name, "Hello!");
    // implicit deref allows transparent access
    assert_eq!(res2.name.len(), 6);
    assert_eq!(&res2.name[2..], "llo!");
};

resources.name.lazy_init("Hello!".to_string());
func();

Structs

FreezeBox

FreezeBox is a deref'able lazy-initialized container.