2 个版本
| 新 0.1.1 | 2024 年 8 月 22 日 |
|---|---|
| 0.1.0 | 2024 年 8 月 22 日 |
#654 在 Rust 模式
30KB
452 行
TAny 是为 Tiny Any 设计的
简介
TAny 是一个库,它提供了一个名为 TAny 的容器,作为 Box<dyn Any> 的直接替代品。它旨在在值适合存储时避免分配。目前存储大小是 usize 的 3 倍,最大对齐为 8 字节。如果值的尺寸或对齐方式大于存储,它将在堆上分配并装箱。
用法
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::<u32>().unwrap();
// Get reference to the value.
let r: &mut u32 = a.downcast_mut::<u32>().unwrap();
// Take ownership of the value.
let a: u32 = a.downcast::<u32>().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<dyn Any + Send + Sync> = Box::new(42u32);
// Construct TAny from existing Box<dyn Any>.
let a: TAny = TAny::from_any(any); // Or use `From<Box<dyn Any + Send + Sync>>` trait.
assert_eq!(a.downcast_ref::<u32>().unwrap(), &42);
TAny 需要类型实现 Send 和 Sync。反过来,TAny 本身也是 Send 和 Sync。
对于非 Send 和非 Sync 类型,tany 软件包提供了与 TAny 具有相同 API 的 LTAny 类型,唯一的区别是没有 Send 和 Sync 约束。