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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Allocator abstraction for [`BStack`]-backed region management.
//!
//! # Overview
//!
//! This module provides three region handle types and a pair of allocator traits:
//!
//! * [`BStackRange`] — a raw `(offset, len)` coordinate pair with no backing
//! reference. `Copy`, serializable, suitable for on-disk storage. No I/O.
//!
//! * [`BStackOwnedSlice<'a, A>`](BStackOwnedSlice) — the **ownership handle**
//! for one allocation. Returned by [`alloc`](BStackAllocator::alloc) and
//! consumed by [`realloc`](BStackAllocator::realloc) /
//! [`dealloc`](BStackAllocator::dealloc). Non-`Copy`, non-`Clone`.
//! No direct I/O; use [`as_slice`](BStackOwnedSlice::as_slice) or
//! [`as_slice_mut`](BStackOwnedSlice::as_slice_mut) to get a view.
//!
//! * [`BStackSlice<'a>`](BStackSlice) — a **borrowed I/O view**. Does not
//! carry an allocator; carries `&'a BStack` directly. Non-`Copy`, `Clone`.
//! Exposes `read*(&self)` and (with `set`) `write*(&mut self)`. Subsliceable.
//!
//! * [`BStackSliceReader`] — a cursor-based reader ([`io::Read`] + [`io::Seek`]).
//!
//! * [`BStackSliceWriter`] — a cursor-based writer ([`io::Write`] + [`io::Seek`],
//! `set` feature).
//!
//! * [`BStackAllocator`] — allocator trait. `alloc`/`realloc`/`dealloc`
//! take and return `Self::Allocated<'a>`, which must implement
//! `Into<BStackOwnedSlice<'a, Self>>`. [`into_stack`](BStackAllocator::into_stack)
//! consumes the allocator; outstanding owned slices statically prevent this.
//!
//! * [`BStackBulkAllocator`] — extension trait for atomic bulk
//! [`alloc_bulk`](BStackBulkAllocator::alloc_bulk) /
//! [`dealloc_bulk`](BStackBulkAllocator::dealloc_bulk).
//!
//! * [`BStackUninitAllocator`] — opt-in extension trait for allocators with a
//! cheaper uninitialised path. [`alloc_uninit`](BStackUninitAllocator::alloc_uninit) /
//! [`realloc_uninit`](BStackUninitAllocator::realloc_uninit) skip the
//! zero-fill of newly allocated or grown bytes, returning **unspecified**
//! (but always valid-to-read) contents for callers that overwrite the region
//! immediately.
//!
//! * [`BStackOwnedSliceAllocator`] — convenience supertrait:
//! `BStackAllocator<Error = io::Error, Allocated<'a> = BStackOwnedSlice<'a, Self>>`.
//!
//! * [`BStackByteVec`] — growable `u8` vector backed by a [`BStack`] allocation
//! (`alloc` + `set`). 16-byte header stores `len`/`cap` for crash recovery.
//!
//! * Standard allocator implementations: [`LinearBStackAllocator`], [`FirstFitBStackAllocator`],
//! [`GhostTreeBstackAllocator`], [`SlabBStackAllocator`], and [`CheckedSlabBStackAllocator`].
//!
//! # Standard Allocators
//!
//! * [`LinearBStackAllocator`] — bump allocator that always appends to the tail.
//! `Send` without `atomic`; `Send + Sync` with `atomic`.
//!
//! * [`FirstFitBStackAllocator`] — persistent first-fit free-list allocator
//! (`alloc` + `set`). Adjacent free blocks coalesce on dealloc.
//! `Send` without `atomic`; `Send + Sync` with `atomic`.
//!
//! * [`GhostTreeBstackAllocator`] — pure-AVL general-purpose allocator
//! (`alloc` feature). Zero per-block overhead.
//! `Send` in all configurations; `Send + Sync` with `atomic`.
//!
//! * [`SlabBStackAllocator`] — fixed-block slab allocator (`alloc` + `set`).
//! O(1) alloc/dealloc.
//!
//! * [`CheckedSlabBStackAllocator`] — crash-recoverable slab variant (`alloc` + `set`).
//! 8-byte per-block header tracks state; double-frees caught.
//!
//! # Region handle design
//!
//! The three handle types cleanly separate concerns:
//!
//! | Type | Carries | Copy | I/O | Alloc ops |
//! |----------------------------------------------|--------------|------|----------|-----------|
//! | [`BStackRange`] | nothing | yes | no | no |
//! | [`BStackOwnedSlice<'a,A>`](BStackOwnedSlice) | `&'a A` | no | via view | yes |
//! | [`BStackSlice<'a>`](BStackSlice) | `&'a BStack` | no | yes | no |
//!
//! `BStackOwnedSlice` is non-`Copy` and non-`Clone`: an allocation has exactly
//! one owner. Consuming it for `realloc` or `dealloc` is a compile error if
//! any view (`BStackSlice`) derived from it is still live — views are tied to
//! the handle's borrow by `as_slice<'s>(&'s self) -> BStackSlice<'s>`.
//!
//! `BStackSlice` is non-`Copy` so that `write*(&mut self)` provides genuine
//! single-writer exclusivity within safe code: a slice cannot be silently
//! duplicated out of a `&mut` borrow. It is `Clone` for explicit second views.
//!
//! # Feature flags
//!
//! The `alloc` Cargo feature enables this module, including all allocator traits,
//! handle types, and [`LinearBStackAllocator`] / [`GhostTreeBstackAllocator`]:
//!
//! ```toml
//! bstack = { version = "0.1", features = ["alloc"] }
//! ```
//!
//! [`BStackSliceWriter`], [`FirstFitBStackAllocator`], [`SlabBStackAllocator`],
//! [`CheckedSlabBStackAllocator`], and [`BStackByteVec`] additionally require `set`:
//!
//! ```toml
//! bstack = { version = "0.1", features = ["alloc", "set"] }
//! ```
//!
//! # Crash consistency
//!
//! Every individual [`BStack`] operation performs a durable sync before returning.
//! At the allocator level, operations spanning multiple [`BStack`] calls are not
//! automatically atomic. Each allocator documents which operations are
//! single-call (crash-safe by inheritance) and which are multi-call (requiring
//! explicit recovery design, typically write-ahead ordering).
//!
//! # Trait implementations
//!
//! All three handle types implement `PartialEq`/`Eq` and `PartialOrd`/`Ord` on
//! `(offset, len)`, and `Hash` consistently. `BStackRange` also implements
//! `From<[u8; 16]>` and `From<BStackRange> for [u8; 16]` for serialization.
//!
//! `BStackSliceReader` and `BStackSliceWriter` implement `PartialEq`/`PartialOrd`
//! by absolute payload position. Both cross-compare with each other and with a
//! bare `BStackSlice` (slice comparison ignores cursor).
use crateBStack;
use fmt;
use io;
pub use BStackSliceWriter;
pub use ;
/// Error returned by [`BStackAllocator::realloc`] and
/// [`BStackAllocator::dealloc`] when the operation fails.
///
/// A failed resize or free almost always leaves a valid allocation behind — the
/// original region is untouched, or the new region is fully committed (in which
/// case the operation should have succeeded). This type carries that surviving
/// allocation back to the caller so it can retry, fall back, or explicitly
/// [`dealloc`](BStackAllocator::dealloc) it rather than leak it. Because
/// [`BStackOwnedSlice`]'s `Drop` is a no-op, dropping the handle instead of
/// returning it here would silently leak the region.
///
/// It implements [`std::error::Error`] (delegating [`Display`](fmt::Display) to
/// [`source`](Self::source)), so `?` works within functions that return it.
/// Note that converting *out* to a bare `Self::Error` necessarily discards the
/// recovered handle, so that conversion is intentionally left explicit — the
/// caller must decide what to do with the allocation first.
// Manual `Debug` (rather than derive) because `A::Allocated<'a>` is not bound
// by `Debug`. We surface only whether the handle was recovered, which is the
// diagnostically useful bit and needs no bound on `Allocated`.
// `A::Error` is only bound by `Debug + Display`, not `Error`, so `source()`
// cannot be forwarded; the default (`None`) is used.
/// Error returned by [`BStackBulkAllocator::dealloc_bulk`] when the bulk free
/// fails, carrying back the handles that were **not** freed.
///
/// This is the bulk analogue of [`BStackAllocError`]: rather than a single
/// optional handle it holds a `Vec` of the still-owned handles, so a failed
/// bulk free does not silently leak the regions it could not reclaim (recall
/// that [`BStackOwnedSlice`]'s `Drop` is a no-op).
///
/// It implements [`std::error::Error`] (delegating [`Display`](fmt::Display) to
/// [`source`](Self::source)), so `?` works within functions that return it.
// Manual `Debug` (rather than derive) because `A::Allocated<'a>` is not bound
// by `Debug`. We surface how many handles were recovered, which needs no bound.
/// A trait for types that own a [`BStack`] and manage contiguous byte regions
/// within its payload.
///
/// # Ownership model
///
/// An implementor takes ownership of a [`BStack`]. [`BStackOwnedSlice`] handles
/// produced by [`alloc`](Self::alloc) borrow the allocator for lifetime `'_`,
/// which prevents the allocator from being consumed by
/// [`into_stack`](Self::into_stack) while any slice is alive. The canonical
/// pattern:
///
/// ```rust,ignore
/// struct MyAllocator { stack: BStack }
///
/// impl BStackAllocator for MyAllocator {
/// // Or some richer type that implements Debug + Display
/// type Error = io::Error;
///
/// // Or some richer type that implements Into<BStackOwnedSlice<'a, Self>>
/// type Allocated<'a> = BStackOwnedSlice<'a, Self>;
///
/// fn stack(&self) -> &BStack { &self.stack }
/// fn into_stack(self) -> BStack { self.stack }
/// fn alloc(&self, len: u64) -> io::Result<BStackOwnedSlice<'_, Self>> { ... }
/// fn realloc<'a>(&'a self, handle: BStackOwnedSlice<'a, Self>, new_len: u64)
/// -> Result<BStackOwnedSlice<'a, Self>, BStackAllocError<'a, Self>> { ... }
/// }
/// ```
///
/// On the failure path, `realloc`/`dealloc` return a [`BStackAllocError`]
/// carrying the surviving allocation (see that type for the `handle`
/// contract), so a failed operation never silently leaks the region.
///
/// # Crash consistency
///
/// Implementors **must** document the crash-consistency class of each
/// operation they provide. As a rule of thumb: if every method maps to a
/// single [`BStack`] call it is crash-safe by inheritance; if any method
/// issues two or more calls it requires an explicit recovery design.
///
/// # See also
///
/// [`BStackBulkAllocator`] — extension trait that adds atomic bulk
/// [`alloc_bulk`](BStackBulkAllocator::alloc_bulk) and
/// [`dealloc_bulk`](BStackBulkAllocator::dealloc_bulk) methods for
/// allocators that can batch multiple operations into a single I/O call.
/// Extension trait for allocators that support batching multiple allocations
/// and deallocations in a single operation.
///
/// Both methods must be **atomic**: on success every requested item is
/// allocated or deallocated; on failure the backing store is left unchanged —
/// no partial allocation or deallocation is permitted, unless a crash occurs in
/// the middle of the underlying operation, in which case the backing store may be
/// partially updated but must remain internally consistent and recoverable by the
/// allocator's crash recovery procedure. Implementors should also reduce I/O
/// overhead relative to repeated single-item calls, for example by issuing a reduced
/// [`BStack::extend`] or [`BStack::discard`] call.
///
/// Implementations should not simply loop over single-item `alloc` or `dealloc` calls,
/// as this would not provide the intended atomicity guarantees. Even if protected
/// under some crash safety and rollback mechanism, such an implementation is still not
/// recommended due to its misleading semantics and potential performance pitfalls.
/// Extension trait for allocators that can skip zero-initialisation of newly
/// allocated or grown regions.
///
/// [`BStackAllocator::alloc`] guarantees a zero-initialised region and
/// [`realloc`](BStackAllocator::realloc) zero-fills any newly added bytes when
/// growing. That guarantee costs a write: a region pulled from a free list may
/// hold leftover bytes from a previous allocation, which the allocator must
/// scrub before returning. Callers that immediately overwrite the whole region
/// (for example, `write`-ing a serialized record right after `alloc`) have no
/// use for that zero-fill. This trait lets them opt out of it.
///
/// The bytes in a region returned by [`alloc_uninit`](Self::alloc_uninit), or
/// in the newly added portion of a region returned by
/// [`realloc_uninit`](Self::realloc_uninit), are **unspecified**: they may be
/// zero, or may be leftover bytes from a previous allocation that occupied the
/// same on-disk space. They are always valid to read — no undefined behavior
/// results, unlike `MaybeUninit<u8>` in memory — but callers must not rely on
/// their value until they have written to the region themselves. This mirrors
/// `Vec::with_capacity` followed by `set_len`, except no analog of `set_len` is
/// needed since the bytes are always valid to read, just unspecified in value.
///
/// # Implementing this trait is optional
///
/// Implementing it signals that the allocator actually has a cheaper
/// uninitialised path. Allocators for which zero-fill is already free — an
/// always-extend bump allocator whose growth goes through [`BStack::extend`]
/// (the tail is already zero via `set_len` on a sparse file), or an allocator
/// that scrubs blocks eagerly on free — gain nothing and may either implement
/// the trait as a thin wrapper around `alloc`/`realloc` or not implement it at
/// all. The savings are concentrated in the free-list-reuse path, where a
/// previously-occupied block is handed back without being scrubbed first.
/// Convenience supertrait for the common case of a [`BStackAllocator`] whose
/// handle type is [`BStackOwnedSlice`] and whose error type is [`io::Error`].
///
/// Requires `'static` because the `for<'a>` higher-ranked bound implies the
/// allocator must outlive any borrow of its own slices. All allocators
/// provided by this library own their data and satisfy this bound automatically.
///
/// Generic code that does not need custom handle or error types can use
/// `A: BStackOwnedSliceAllocator` as a compact replacement for the three-part bound:
///
/// ```rust,ignore
/// // Verbose form:
/// A: 'static + BStackAllocator<Error = io::Error>,
/// for<'a> A: BStackAllocator<Allocated<'a> = BStackOwnedSlice<'a, A>>,
///
/// // Compact form:
/// A: BStackOwnedSliceAllocator,
/// ```
// Macros
// Read a little-endian value of type `$ty` from `$buf` at offset `$off`.
pub use CheckedSlabBStackAllocator;
pub use FirstFitBStackAllocator;
pub use GhostTreeBstackAllocator;
pub use ;
pub use ;
pub use LinearBStackAllocator;
pub use SlabBStackAllocator;
pub use ;