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
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
//! [`BStackLinkedList<T>`]: an owned, doubly-linked list of block values.
//!
//! # Prefer a vector unless you actually need a list
//!
//! On disk a linked list is usually the *wrong* choice. Every traversal step
//! chases a pointer to a physically unrelated block — a random on-disk seek per
//! element — whereas a [`crate::BStackBlockVec`] keeps its element offsets in one
//! contiguous block and its values need no per-step indirection. For iteration,
//! indexing, and bulk reads a vector is faster and denser; reach for a linked
//! list only when you genuinely need O(1) splice / push / pop at *both* ends
//! without disturbing the other elements' identities (their on-disk offsets stay
//! put across insert/remove, which a vector cannot promise).
//!
//! # Non-intrusive, single-ref nodes
//!
//! This list is deliberately **not** intrusive: the links do not live inside `T`.
//! An intrusive list would have to weave `prev`/`next` into each value type,
//! which for a generic `T` means the codegen must understand `T`'s layout and
//! inject fields — a lot of per-`T` machinery for no real payoff here. Instead
//! every node is its own small block holding just `{ prev, next, value }`, where
//! `value` is a **single `u64` reference** to an ordinary, unmodified `T` block.
//!
//! The payoff of the single ref is that a node's on-disk layout is
//! [`NodeOnDisk`] — three `u64`s after the header — **identical for every `T`**.
//! There is no generic on-disk struct, the tag is the only thing that varies by
//! `T`, and the read/write/teardown/clone code is one fixed shape rather than a
//! monomorphized family. The list *owns* its nodes and, through each node's
//! single ref, the value blocks: teardown frees both, and a deep clone
//! reproduces the whole chain with freshly deep-cloned values.

use core::cell::Cell;
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::{WriteBuf, alloc_image, atomic_update, read_fields, w8};
use crate::handback::ReplaceError;
use crate::io_core::{ClonePlan, TryCloneIn, dealloc_range};
use crate::primitives::{EightCC, checked_off};
use crate::types::compiled::{BStackOwned, BlockHeader, HEADER_SIZE};
use crate::types::traits::{BStackBlock, BStackCast, BStackDrop};
use crate::util::{SmallBuf, io_error, read_u64};

/// The on-disk image of a [`BStackLinkedList`]: the block header followed by the
/// `head`/`tail` node offsets (`0` = empty) and the element count. `#[repr(C)]`
/// with only `u64` fields after a 16-byte header, so it is naturally padding-free
/// and **non-generic** — the same layout for every element type.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct ListOnDisk {
    /// The 16-byte block header (size + type tag).
    pub header: BlockHeader,
    /// Offset of the first node, or `0` when the list is empty.
    pub head: u64,
    /// Offset of the last node, or `0` when the list is empty.
    pub tail: u64,
    /// Number of elements.
    pub len: u64,
}

/// The on-disk image of one list node: the block header followed by the
/// `prev`/`next` node offsets (`0` = none) and a **single** `u64` reference to
/// the value block. Non-generic: the same layout for every element type.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct NodeOnDisk {
    /// The 16-byte block header (size + type tag).
    pub header: BlockHeader,
    /// Offset of the previous node, or `0` at the head.
    pub prev: u64,
    /// Offset of the next node, or `0` at the tail.
    pub next: u64,
    /// The single reference to this node's value block.
    pub value: u64,
}

// Field offsets within a list block.
const HEAD_OFF: u64 = HEADER_SIZE; // 16
const TAIL_OFF: u64 = HEADER_SIZE + 8; // 24
const LEN_OFF: u64 = HEADER_SIZE + 16; // 32
// Field offsets within a node block (same shape, different meaning).
const NPREV_OFF: u64 = HEADER_SIZE; // 16
const NNEXT_OFF: u64 = HEADER_SIZE + 8; // 24
const NVAL_OFF: u64 = HEADER_SIZE + 16; // 32

const LIST_SIZE: u64 = size_of::<ListOnDisk>() as u64;
const NODE_SIZE: u64 = size_of::<NodeOnDisk>() as u64;
// `push_front`/`push_back` inline a node's full image into a `SmallBuf::Buf40`
// (see `super::util::SmallBuf`) — no length field, so it's exact-size-only.
const _: () = assert!(
    NODE_SIZE == 40,
    "SmallBuf::Buf40 assumes a 40-byte NodeOnDisk"
);

