9 releases

0.5.6 Jul 18, 2024
0.5.5 Jul 18, 2024
0.5.1 Apr 5, 2024
0.5.0 Mar 28, 2024
0.1.0 Dec 6, 2023

#127 in Memory management

Download history 3271/week @ 2024-04-05 2132/week @ 2024-04-12 1957/week @ 2024-04-19 2750/week @ 2024-04-26 3620/week @ 2024-05-03 3616/week @ 2024-05-10 3898/week @ 2024-05-17 3300/week @ 2024-05-24 3958/week @ 2024-05-31 3546/week @ 2024-06-07 3798/week @ 2024-06-14 3906/week @ 2024-06-21 3109/week @ 2024-06-28 2144/week @ 2024-07-05 2949/week @ 2024-07-12 2879/week @ 2024-07-19

11,637 downloads per month
Used in 66 crates (10 directly)

MIT/Apache

42KB
920 lines

Generational Box

Generational Box is a runtime for Rust that allows any static type to implement Copy. It can be combined with a global runtime to create an ergonomic state solution like dioxus-signals. This crate doesn't have any unsafe code.

Three main types manage state in Generational Box:

  • Store: Handles recycling generational boxes that have been dropped. Your application should have one store or one store per thread.
  • Owner: Handles dropping generational boxes. The owner acts like a runtime lifetime guard. Any states that you create with an owner will be dropped when that owner is dropped.
  • GenerationalBox: The core Copy state type. The generational box will be dropped when the owner is dropped.

Example:

use generational_box::{UnsyncStorage, AnyStorage};

// Create an owner for some state for a scope
let owner = UnsyncStorage::owner();

// Create some non-copy data, move it into a owner, and work with copy data
let data: String = "hello world".to_string();
let key = owner.insert(data);

// The generational box can be read from and written to like a RefCell
let value = key.read();
assert_eq!(*value, "hello world");

How it works

Internally, generational-box creates an arena of generational RefCells that are recycled when the owner is dropped. You can think of the cells as something like &'static RefCell<Box<dyn Any>> with a generational check to make recycling a cell easier to debug. Then GenerationalBoxes are Copy because the &'static pointer is Copy.

Dependencies

~0.4–5.5MB
~11K SLoC