bstack_raii 0.1.0

Typed, RAII-style ownership and lifetime layer over the bstack allocation primitives
Documentation
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
//! [`BStackBinaryHeap<K, V>`]: an owned priority queue (binary min-heap).
//!
//! A priority queue keyed by a `Pod + Ord` priority `K`, carrying a block value
//! `V` the heap owns. [`pop`](BStackBinaryHeap::pop) always returns the entry
//! with the **smallest** key.
//!
//! # Array-backed, pointer-free
//!
//! Despite being a tree, a binary heap needs **no pointers**: it is a single
//! contiguous array with the tree structure implicit in the indices — the
//! children of slot `i` are `2i+1` and `2i+2`. So, like [`crate::BStackDeque`],
//! the entries live in one contiguous block (`[ (K, value_ref) ; cap ]`); only
//! the block pointer, capacity, and length live in the fixed handle, and growth
//! reallocates just that array. Each slot is the inline priority followed by a
//! `u64` reference to the owned value block.
//!
//! # Atomicity — single-writer
//!
//! `push` sifts a new element up and `pop` sifts the last element down; both
//! touch an `O(log n)` path of slots whose shape depends on key comparisons. Each
//! operation reads that path, then commits *all* of its slot moves plus the
//! length change as one crash-atomic [`bstack::BStack::set_batched`] batch — so a
//! crash never leaves the heap half-sifted (the ordering invariant is preserved
//! all-or-nothing). Because the sift is computed from reads taken before the
//! commit, the heap is **single-writer / multi-reader**: concurrent writers need
//! external synchronization; concurrent readers (and `peek`) are always fine.
//! Growth reallocates the array and swaps the descriptor atomically.

use core::marker::PhantomData;
use core::mem::size_of;
use std::io;

use crate::BStackRaiiAllocator;
use bstack::{BStack, BStackRange};
use bytemuck::{Pod, Zeroable};

use super::util::{alloc_image, read_fields, w8};
use crate::handback::ReplaceError;
use crate::io_core::{ClonePlan, TryCloneIn, dealloc_range};
use crate::primitives::{EightCC, checked_off_mul};
use crate::types::compiled::{BStackOwned, BlockHeader, HEADER_SIZE};
use crate::types::traits::{BStackBlock, BStackCast, BStackDrop};
use crate::util::{SmallBuf, get_u64, io_error, read_u64};

/// The on-disk image of a [`BStackBinaryHeap`]: header, array-block pointer
/// (`0` = none), capacity in slots, and element count. Non-generic.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct HeapOnDisk {
    /// The 16-byte block header (size + type tag).
    pub header: BlockHeader,
    /// Offset of the `[(K, value_ref); cap]` array block, or `0` when unallocated.
    pub data: u64,
    /// Number of slots in the array.
    pub cap: u64,
    /// Number of elements currently held.
    pub len: u64,
}

const DATA_OFF: u64 = HEADER_SIZE; // 16
const CAP_OFF: u64 = HEADER_SIZE + 8; // 24
const LEN_OFF: u64 = HEADER_SIZE + 16; // 32
const HEAP_SIZE: u64 = size_of::<HeapOnDisk>() as u64;
const MIN_CAP: u64 = 4;

/// An owned binary min-heap of `(K, V)` entries.
pub struct BStackBinaryHeap<K: Pod + Ord, V: BStackBlock> {
    range: BStackRange,
    _marker: PhantomData<fn() -> (K, V)>,
}

impl<K: Pod + Ord, V: BStackBlock> BStackBinaryHeap<K, V> {
    fn ksize() -> usize {
        size_of::<K>()
    }
    /// Bytes per slot: inline priority `K` + a `u64` value reference.
    fn stride() -> u64 {
        Self::ksize() as u64 + 8
    }

    /// The absolute offset of slot `i` in the array at `data`, rejecting overflow.
    /// `data`/`i` (via a corrupted on-disk `len`/`cap`) are not otherwise bounded
    /// against the array's real allocated size, so an unchecked `data + i*stride`
    /// could wrap to an unrelated in-file offset that a write then corrupts.
    fn slot_off(data: u64, i: u64) -> io::Result<u64> {
        checked_off_mul(data, i, Self::stride())
    }

    fn value_size() -> u64 {
        size_of::<<V as BStackBlock>::OnDisk>() as u64
    }
    fn value_at(off: u64) -> V {
        unsafe { <V as BStackBlock>::from_range(BStackRange::new(off, Self::value_size())) }
    }
    fn read_key(slot: &[u8]) -> K {
        bytemuck::pod_read_unaligned::<K>(&slot[..Self::ksize()])
    }
    fn slot_val(slot: &[u8]) -> u64 {
        get_u64(&slot[Self::ksize()..Self::ksize() + 8])
    }