/// An owned, doubly-linked list of `T` blocks.
///
/// A typed handle (a newtype over a [`BStackRange`], like every block handle),
/// carrying no allocator. [`new`](Self::new) returns a bare
/// [`BStackOwned<BStackLinkedList<T>>`] that frees nothing on scope exit; free it
/// with [`bstack_drop`](BStackDrop::bstack_drop) or wrap it
/// ([`crate::AutoDrop`] / [`crate::BStackCow`]).
///
/// The list owns its nodes and their value blocks: pushing takes a
/// [`BStackOwned<T>`] (transferring ownership into a node), popping hands one
/// back, and teardown recursively frees every value and node.
pub struct BStackLinkedList<T: BStackBlock> {
    range: BStackRange,
    _marker: PhantomData<fn() -> T>,
}

impl<T: BStackBlock> BStackLinkedList<T> {
    /// The fixed on-disk size of one `T` value block.
    fn value_size() -> u64 {
        size_of::<<T as BStackBlock>::OnDisk>() as u64
    }

    /// The tag stamped on this list's internal node blocks — a `"LNd"` prefix
    /// perturbed by `T`'s tag, so a node is never mistaken for another type.
    fn node_tag() -> EightCC {
        const BASE: EightCC = EightCC::new([b'L', b'N', b'd', 0x80, 0x81, 0x82, 0x83, 0x84]);
        BASE.mix(<T as BStackCast>::eightcc())
    }

    /// A `T`-value handle over the block at `off` (fixed-size-block model).
    fn value_at(off: u64) -> T {
        unsafe { <T as BStackBlock>::from_range(BStackRange::new(off, Self::value_size())) }
    }

    /// Build a node image with the given links and value ref.
    fn node_image(prev: u64, next: u64, value: u64) -> NodeOnDisk {
        NodeOnDisk {
            header: BlockHeader {
                size: NODE_SIZE,
                tag: Self::node_tag(),
            },
            prev,
            next,
            value,
        }
    }

