mtb_entity_slab/lib.rs
1//! # MTB Entity Allocator and Utilities
2//!
3//! Address-stable, internally mutable entity Slab allocator. Mainly solves the problem
4//! where `Slab` cannot allocate new elements while reading existing ones.
5//!
6//! 地址稳定、内部可变的实体 Slab 分块分配器. 主要解决 `Slab` 无法在读取元素的同时
7//! 分配新元素的问题.
8//!
9//! ## Example 使用示例
10//!
11//! ```
12//! use mtb_entity_slab::{EntityAlloc, PtrID, IEntityAllocID, IEntityAllocatable, EntityAllocPolicy256};
13//!
14//! #[derive(Debug, Clone, PartialEq, Eq)]
15//! struct Inst {
16//! pub opcode: u32,
17//! pub operands: [u64; 4],
18//! pub heap_data: String,
19//! }
20//! impl IEntityAllocatable for Inst {
21//! type AllocatePolicyT = EntityAllocPolicy256<Self>;
22//! }
23//!
24//! impl Inst {
25//! fn new(opcode: u32) -> Self {
26//! Self {
27//! opcode,
28//! operands: [0; 4],
29//! heap_data: format!("InstData{}", opcode),
30//! }
31//! }
32//! }
33//!
34//! fn main() {
35//! let mut alloc = EntityAlloc::with_capacity(1024);
36//! let ptrs = {
37//! let mut v = Vec::new();
38//! for i in 0..1000 {
39//! let ptr = alloc.allocate(Inst::new(i));
40//! v.push(ptr);
41//! }
42//! v
43//! };
44//!
45//! let inst = ptrs[500].deref(&alloc);
46//!
47//! // Allocates a new element while reading existing ones
48//! // 在读取时分配新元素
49//! let new_id = alloc.allocate(Inst::new(2000));
50//! assert_eq!(inst.opcode, 500);
51//! assert_eq!(new_id.deref(&alloc).opcode, 2000);
52//!
53//! for &ptr in ptrs.iter() {
54//! let inst = ptr.deref(&alloc);
55//! let indexed_id = ptr.as_indexed(&alloc).unwrap();
56//! assert_eq!(inst.opcode as usize, indexed_id.0);
57//! assert!(ptr.free(&mut alloc).is_some());
58//! }
59//! }
60//! ```
61//!
62//! ## Safety 安全性
63//!
64//! This crate provides access to allocated elements via `PtrID`. `PtrID` contains a raw pointer,
65//! and most operations on `PtrID` are safe, but there is no ABA usage detection.
66//!
67//! This crate is designed for Remusys-IR and is for learning purposes only. It does not guarantee
68//! safety in all scenarios. Please carefully assess the risks when using it in production environments.
69//!
70//! 本库通过 `PtrID` 提供对分配元素的访问. `PtrID` 内部包含裸指针, 对 PtrID 的大多数操作都是安全的,
71//! 但没有 ABA 使用检测.
72//!
73//! 本库为 Remusys-IR 设计, 仅为学习用途, 不保证在所有场景下的安全性. 在生产环境中使用时请谨慎评估风险.
74
75mod alloc;
76mod bitalloc;
77mod chunk;
78mod container;
79mod id;
80mod iter;
81mod policy;
82
83pub use crate::{
84 alloc::{EntityAlloc, IEntityAllocatable},
85 chunk::NULL_INDEXED_ID,
86 container::ptrlist::*,
87 id::{IDProxy, IEntityAllocID, IndexedID, PtrID},
88 iter::{EntityAllocConsumeIter, EntityAllocEditIter, EntityAllocReadIter},
89 policy::*,
90};
91
92pub const MTBLIB_PACKAGE_NAME: &str = "io.medihbt.mtb.entity";
93pub const MTBLIB_PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
94
95mod tests;