    /// Read `(data, cap, len)` — the three contiguous handle fields — in one I/O.
    fn read_meta(stack: &BStack, handle: u64) -> io::Result<(u64, u64, u64)> {
        let [data, cap, len] = read_fields::<3>(stack, handle + DATA_OFF)?;
        Ok((data, cap, len))
    }

    /// Read the `stride` raw bytes of slot `i`.
    fn read_slot(stack: &BStack, data: u64, i: u64) -> io::Result<Vec<u8>> {
        let mut buf = vec![0u8; Self::stride() as usize];
        stack.get_into(Self::slot_off(data, i)?, &mut buf)?;
        Ok(buf)
    }

    /// Allocate an empty heap (no array until the first push).
    pub fn new<A: BStackRaiiAllocator>(allocator: &A) -> io::Result<BStackOwned<Self>> {
        Self::with_image(allocator, 0, 0)
    }

    /// Allocate an empty heap with room for `cap` elements pre-reserved.
    pub fn with_capacity<A: BStackRaiiAllocator>(
        allocator: &A,
        cap: u64,
    ) -> io::Result<BStackOwned<Self>> {
        if cap == 0 {
            return Self::new(allocator);
        }
        // `cap` is caller-supplied: check the multiply once (a wrap would under-size the
        // allocation while the descriptor records the full `cap`, so later slot writes
        // would land outside the array) and reuse it for the rollback dealloc.
        let size = cap
            .checked_mul(Self::stride())
            .ok_or_else(|| io_error!("heap capacity overflow"))?;
        let data = allocator.alloc(size)?.as_range().start();
        match Self::with_image(allocator, data, cap) {
            Ok(o) => Ok(o),
            Err(e) => {
                // SAFETY: the array was just allocated, linked to nothing.
                let _ = unsafe { dealloc_range(allocator, BStackRange::new(data, size)) };
                Err(e)
            }
        }
    }

    fn with_image<A: BStackRaiiAllocator>(
        allocator: &A,
        data: u64,
        cap: u64,
    ) -> io::Result<BStackOwned<Self>> {
        let od = HeapOnDisk {
            header: BlockHeader {
                size: HEAP_SIZE,
                tag: Self::eightcc(),
            },
            data,
            cap,
            len: 0,
        };
        let range = alloc_image(allocator, bytemuck::bytes_of(&od))?;
        // SAFETY: a freshly allocated block owned by no other handle.
        Ok(unsafe { BStackOwned::from_raw(Self::from_range(range)) })
    }

    /// Number of elements.
    pub fn len(&self, stack: &BStack) -> io::Result<u64> {
        read_u64(stack, self.range.start() + LEN_OFF)
    }

    /// Whether the heap is empty.
    pub fn is_empty(&self, stack: &BStack) -> io::Result<bool> {
        Ok(self.len(stack)? == 0)
    }

    /// Current array capacity.
    pub fn capacity(&self, stack: &BStack) -> io::Result<u64> {
        read_u64(stack, self.range.start() + CAP_OFF)
    }

    /// A **borrowed** view of the minimum entry (no ownership), or `None` if
    /// empty.
    pub fn peek(&self, stack: &BStack) -> io::Result<Option<(K, V)>> {
        let (data, _cap, len) = Self::read_meta(stack, self.range.start())?;
        if len == 0 {
            return Ok(None);
        }
        let slot = Self::read_slot(stack, data, 0)?;
        Ok(Some((
            Self::read_key(&slot),
            Self::value_at(Self::slot_val(&slot)),
        )))
    }