    /// Allocate an empty list.
    pub fn new<A: BStackRaiiAllocator>(allocator: &A) -> io::Result<BStackOwned<Self>> {
        let od = ListOnDisk {
            header: BlockHeader {
                size: LIST_SIZE,
                tag: Self::eightcc(),
            },
            head: 0,
            tail: 0,
            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 list has no elements.
    pub fn is_empty(&self, stack: &BStack) -> io::Result<bool> {
        Ok(self.len(stack)? == 0)
    }

    /// Append a value to the back, taking ownership of its block.
    ///
    /// Atomic and external-lock-free: the node is allocated first (an orphan),
    /// then the tail read, node-image write, tail/`prev.next` relink and length
    /// bump all commit as one crash-atomic `atomic_update`. A crash before the
    /// commit leaks the orphan node; it never tears the list.
    pub fn push_back<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        value: BStackOwned<T>,
    ) -> Result<(), ReplaceError<BStackOwned<T>>> {
        let list = self.range.start();
        // Guard the value block: the node `alloc` or the commit can fail *after* the
        // value's ownership is taken. On failure [`finish_handback`] returns it to
        // the caller rather than freeing it; on success the guard
        // is defused once the commit links it in.
        let value = value.auto(allocator);
        let val_off = value.range().start();
        let outcome: io::Result<()> = (|| {
            // Allocate the node up front; it stays an orphan until the commit links it.
            let node = allocator.alloc(NODE_SIZE)?.as_range().start();
            let mut w: WriteBuf<4> = WriteBuf::new();

            let res = atomic_update(
                allocator,
                &[list + TAIL_OFF, list + LEN_OFF],
                |_v1| Ok(Vec::new()),
                |v1, _v2| {
                    let (old_tail, len) = (v1[0], v1[1]);
                    // The node's full image (with `prev` wired to the read tail).
                    let image: [u8; 40] =
                        bytemuck::bytes_of(&Self::node_image(old_tail, 0, val_off))
                            .try_into()
                            .unwrap();
                    w.push((node, SmallBuf::Buf40(image)));
                    // Link the old tail (or the head, if the list was empty) to it —
                    // `old_tail` is a node pointer read from disk, so a corrupted
                    // value near `u64::MAX` must not silently wrap this addition.
                    let link = if old_tail != 0 {
                        checked_off(old_tail, NNEXT_OFF)?
                    } else {
                        list + HEAD_OFF
                    };
                    w.push(w8(link, node));
                    w.push(w8(list + TAIL_OFF, node));
                    w.push(w8(list + LEN_OFF, len + 1));
                    Ok(w.as_slice())
                },
            );
            if res.is_err() {
                // The node was never linked in; reclaim the orphan (the value block
                // is handed back to the caller by `finish_handback`).
                // SAFETY: freshly allocated, referenced by nobody.
                let _ = unsafe { dealloc_range(allocator, BStackRange::new(node, NODE_SIZE)) };
            }
            res
        })();
        value.finish_handback(outcome)
    }

    /// Prepend a value to the front, taking ownership of its block. Atomic and
    /// external-lock-free (see [`push_back`](Self::push_back)).
    pub fn push_front<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        value: BStackOwned<T>,
    ) -> Result<(), ReplaceError<BStackOwned<T>>> {
        let list = self.range.start();
        // 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_off = value.range().start();
        let outcome: io::Result<()> = (|| {
            let node = allocator.alloc(NODE_SIZE)?.as_range().start();
            let mut w: WriteBuf<4> = WriteBuf::new();

            let res = atomic_update(
                allocator,
                &[list + HEAD_OFF, list + LEN_OFF],
                |_v1| Ok(Vec::new()),
                |v1, _v2| {
                    let (old_head, len) = (v1[0], v1[1]);
                    let image: [u8; 40] =
                        bytemuck::bytes_of(&Self::node_image(0, old_head, val_off))
                            .try_into()
                            .unwrap();
                    w.push((node, SmallBuf::Buf40(image)));
                    let link = if old_head != 0 {
                        checked_off(old_head, NPREV_OFF)?
                    } else {
                        list + TAIL_OFF
                    };
                    w.push(w8(link, node));
                    w.push(w8(list + HEAD_OFF, node));
                    w.push(w8(list + LEN_OFF, len + 1));
                    Ok(w.as_slice())
                },
            );
            if res.is_err() {
                // SAFETY: freshly allocated, referenced by nobody. The value block is
                // handed back to the caller by `finish_handback`.
                let _ = unsafe { dealloc_range(allocator, BStackRange::new(node, NODE_SIZE)) };
            }
            res
        })();
        value.finish_handback(outcome)
    }

