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