    /// Insert `key -> value`, taking ownership of the value block.
    ///
    /// Sifts the new element up and commits the whole path atomically.
    pub fn push<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        key: K,
        value: BStackOwned<V>,
    ) -> Result<(), ReplaceError<BStackOwned<V>>> {
        let handle = self.range.start();
        let stride = Self::stride();
        // Guard the value block: on failure [`finish_handback`] returns it to the
        // caller rather than freeing it, defused once linked.
        let value = value.auto(allocator);
        let val_ref = value.range().start();
        let key_bytes = bytemuck::bytes_of(&key).to_vec();

        let outcome: io::Result<()> = (|| loop {
            let (data, cap, len) = Self::read_meta(allocator.stack(), handle)?;
            if data == 0 || len >= cap {
                self.grow(allocator)?;
                continue;
            }
            // The new element's slot bytes: priority then value ref.
            let mut new_slot = Vec::with_capacity(stride as usize);
            new_slot.extend_from_slice(&key_bytes);
            new_slot.extend_from_slice(&val_ref.to_le_bytes());

            // Sift up: walk toward the root, moving greater parents down into the
            // hole, until the new key is `>=` its parent.
            let mut hole = len;
            let mut writes: Vec<(u64, SmallBuf)> = Vec::new();
            while hole > 0 {
                let parent = (hole - 1) / 2;
                let parent_slot = Self::read_slot(allocator.stack(), data, parent)?;
                if Self::read_key(&parent_slot) > key {
                    writes.push((
                        Self::slot_off(data, hole)?,
                        SmallBuf::Heap(parent_slot.into_boxed_slice()),
                    ));
                    hole = parent;
                } else {
                    break;
                }
            }
            writes.push((
                Self::slot_off(data, hole)?,
                SmallBuf::Heap(new_slot.into_boxed_slice()),
            ));
            writes.push(w8(handle + LEN_OFF, len + 1));
            allocator.stack().set_batched(writes)?;
            // Linked into the heap.
            return Ok(());
        })();
        value.finish_handback(outcome)
    }

    /// Remove and return the minimum entry (its value block owned), or `None` if
    /// empty. Sifts the last element down and commits the whole path atomically.
    pub fn pop<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
    ) -> io::Result<Option<(K, BStackOwned<V>)>> {
        let handle = self.range.start();
        let (data, _cap, len) = Self::read_meta(allocator.stack(), handle)?;
        if len == 0 {
            return Ok(None);
        }
        let min_slot = Self::read_slot(allocator.stack(), data, 0)?;
        let min_key = Self::read_key(&min_slot);
        let min_val = Self::slot_val(&min_slot);

        if len == 1 {
            allocator
                .stack()
                .set(handle + LEN_OFF, 0u64.to_le_bytes())?;
            // SAFETY: the value block's ownership transfers to the caller.
            return Ok(Some((min_key, unsafe {
                BStackOwned::from_raw(Self::value_at(min_val))
            })));
        }

        // Re-place the last element from the root down.
        let last_slot = Self::read_slot(allocator.stack(), data, len - 1)?;
        let last_key = Self::read_key(&last_slot);
        let newlen = len - 1;
        let mut hole = 0u64;
        let mut writes: Vec<(u64, SmallBuf)> = Vec::new();
        loop {
            let mut child = 2 * hole + 1;
            if child >= newlen {
                break;
            }
            let mut smaller = Self::read_slot(allocator.stack(), data, child)?;
            let mut smaller_key = Self::read_key(&smaller);
            if child + 1 < newlen {
                let right = Self::read_slot(allocator.stack(), data, child + 1)?;
                let right_key = Self::read_key(&right);
                if right_key < smaller_key {
                    smaller = right;
                    smaller_key = right_key;
                    child += 1;
                }
            }
            if smaller_key < last_key {
                writes.push((
                    Self::slot_off(data, hole)?,
                    SmallBuf::Heap(smaller.into_boxed_slice()),
                ));
                hole = child;
            } else {
                break;
            }
        }
        writes.push((
            Self::slot_off(data, hole)?,
            SmallBuf::Heap(last_slot.into_boxed_slice()),
        ));
        writes.push(w8(handle + LEN_OFF, newlen));
        allocator.stack().set_batched(writes)?;

        // SAFETY: the value block's ownership transfers to the caller.
        Ok(Some((min_key, unsafe {
            BStackOwned::from_raw(Self::value_at(min_val))
        })))
    }

    /// Grow the array to at least double its capacity, copying the elements and
    /// atomically swapping the descriptor.
    fn grow<A: BStackRaiiAllocator>(&self, allocator: &A) -> io::Result<()> {
        let handle = self.range.start();
        let stride = Self::stride();
        let (data, cap, len) = Self::read_meta(allocator.stack(), handle)?;
        let newcap = if cap == 0 {
            MIN_CAP
        } else {
            cap.saturating_mul(2)
        };
        // A corrupted on-disk `cap` near `u64::MAX` would otherwise make
        // `cap * 2` wrap small (silently swapping in a tiny array while `len`
        // still reflects the old count) or panic under overflow-checks; reject
        // it instead of ever installing a smaller-or-equal capacity.
        if newcap <= cap {
            return Err(io_error!("corrupt heap capacity"));
        }
        let new_size = newcap
            .checked_mul(stride)
            .ok_or_else(|| io_error!("heap capacity overflow"))?;
        let newdata = allocator.alloc(new_size)?.as_range().start();

        // Copy the live elements into the new (orphan) array.
        if len > 0 {
            let len_size = len
                .checked_mul(stride)
                .ok_or_else(|| io_error!("heap length overflow"))?;
            let mut buf = vec![0u8; len_size as usize];
            allocator.stack().get_into(data, &mut buf)?;
            allocator.stack().set(newdata, buf)?;
        }
        // Swap the descriptor's `data`/`cap` (contiguous) in one atomic write.
        let mut meta = [0u8; 16];
        meta[0..8].copy_from_slice(&newdata.to_le_bytes());
        meta[8..16].copy_from_slice(&newcap.to_le_bytes());
        allocator.stack().set(handle + DATA_OFF, meta)?;

        if data != 0 {
            // SAFETY: the descriptor no longer points at the old array.
            let _ = unsafe {
                dealloc_range(
                    allocator,
                    BStackRange::new(data, cap.saturating_mul(stride)),
                )
            };
        }
        Ok(())
    }
}

