embed_collections/lib.rs
1#![allow(rustdoc::redundant_explicit_links)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(docsrs, allow(unused_attributes))]
4#![cfg_attr(not(feature = "std"), no_std)]
5//!
6//! # embed-collections
7//!
8//! A collection of memory efficient data structures, for embedding environment and server applications that need tight memory management.
9//!
10//! This crate provides two categories of modules:
11//!
12//! - Cache efficient collections:
13//! - [const_vec](crate::const_vec): Fixed capacity inline vec
14//! - [seg_list](#seglist--various): A cache aware (short-live) list to store elements with adaptive size segments
15//! - [various](#seglist--various): A short-live list wrapping `SegList` with `Option<T>` to delay allocation.
16//! - [btree](#btree): A cache aware B+tree for lone-live and large dataset, optimized for numeric types, with special entry API allows peeking adjacent values.
17//! - [various_map](crate::various_map): A short-live map wrapping BTreeMap (std) with `Option<(K, V)>` to delay allocation.
18//!
19//! - [Intrusive collections](#intrusive-collections):
20//! - Supports various smart pointer types: owned (Box), multiple ownership (Arc, Rc), raw pointers (`NonNull<T>`, `*const T`, `*mut T`)
21//! - [dlist](crate::dlist): Intrusive Doubly Linked List (Queue / Stack).
22//! - [slist](crate::slist): Intrusive Singly Linked List ( Queue / stack).
23//! - [slist_owned](crate::slist_owned): An intrusive slist but with safe and more compact interface
24//! - [avl](crate::avl): Intrusive AVL Tree (Balanced Binary Search Tree), port to rust from ZFS
25//!
26//! ## SegList & Various
27//!
28//! [SegList](crate::seg_list) and [Various](crate::various) is designed for parameter passing.
29//!
30//! More CPU-cache friendly compared to `LinkedList`. And because it does not re-allocate, it's faster than `Vec::push()` when the number of elements is small.
31//! It's nice to the memory allocator (always allocate with fixed size segment).
32//!
33//! Benchmark: append + drain (x86_64, cache line 128 bytes):
34//!
35//! (platform: intel i7-8550U)
36//!
37//! | Elements | SegList | Vec | SegList vs Vec |
38//! |----------|---------|-----|----------------|
39//! | 10 | 40.5 ns | 147.0 ns | **3.6x faster** |
40//! | 32 | 99.1 ns | 237.8 ns | **2.4x faster** |
41//! | 100 | 471.1 ns | 464.0 ns | ~1.0x |
42//! | 500 | 2.77 µs | 895.5 ns | 3.1x slower |
43//!
44//! ## B+tree
45//!
46//! We provide a [BTreeMap](crate::btree) for single-threaded long-term in-memory storage.
47//! It's a cache aware b+tree:
48//!
49//! - Nodes are filled up in 4 cache lines (256 bytes on x86_64).
50//! - Capacity in compile-time determined according to the size of Key, Value.
51//! - Reduce memory fragmentation by alignment.
52//! - **Optimised for numeric key**
53//! - Respecting numeric space for sequential insertion.
54//! - Reduce latency for sequential insertion.
55//! - Faster iteration and teardown
56//! - **Limitation**:
57//! - K should have clone (for propagate into the InterNode during split)
58//! - K & V should <= CACHE_LINE_SIZE - 16
59//! - It make sure InterNode can hold at least two children.
60//! - If K & V is large you should put into `Box`, for room saving, and for the speed to move value
61//! - **Special API**:
62//! - Peak and move to previous/next `Entry` (for modification).
63//! - Alter key of an OccupiedEntry.
64//! - Batch remove with range.
65//! - Movable `Cursor` (for readonly)
66//!
67//! Compared to std::collections::btree (as of rust 1.94):
68//! - The std impl is pure btree (not b+tree) without horizontal links. Each key store only once at either leaf and inter nodes.
69//! - The std impl is optimised for point lookup.
70//! - The std impl has fixed Cap=11, node size varies according to T. (For T=U64, size is 288B for InterNode and 192B for LeafNode)
71//! - The std cursor API is still unstable (as of 1.94) and relatively complex to use.
72//!
73//! **benchmark**
74//!
75//! platform: intel i7-8550U, key: u32, value: u32, rust 1.92.
76//!
77//! Measured in million ops for different size of dataset:
78//!
79//! insert_seq |btree|std
80//! -|-|-
81//! 1k|**88.956**|20.001
82//! 10k|**75.291**|16.04
83//! 100k|**45.959**|11.207
84//!
85//! insert_rand|btree|std|avl(box)|avl(arc)
86//! -|-|-|-|-
87//! 1k|**21.311**|17.792|11.172|9.5397
88//! 10k|**14.268**|11.587|6.3669|5.651
89//! 100k|**5.4814**|3.0691|0.78|0.732
90//!
91//! get_seq|btree|std
92//! -|-|-
93//! 1k|**59.448**|34.248
94//! 10k|**37.225**|27.571
95//! 100k|**30.77**|19.907
96//!
97//! get_rand|btree|std|avl(box)|avl(arc)
98//! -|-|-|-|-
99//! 1k|**47.33**|27.651|24.254|23.466
100//! 10k|**19.358**|16.868|11.771|10.806
101//! 100k|**5.2584**|3.2569|1.4423|1.2712
102//!
103//! remove_rand |btree|std
104//! -|-|-
105//! 1k|**20.965**|15.968
106//! 10k|**16.073**|11.701
107//! 100k|**5.0214**|3.0724
108//!
109//! iter|btree|std
110//! -|-|-
111//! 1k|1342.8|346.8
112//! 10k|1209.4|303.83
113//! 100k|**152.57**|51.147
114//!
115//! into_iter|btree|std
116//! -|-|-
117//! 1k|396.07|143.81
118//! 10k|397.05|81.389
119//! 100k|**360.18**|56.742
120//!
121//!
122//! ## Intrusive Collections
123//!
124//! intrusive collection is often used in c/c++ code, they does not need extra allocation.
125//! But the disadvantages includes: complexity to write, bad for cache hit when the node is too small
126//!
127//! There're three usage scenarios:
128//!
129//! 1. Push smart pointer to the list, so that the list hold 1 ref count when the type is `Arc` /
130//! `Rc`, but you have to use UnsafeCell for internal mutation.
131//!
132//! 2. Push `Box` to the list, the list own the items until they are popped, it's better than std
133//! LinkedList because no additional allocation is needed.
134//!
135//! 3. Push raw pointer (better use NonNull instead of *const T for smaller footprint) to the list,
136//! for temporary usage. You must ensure the list item not dropped be other refcount
137//! (for example, the item is holding by Arc in other structure).
138//!
139//!
140//! ### Difference to `intrusive-collections` crate
141//!
142//! This crate choose to use trait instead of c like `offset_of!`, mainly because:
143//!
144//! - Mangling with offset conversion makes the code hard to read (for people not used to c style coding).
145//!
146//! - You don't have to understand some complex macro style.
147//!
148//! - It's dangerous to use pointer offset conversion when the embedded Node not perfectly aligned,
149//! and using memtion to return the node ref is more safer approach.
150//! For example, the default `repr(Rust)` might reorder the field, or you mistakenly use `repr(packed)`.
151//!
152//! ### instrusive link list example
153//!
154//! ```rust
155//! use embed_collections::{dlist::{DLinkedList, DListItem, DListNode}, Pointer};
156//! use std::cell::UnsafeCell;
157//! use std::sync::Arc;
158//!
159//! // The tag structure only for labeling, distinguish two lists
160//! struct CacheTag;
161//! struct IOTag;
162//!
163//! struct MyItem {
164//! val: i32,
165//! cache_link: UnsafeCell<DListNode<MyItem, CacheTag>>,
166//! io_link: UnsafeCell<DListNode<MyItem, IOTag>>,
167//! }
168//!
169//! impl MyItem {
170//! fn new(val: i32) -> Self {
171//! Self {
172//! val,
173//! cache_link: UnsafeCell::new(DListNode::default()),
174//! io_link: UnsafeCell::new(DListNode::default()),
175//! }
176//! }
177//! }
178//!
179//! unsafe impl DListItem<CacheTag> for MyItem {
180//! fn get_node(&self) -> &mut DListNode<Self, CacheTag> {
181//! unsafe { &mut *self.cache_link.get() }
182//! }
183//! }
184//!
185//! unsafe impl DListItem<IOTag> for MyItem {
186//! fn get_node(&self) -> &mut DListNode<Self, IOTag> {
187//! unsafe { &mut *self.io_link.get() }
188//! }
189//! }
190//!
191//! let mut cache_list = DLinkedList::<Arc<MyItem>, CacheTag>::new();
192//! let mut io_list = DLinkedList::<Arc<MyItem>, IOTag>::new();
193//!
194//! let item1 = Arc::new(MyItem::new(10));
195//! let item2 = Arc::new(MyItem::new(20));
196//!
197//! // Push the same item to both lists
198//! cache_list.push_back(item1.clone());
199//! io_list.push_back(item1.clone());
200//!
201//! cache_list.push_back(item2.clone());
202//! io_list.push_back(item2.clone());
203//!
204//! assert_eq!(cache_list.pop_front().unwrap().val, 10);
205//! assert_eq!(io_list.pop_front().unwrap().val, 10);
206//! assert_eq!(cache_list.pop_front().unwrap().val, 20);
207//! assert_eq!(io_list.pop_front().unwrap().val, 20);
208//! ```
209//!
210//! ## Feature Flags
211//!
212//! * **`default`**: Enabled by default. Includes the `std` features.
213//! * **`std`**: Enables integration with the Rust standard library, including the `println!` macro for debugging. Disabling this feature enables `no_std` compilation.
214//! * **`slist`**: Enables the singly linked list (`slist`) and owned singly linked list (`slist_owned`) modules.
215//! * **`dlist`**: Enables the doubly linked list (`dlist`) module.
216//! * **`avl`**: Enables the `avl` module.
217//! * **`btree`**: Enable the btree module.
218//! * **`full`**: Enabled by default. Includes `slist`, `dlist`, and `avl`.
219//!
220//! To compile with `no_std` and only the `slist` module, you would use:
221//! `cargo build --no-default-features --features slist`
222
223extern crate alloc;
224#[cfg(any(feature = "std", test))]
225extern crate std;
226
227use alloc::boxed::Box;
228use alloc::rc::Rc;
229use alloc::sync::Arc;
230use core::ptr::NonNull;
231
232/// Abstract pointer trait to support various pointer types in collections.
233///
234/// This trait allows the collections to work with:
235/// - `Box<T>`: Owned, automatically dropped.
236/// - `Arc<T>`: Shared ownership.
237/// - `Rc<T>`: Single thread ownership.
238/// - `NonNull<T>`: Raw non-null pointers (manual memory management).
239/// - `*const T`: Raw pointers (recommend to use `NonNull<T>` instead)
240pub trait Pointer: Sized {
241 type Target;
242
243 fn as_ref(&self) -> &Self::Target;
244
245 #[inline(always)]
246 fn as_ptr(&self) -> *const Self::Target {
247 self.as_ref() as *const Self::Target
248 }
249
250 #[allow(clippy::missing_safety_doc)]
251 unsafe fn from_raw(p: *const Self::Target) -> Self;
252
253 fn into_raw(self) -> *const Self::Target;
254}
255
256pub trait SmartPointer: Pointer {
257 fn new(t: Self::Target) -> Self;
258}
259
260#[allow(clippy::unnecessary_cast)]
261impl<T> Pointer for *const T {
262 type Target = T;
263
264 #[inline]
265 fn as_ref(&self) -> &Self::Target {
266 unsafe { &**self }
267 }
268
269 #[inline]
270 unsafe fn from_raw(p: *const Self::Target) -> Self {
271 p as *const T
272 }
273
274 #[inline]
275 fn into_raw(self) -> *const Self::Target {
276 self as *const T
277 }
278}
279
280#[allow(clippy::unnecessary_cast)]
281impl<T> Pointer for *mut T {
282 type Target = T;
283
284 #[inline]
285 fn as_ref(&self) -> &Self::Target {
286 unsafe { &**self }
287 }
288
289 #[inline]
290 unsafe fn from_raw(p: *const Self::Target) -> Self {
291 p as *mut T
292 }
293
294 #[inline]
295 fn into_raw(self) -> *const Self::Target {
296 self as *mut T
297 }
298}
299
300impl<T> Pointer for NonNull<T> {
301 type Target = T;
302
303 #[inline]
304 fn as_ref(&self) -> &Self::Target {
305 unsafe { self.as_ref() }
306 }
307
308 #[inline]
309 unsafe fn from_raw(p: *const Self::Target) -> Self {
310 unsafe { NonNull::new_unchecked(p as *mut T) }
311 }
312
313 #[inline]
314 fn into_raw(self) -> *const Self::Target {
315 self.as_ptr()
316 }
317}
318
319impl<T> Pointer for Box<T> {
320 type Target = T;
321
322 #[inline]
323 fn as_ref(&self) -> &Self::Target {
324 self
325 }
326
327 #[inline]
328 unsafe fn from_raw(p: *const Self::Target) -> Self {
329 unsafe { Box::from_raw(p as *mut T) }
330 }
331
332 #[inline]
333 fn into_raw(self) -> *const Self::Target {
334 Box::into_raw(self)
335 }
336}
337
338impl<T> SmartPointer for Box<T> {
339 #[inline]
340 fn new(inner: T) -> Self {
341 Box::new(inner)
342 }
343}
344
345impl<T> Pointer for Rc<T> {
346 type Target = T;
347
348 #[inline]
349 fn as_ref(&self) -> &Self::Target {
350 self
351 }
352
353 #[inline]
354 unsafe fn from_raw(p: *const Self::Target) -> Self {
355 unsafe { Rc::from_raw(p) }
356 }
357
358 #[inline]
359 fn into_raw(self) -> *const Self::Target {
360 Rc::into_raw(self)
361 }
362}
363
364impl<T> SmartPointer for Rc<T> {
365 #[inline]
366 fn new(inner: T) -> Self {
367 Rc::new(inner)
368 }
369}
370
371impl<T> Pointer for Arc<T> {
372 type Target = T;
373
374 #[inline]
375 fn as_ref(&self) -> &Self::Target {
376 self
377 }
378
379 #[inline]
380 unsafe fn from_raw(p: *const Self::Target) -> Self {
381 unsafe { Arc::from_raw(p) }
382 }
383
384 #[inline]
385 fn into_raw(self) -> *const Self::Target {
386 Arc::into_raw(self)
387 }
388}
389
390impl<T> SmartPointer for Arc<T> {
391 #[inline]
392 fn new(inner: T) -> Self {
393 Arc::new(inner)
394 }
395}
396
397impl<T> Pointer for &T {
398 type Target = T;
399
400 #[inline]
401 fn as_ref(&self) -> &Self::Target {
402 self
403 }
404
405 #[inline]
406 unsafe fn from_raw(p: *const Self::Target) -> Self {
407 unsafe { &*p }
408 }
409
410 #[inline]
411 fn into_raw(self) -> *const Self::Target {
412 self as *const T
413 }
414}
415
416#[cfg(feature = "avl")]
417pub mod avl;
418pub mod const_vec;
419pub use const_vec::ConstVec;
420#[cfg(feature = "dlist")]
421pub mod dlist;
422pub mod seg_list;
423pub use seg_list::SegList;
424#[cfg(feature = "slist")]
425pub mod slist;
426#[cfg(feature = "slist")]
427pub mod slist_owned;
428pub mod various;
429pub use various::Various;
430#[allow(private_interfaces)]
431pub mod various_map;
432pub use various_map::VariousMap;
433#[cfg(feature = "btree")]
434pub mod btree;
435#[cfg(feature = "btree")]
436pub use btree::BTreeMap;
437
438#[cfg(test)]
439pub mod test;
440
441/// Cache line size in bytes
442#[cfg(any(
443 target_arch = "x86_64",
444 target_arch = "aarch64",
445 target_arch = "arm64ec",
446 target_arch = "powerpc64",
447))]
448pub const CACHE_LINE_SIZE: usize = 64;
449#[cfg(not(any(
450 target_arch = "x86_64",
451 target_arch = "aarch64",
452 target_arch = "arm64ec",
453 target_arch = "powerpc64",
454)))]
455pub const CACHE_LINE_SIZE: usize = 32;
456
457/// logging macro for development
458#[macro_export(local_inner_macros)]
459macro_rules! trace_log {
460 ($($arg:tt)+)=>{
461 #[cfg(feature="trace_log")]
462 {
463 log::debug!($($arg)+);
464 }
465 };
466}
467
468/// logging macro for development
469#[macro_export(local_inner_macros)]
470macro_rules! print_log {
471 ($($arg:tt)+)=>{
472 #[cfg(feature="trace_log")]
473 {
474 log::debug!($($arg)+);
475 }
476 #[cfg(not(feature="trace_log"))]
477 {
478 std::println!($($arg)+);
479 }
480 };
481}