Crate deferred_cell

Source
Expand description

deferred-cell: A single-assignment, weak reference wrapper for write-once cyclic node graphs with late initialization.

This crate provides a lightweight alternative to runtime mutation or interior mutability when building write-once reference graphs such as cyclic trees or bidirectional structures.

Deferred<T> enables building self-referential or cyclic structures without interior mutability. It starts uninitialized, and can be set once with a weak reference to a value of type T.

To assign a value, use SetOnce::from followed by SetOnce::try_set.

After initialization, the reference can be accessed using Deferred::get or Deferred::try_get.

§Example

use deferred_cell::{Deferred, SetOnce, DeferredError};
use std::rc::Rc;

struct Node {
    value: String,
    neighbor: Deferred<Node>,
}

fn main() -> Result<(), DeferredError> {
    let node = Rc::new(Node {
        value: "A".into(),
        neighbor: Deferred::default(),
    });
    let neighbor = Rc::new(Node {
        value: "B".into(),
        neighbor: Deferred::default(),
    });

    SetOnce::from(&node.neighbor).try_set(&neighbor)?;
    let linked = node.neighbor.try_get()?;
    assert_eq!(linked.value, "B");
    // Calling `get()` will panic if node.neighbor is not initialized!
    assert_eq!(node.neighbor.get().value, "B");

    Ok(())
}

Structs§

Deferred
A write-once, weak reference wrapper for late initialization.
SetOnce
A write-once assignment interface for Deferred<T>.

Enums§

DeferredError
Errors thrown by deferred-cell

Traits§

DeferredIteratorExt
Iterator extension trait to improve the ergonomics of Deferred<T> collections