https://github.com/zakarumych/tany
Tiny Any for Rust
https://github.com/zakarumych/tany
Last synced: about 2 months ago
JSON representation
Tiny Any for Rust
- Host: GitHub
- URL: https://github.com/zakarumych/tany
- Owner: zakarumych
- Created: 2024-08-22T11:42:39.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2024-08-22T11:59:36.000Z (10 months ago)
- Last Synced: 2024-10-31T11:47:37.639Z (8 months ago)
- Language: Rust
- Size: 5.86 KB
- Stars: 8
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# TAny is for Tiny Any
## Introduction
TAny is a library that provides container `TAny` as drop-in replacement for `Box`.
It is designed to avoid allocations when value fits into the storage.
Currently size of the storage is 3 times `usize` and max alignment is 8 bytes.
If size or alignment of the value is greater than the storage, it is allocated on heap and boxed.## Usage
```rust
use tany::TAny;// u32 fits inline storage, so no allocation is performed.
let a: TAny = TAny::new(42u32);// Get reference to the value.
let r: &u32 = a.downcast_ref::().unwrap();// Get reference to the value.
let r: &mut u32 = a.downcast_mut::().unwrap();// Take ownership of the value.
let a: u32 = a.downcast::().unwrap();let already_boxed = Box::new([1u32; 10]);
// Construct TAny from already boxed value.
// If type doesn't fit into the storage, the box is used as is,
// otherwise value is unboxed.
let a: TAny = TAny::from_box(already_boxed);assert_eq!(a.downcast_ref::<[u32; 10]>().unwrap(), &[1u32; 10]);
let any: Box = Box::new(42u32);
// Construct TAny from existing Box.
let a: TAny = TAny::from_any(any); // Or use `From>` trait.assert_eq!(a.downcast_ref::().unwrap(), &42);
````TAny` requires types to implement `Send` and `Sync`.
And in turn, `TAny` is `Send` and `Sync` itself.For non-`Send` and non-`Sync` types, `tany` crate provides `LTAny` type with all the same API as `TAny`,
except there's no `Send` and `Sync` bounds.