    /// Remove and return the last element (as an owned value block), or `None`
    /// if the list is empty. The node shell is freed; the value block is handed
    /// back to the caller.
    ///
    /// Atomic and external-lock-free: the tail is read, the target node's
    /// `prev`/`value` read (a dependent second round), and the relink + length
    /// decrement commit as one `atomic_update`. Only *after* the node is
    /// unlinked is its shell freed — a crash between leaks the shell, never a
    /// dangling link.
    pub fn pop_back<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
    ) -> io::Result<Option<BStackOwned<T>>> {
        let list = self.range.start();
        let node = Cell::new(0u64);
        let val = Cell::new(0u64);
        let mut w: WriteBuf<3> = WriteBuf::new();

        atomic_update(
            allocator,
            &[list + TAIL_OFF, list + LEN_OFF],
            |v1| {
                let tail = v1[0];
                if tail == 0 {
                    Ok(Vec::new())
                } else {
                    Ok(vec![
                        checked_off(tail, NPREV_OFF)?,
                        checked_off(tail, NVAL_OFF)?,
                    ])
                }
            },
            |v1, v2| {
                let (tail, len) = (v1[0], v1[1]);
                if tail != 0 {
                    let (prev, value) = (v2[0], v2[1]);
                    node.set(tail);
                    val.set(value);
                    if prev != 0 {
                        w.push(w8(checked_off(prev, NNEXT_OFF)?, 0u64));
                        w.push(w8(list + TAIL_OFF, prev));
                    } else {
                        w.push(w8(list + HEAD_OFF, 0u64));
                        w.push(w8(list + TAIL_OFF, 0u64));
                    }
                    w.push(w8(list + LEN_OFF, len - 1));
                }
                Ok(w.as_slice())
            },
        )?;

        if node.get() == 0 {
            return Ok(None);
        }
        // Unlinked above; free the (now unreachable) node shell.
        // SAFETY: the node is unlinked and solely ours.
        unsafe { dealloc_range(allocator, BStackRange::new(node.get(), NODE_SIZE))? };
        // SAFETY: the value block's ownership transfers to the caller.
        Ok(Some(unsafe {
            BStackOwned::from_raw(Self::value_at(val.get()))
        }))
    }

    /// Remove and return the first element (as an owned value block), or `None`
    /// if the list is empty. Atomic and external-lock-free (see
    /// [`pop_back`](Self::pop_back)).
    pub fn pop_front<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
    ) -> io::Result<Option<BStackOwned<T>>> {
        let list = self.range.start();
        let node = Cell::new(0u64);
        let val = Cell::new(0u64);
        let mut w: WriteBuf<3> = WriteBuf::new();

        atomic_update(
            allocator,
            &[list + HEAD_OFF, list + LEN_OFF],
            |v1| {
                let head = v1[0];
                if head == 0 {
                    Ok(Vec::new())
                } else {
                    Ok(vec![
                        checked_off(head, NNEXT_OFF)?,
                        checked_off(head, NVAL_OFF)?,
                    ])
                }
            },
            |v1, v2| {
                let (head, len) = (v1[0], v1[1]);
                if head != 0 {
                    let (next, value) = (v2[0], v2[1]);
                    node.set(head);
                    val.set(value);
                    if next != 0 {
                        w.push(w8(checked_off(next, NPREV_OFF)?, 0u64));
                        w.push(w8(list + HEAD_OFF, next));
                    } else {
                        w.push(w8(list + HEAD_OFF, 0u64));
                        w.push(w8(list + TAIL_OFF, 0u64));
                    }
                    w.push(w8(list + LEN_OFF, len - 1));
                }
                Ok(w.as_slice())
            },
        )?;

        if node.get() == 0 {
            return Ok(None);
        }
        // SAFETY: the node is unlinked and solely ours.
        unsafe { dealloc_range(allocator, BStackRange::new(node.get(), NODE_SIZE))? };
        // SAFETY: the value block's ownership transfers to the caller.
        Ok(Some(unsafe {
            BStackOwned::from_raw(Self::value_at(val.get()))
        }))
    }

    /// A **borrowed** handle to the first value (no ownership; frees nothing), or
    /// `None` if empty.
    pub fn front(&self, stack: &BStack) -> io::Result<Option<T>> {
        let head = read_u64(stack, self.range.start() + HEAD_OFF)?;
        if head == 0 {
            return Ok(None);
        }
        Ok(Some(Self::value_at(read_u64(
            stack,
            checked_off(head, NVAL_OFF)?,
        )?)))
    }

    /// A **borrowed** handle to the last value (no ownership; frees nothing), or
    /// `None` if empty.
    pub fn back(&self, stack: &BStack) -> io::Result<Option<T>> {
        let tail = read_u64(stack, self.range.start() + TAIL_OFF)?;
        if tail == 0 {
            return Ok(None);
        }
        Ok(Some(Self::value_at(read_u64(
            stack,
            checked_off(tail, NVAL_OFF)?,
        )?)))
    }

    /// Collect **borrowed** handles to every value, front to back. The handles
    /// alias the list's blocks — do not free them; they stay valid only while the
    /// list does.
    pub fn to_vec(&self, stack: &BStack) -> io::Result<Vec<T>> {
        let mut out = Vec::new();
        let mut cur = read_u64(stack, self.range.start() + HEAD_OFF)?;
        // Bound the walk by the stored `len` (as the deque bounds by its own
        // header): a corrupt cyclic `next` must fail as invalid data, not
        // yield elements forever.
        let mut remaining = self.len(stack)?;
        while cur != 0 {
            if remaining == 0 {
                return Err(io_error!(
                    "linked list chain longer than its stored len (a next-pointer cycle?)"
                ));
            }
            remaining -= 1;
            // `next` (@24) and `value` (@32) are adjacent — one read per node.
            let [next, value] = read_fields::<2>(stack, checked_off(cur, NNEXT_OFF)?)?;
            out.push(Self::value_at(value));
            cur = next;
        }
        Ok(out)
    }

    /// A lazy iterator over the elements, front to back, yielding `io::Result`
    /// value handles. A read snapshot: do not mutate the list while iterating.
    pub fn iter<'a>(&self, stack: &'a BStack) -> io::Result<ListIter<'a, T>> {
        let head = read_u64(stack, self.range.start() + HEAD_OFF)?;
        let remaining = self.len(stack)?;
        Ok(ListIter {
            stack,
            block_off: self.range.start(),
            len0: remaining,
            remaining,
            cur: head,
            _marker: PhantomData,
        })
    }
}