impl<K: Pod + Ord, V: BStackBlock> BStackCast for BStackBinaryHeap<K, V> {
    /// A `"Hep"` prefix perturbed by the key size and value type's tag.
    fn eightcc() -> EightCC {
        const BASE: EightCC = EightCC::new([b'H', b'e', b'p', 0x80, 0x81, 0x82, 0x83, 0x84]);
        BASE.mix(EightCC::new((size_of::<K>() as u64).to_le_bytes()))
            .mix(<V as BStackCast>::eightcc())
    }
}

// Self-contained (no separate control block): may be `#[embed]`ded.
impl<K: Pod + Ord, V: BStackBlock> crate::types::traits::BStackEmbeddable
    for BStackBinaryHeap<K, V>
{
}

impl<K: Pod + Ord, V: BStackBlock> BStackBlock for BStackBinaryHeap<K, V> {
    type OnDisk = HeapOnDisk;

    unsafe fn from_range(range: BStackRange) -> Self {
        BStackBinaryHeap {
            range,
            _marker: PhantomData,
        }
    }

    fn range(&self) -> BStackRange {
        self.range
    }

    /// Recursively free every value block and the array, **without** freeing the
    /// handle block itself.
    fn __bstack_drop_children<A: BStackRaiiAllocator>(
        allocator: &A,
        range: BStackRange,
    ) -> io::Result<()> {
        let handle = range.start();
        let (data, cap, len) = Self::read_meta(allocator.stack(), handle)?;
        for i in 0..len {
            let slot = Self::read_slot(allocator.stack(), data, i)?;
            let v = Self::slot_val(&slot);
            if v != 0 {
                // SAFETY: the heap solely owns each value block.
                let owned = unsafe { BStackOwned::from_raw(Self::value_at(v)) };
                owned.bstack_drop(allocator)?;
            }
        }
        if data != 0 {
            let size = cap
                .checked_mul(Self::stride())
                .ok_or_else(|| io_error!("heap capacity overflow"))?;
            // SAFETY: the heap solely owns its array block.
            unsafe { dealloc_range(allocator, BStackRange::new(data, size))? };
        }
        Ok(())
    }

    /// Deep-clone: pack the elements into a fresh, exactly-sized array with each
    /// value deep-cloned, and stage the handle, in the parent plan's atomic commit.
    fn __bstack_clone_children_inplace<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        plan: &mut ClonePlan,
    ) -> io::Result<Self::OnDisk> {
        let handle = self.range.start();
        let stride = Self::stride();
        let ksize = Self::ksize();
        let (data, _cap, len) = Self::read_meta(allocator.stack(), handle)?;

        let (new_data, new_cap) = if len > 0 {
            // Untrusted `len`: checked math + stack bound, matching the grow
            // path's `checked_mul` guards.
            let arr_size = len
                .checked_mul(stride)
                .ok_or_else(|| io_error!("heap length overflow"))?;
            if arr_size > allocator.len()? {
                return Err(io_error!("heap element array larger than the stack"));
            }
            let mut image = vec![0u8; arr_size as usize];
            allocator.stack().get_into(data, &mut image)?;
            // Deep-clone each value and repoint its ref in the copy (heap order
            // is preserved, so the array stays a valid heap).
            for i in 0..len as usize {
                let vo = i * stride as usize + ksize;
                let vref = get_u64(&image[vo..vo + 8]);
                let cloned = Self::value_at(vref)
                    .__bstack_clone_into(allocator, plan)?
                    .start();
                image[vo..vo + 8].copy_from_slice(&cloned.to_le_bytes());
            }
            let dst = plan.alloc_raw(allocator, arr_size)?;
            plan.write(dst.start(), image);
            (dst.start(), len)
        } else {
            (0, 0)
        };

        let od = HeapOnDisk {
            header: BlockHeader {
                size: HEAP_SIZE,
                tag: Self::eightcc(),
            },
            data: new_data,
            cap: new_cap,
            len,
        };
        Ok(od)
    }
}

impl<K: Pod + Ord, V: BStackBlock> TryCloneIn for BStackBinaryHeap<K, V> {}