dioxus/packages/generational-box
Rafał Krzyważnia 54dbe6d074
Use RwLock::read in SyncStorage (#2463)
Replaces `RwLock::try_read` with `RwLock::read` in `SyncStorage`. This change prioritizes potential deadlocks over panics, as unwrapping a failed `try_read` is deemed less desirable.
2024-05-30 07:05:20 -05:00
..
benches make the signal runtime global 2023-10-30 14:25:31 -05:00
src Use RwLock::read in SyncStorage (#2463) 2024-05-30 07:05:20 -05:00
tests fix signal error message and add tests (#2118) 2024-03-20 08:45:27 -07:00
Cargo.toml set up example scaping for docs.rs (#2450) 2024-05-28 13:05:55 -07:00
README.md fix(generational-box): polished README.md (#2168) 2024-03-28 10:23:11 -05:00

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.