impl<T: BStackBlock> BStackCast for BStackLinkedList<T> {
    /// A `"List"` prefix over hash bytes perturbed by `T`'s tag, so lists of
    /// different element types never share a discriminant even though their
    /// on-disk layout is identical.
    fn eightcc() -> EightCC {
        const BASE: EightCC = EightCC::new([b'L', b'i', b's', b't', 0x80, 0x81, 0x82, 0x83]);
        BASE.mix(<T as BStackCast>::eightcc())
    }
}

// Self-contained (no separate control block): may be `#[embed]`ded.
impl<T: BStackBlock> crate::types::traits::BStackEmbeddable for BStackLinkedList<T> {}

impl<T: BStackBlock> BStackBlock for BStackLinkedList<T> {
    type OnDisk = ListOnDisk;

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

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

    /// Recursively free every value block and node, **without** freeing the list
    /// block itself (its embedding parent, or [`bstack_drop`](BStackDrop), does
    /// that).
    fn __bstack_drop_children<A: BStackRaiiAllocator>(
        allocator: &A,
        range: BStackRange,
    ) -> io::Result<()> {
        let mut cur = read_u64(allocator.stack(), range.start() + HEAD_OFF)?;
        // Bound the free-as-you-go walk by the stored `len`: on a corrupt cyclic
        // `next` the second lap would re-free every node — a double free. Erroring
        // leaves at most a leak, per the corruption-degrades-to-a-leak baseline.
        let mut remaining = read_u64(allocator.stack(), range.start() + LEN_OFF)?;
        while cur != 0 {
            if remaining == 0 {
                return Err(io_error!(
                    "linked list chain longer than its stored len (a next-pointer cycle?)"
                ));
            }
            remaining -= 1;
            let next = read_u64(allocator.stack(), checked_off(cur, NNEXT_OFF)?)?;
            let val = read_u64(allocator.stack(), checked_off(cur, NVAL_OFF)?)?;
            if val != 0 {
                // Recursively free the value block (its own children, then it).
                // SAFETY: the list solely owns each value block.
                let owned = unsafe { BStackOwned::from_raw(Self::value_at(val)) };
                owned.bstack_drop(allocator)?;
            }
            // SAFETY: the list solely owns each node block.
            unsafe { dealloc_range(allocator, BStackRange::new(cur, NODE_SIZE))? };
            cur = next;
        }
        Ok(())
    }

