Crate loan_cell

Source
Expand description

This crate provides a LoanCell type that allows for lending a reference to a value for a limited scope.

This is useful for publishing a reference to an on-stack value into a thread-local variable for the lifetime of a function call. This can be useful when you can’t or don’t want to temporarily move the value to the thread-local variable:

  • The value is not sized (e.g., it is a slice or a dyn trait object), so you can’t move it.
  • The value is large, so it would be inefficient to move it.
  • The value has a destructor, so putting it in TLS would use the inefficient form of Rust TLS that registers a destructor for the value.

LoanCell is not Sync or Send, so it can only be used within a single thread. This is necessary to ensure that the loaned value is not accessed after the function that loaned it returns.

§Example

use loan_cell::LoanCell;

thread_local! {
   static CONTEXT: LoanCell<str> = const { LoanCell::new() };
}

fn print_name() -> String {
    CONTEXT.with(|name| {
        name.borrow(|name| {
            format!("stored {}", name.unwrap_or("nowhere"))
        })
    })
}

CONTEXT.with(|v| {
    assert_eq!(v.lend(&String::from("in the heap"), || print_name()), "stored in the heap");
    assert_eq!(v.lend("statically", || print_name()), "stored statically");
});
assert_eq!(print_name(), "stored nowhere");

Structs§

  • A cell that allows lending a reference to a value for a limited scope.