    /// Deep-clone the whole chain into `plan`: every value is deep-cloned (via
    /// `T`'s own clone hook), fresh nodes are allocated and wired, and the list
    /// block is staged — all as part of the parent plan's single atomic commit.
    fn __bstack_clone_children_inplace<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        plan: &mut ClonePlan,
    ) -> io::Result<Self::OnDisk> {
        let src = self.range.start();

        // 1. Gather the source value offsets in order.
        let mut vals = Vec::new();
        let mut cur = read_u64(allocator.stack(), src + HEAD_OFF)?;
        // Bound by the stored `len` (see `to_vec`): a cycle must error, not grow
        // `vals` without bound.
        let mut remaining = read_u64(allocator.stack(), src + LEN_OFF)?;
        while cur != 0 {
            if remaining == 0 {
                return Err(io_error!(
                    "linked list chain longer than its stored len (a next-pointer cycle?)"
                ));
            }
            remaining -= 1;
            vals.push(read_u64(allocator.stack(), checked_off(cur, NVAL_OFF)?)?);
            cur = read_u64(allocator.stack(), checked_off(cur, NNEXT_OFF)?)?;
        }
        let n = vals.len();

        // 2. Deep-clone each value into the plan.
        let mut val_dsts = Vec::with_capacity(n);
        for &v in &vals {
            let dst = if v != 0 {
                Self::value_at(v)
                    .__bstack_clone_into(allocator, plan)?
                    .start()
            } else {
                0
            };
            val_dsts.push(dst);
        }

        // 3. Reserve the node blocks up front so their offsets are known for wiring.
        let mut node_dsts = Vec::with_capacity(n);
        for _ in 0..n {
            node_dsts.push(plan.alloc_raw(allocator, NODE_SIZE)?.start());
        }

        // 4. Stage each node image with links resolved.
        for i in 0..n {
            let prev = if i > 0 { node_dsts[i - 1] } else { 0 };
            let next = if i + 1 < n { node_dsts[i + 1] } else { 0 };
            let od = Self::node_image(prev, next, val_dsts[i]);
            plan.write(node_dsts[i], bytemuck::bytes_of(&od).to_vec());
        }

        // 5. Return the list descriptor (the caller places it — in a fresh block for
        // an owned clone, or inline for an `#[embed]`ded one).
        let od = ListOnDisk {
            header: BlockHeader {
                size: LIST_SIZE,
                tag: Self::eightcc(),
            },
            head: node_dsts.first().copied().unwrap_or(0),
            tail: node_dsts.last().copied().unwrap_or(0),
            len: n as u64,
        };
        Ok(od)
    }
}

impl<T: BStackBlock> TryCloneIn for BStackLinkedList<T> {}

/// A front-to-back iterator over a [`BStackLinkedList`], yielding `io::Result<T>`
/// value handles. Created by [`BStackLinkedList::iter`]; walks the `next` links.
pub struct ListIter<'a, T: BStackBlock> {
    stack: &'a BStack,
    /// The list handle block, re-read each step to detect mutation.
    block_off: u64,
    /// The list's `len` at construction — a change means it was mutated.
    len0: u64,
    cur: u64,
    /// Nodes left per the list's stored `len` — the walk bound: a corrupt cyclic
    /// `next` yields one `InvalidData` and ends, instead of iterating forever.
    remaining: u64,
    _marker: PhantomData<fn() -> T>,
}

impl<'a, T: BStackBlock> Iterator for ListIter<'a, T> {
    type Item = io::Result<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cur == 0 {
            return None;
        }
        // Fail fast if the list was mutated during iteration: a `pop_front` /
        // `pop_back` frees a node, so the cached `cur` could name freed storage. A
        // list only mutates at its ends, so every push/pop changes `len` — a changed
        // `len` means the snapshot is stale. Conservative (a growing push also trips
        // it), matching the "do not mutate while iterating" contract.
        match read_u64(self.stack, self.block_off + LEN_OFF) {
            Ok(len) if len == self.len0 => {}
            Ok(_) => {
                self.cur = 0;
                return Some(Err(io_error!(
                    "BStackLinkedList was mutated during iteration (its length changed); \
                     the iterator is invalidated"
                )));
            }
            Err(e) => {
                self.cur = 0;
                return Some(Err(e));
            }
        }
        if self.remaining == 0 {
            self.cur = 0;
            return Some(Err(io_error!(
                "linked list chain longer than its stored len (a next-pointer cycle?)"
            )));
        }
        self.remaining -= 1;
        // `next` (@24) and `value` (@32) are adjacent — one read per node.
        let off = match checked_off(self.cur, NNEXT_OFF) {
            Ok(off) => off,
            Err(e) => {
                self.cur = 0;
                return Some(Err(e));
            }
        };
        match read_fields::<2>(self.stack, off) {
            Ok([next, value]) => {
                self.cur = next;
                Some(Ok(BStackLinkedList::<T>::value_at(value)))
            }
            Err(e) => {
                self.cur = 0;
                Some(Err(e))
            }
        }
    }
}