o3 0.60.0

shared-nothing 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
pub mod common;

use std::{cell::Cell, num::NonZero, ops::ControlFlow, ptr};

use common::{alloc::system::Tracker, buffer::domain::Capacity};
use o3::{
    buffer::{
        self, Residency as _,
        hold::ranges,
        raw::{Chunks as _, Scatter as _},
        resident,
        segments::{self, Source},
        storage,
    },
    mem::rc,
};

#[global_allocator]
static ALLOCATOR: Tracker = Tracker;

#[test]
fn compact_ranges_keep_one_backing() -> Result<(), &'static str> {
    let page = storage::Shared::try_copy(b"_abcdef_").map_err(|_| "page")?;
    let address = page.as_ptr();
    let spans = [(1u16, 3), (3, 5), (6, 7)];
    let plan = ranges::Set::try_new(&page, &spans, 5).map_err(|_| "ranges")?;
    let direct = plan.get(1).ok_or("second range")?;
    let iterated = plan.iter().next().ok_or("first range")?;
    assert_eq!(direct.as_slice().as_ptr(), address.wrapping_add(3));
    assert_eq!(iterated.as_slice().as_ptr(), address.wrapping_add(1));
    assert_eq!(plan.contiguous(), None);
    let (retained, counts) = Tracker::counts(|| plan.try_retain());
    let mut retained = retained.map_err(|_| "retained")?;
    assert_eq!(counts, [1, 0]);
    assert_eq!(retained.count().into_raw(), 3);
    assert_eq!(retained.resident(), page.resident());
    assert_eq!(
        buffer::hold::Charge::from(&retained),
        buffer::hold::Charge::from_commit(5, page.resident(), 1)
    );
    assert!(retained.segments().eq([b"ab".as_slice(), b"cd", b"f"]));
    assert!(retained.runs().eq([b"abcd".as_slice(), b"f"]));
    assert!(retained.segments().map(|s| s.as_ptr()).eq([
        address.wrapping_add(1),
        address.wrapping_add(3),
        address.wrapping_add(6),
    ]));
    drop(page);
    assert!(retained.segments().flatten().eq(b"abcdf"));
    for expected in [b"cdf".as_slice(), b"f"] {
        // SAFETY: the unchanged front is the original two-byte span; no sum is retained.
        assert_eq!(
            Tracker::counts(|| unsafe {
                segments::source::raw::pop_front::<false, 0>(&mut retained, 2, [])
            }).1,
            [0, 0]
        );
        assert!(retained.segments().flatten().eq(expected));
        assert_eq!(
            buffer::hold::Charge::from(&retained),
            buffer::hold::Charge::from_commit(expected.len(), 8, 1)
        );
    }
    // SAFETY: only the original one-byte final span remains; no sum is retained.
    assert_eq!(
        Tracker::counts(|| unsafe {
            segments::source::raw::pop_front::<false, 0>(&mut retained, 1, [])
        }).1,
        [0, 2]
    );
    assert!(retained.is_empty());
    Ok(())
}

#[test]
fn retains_after_rejection() -> Result<(), &'static str> {
    let source = storage::Shared::try_copy(b"head_ab__cde_tail").map_err(|_| "page")?;
    // SAFETY: these fixed bounds select this unchanged initialized owner.
    let view = unsafe { buffer::raw::view(&source, 4..13) };
    let spans = [(1u16, 3), (5, 8)];
    let plan = ranges::Set::try_new(view, &spans, 5).map_err(|_| "ranges")?;
    // SAFETY: the existing Shared representation stores Option<Tag> first;
    // Count is transparent over Cell<u32>. This test owns all real edges.
    let count = unsafe {
        let tag = &*ptr::from_ref(&source).cast::<Option<storage::regions::Tag>>();
        let tag = tag.as_ref().ok_or("owned page")?;
        &*ptr::from_ref(o3::mem::raw::Edge::count(tag)).cast::<Cell<u32>>()
    };
    let original = count.replace(u32::MAX);
    let (metadata, first) = Tracker::counts(|| Tracker::fail_after(0, || plan.try_retain()));
    let (retain, second) = Tracker::counts(|| plan.try_retain());
    assert_eq!(count.replace(original), u32::MAX);
    assert!(matches!(
        metadata,
        Err(ranges::retain::Error::Metadata(o3::alloc::Error::Exhausted))
    ));
    assert!(matches!(
        retain,
        Err(ranges::retain::Error::Retain(rc::Error::Exhausted))
    ));
    assert_eq!(first, [0, 0]);
    assert_eq!(second, [1, 1]);
    let retained = plan.try_retain().map_err(|_| "retry")?;
    assert_eq!(count.get(), original + 1);
    assert!(retained.segments().flatten().eq(b"abcde"));
    drop(retained);
    assert_eq!(count.get(), original);

    let owner: resident::Shared<'_> = source.into();
    let address = owner.as_ptr();
    let spans = [(5u16, 7), (9, 12)];
    let plan = ranges::Set::try_new(owner, &spans, 5).map_err(|_| "owned ranges")?;
    let rejected = Tracker::fail_after(0, || plan.try_retain())
        .err()
        .ok_or("metadata failure")?;
    let (owner, error) = rejected.into_parts();
    assert!(matches!(error, o3::alloc::Error::Exhausted));
    assert_eq!(owner.as_ptr(), address);
    assert_eq!(owner.as_slice(), b"head_ab__cde_tail");
    let retained = ranges::Set::try_new(owner, &spans, 5)
        .map_err(|_| "retry ranges")?
        .try_retain()
        .map_err(|_| "retry owner")?;
    assert!(retained.segments().flatten().eq(b"abcde"));
    Ok(())
}

#[test]
fn empty_and_single_move_without_metadata() -> Result<(), &'static str> {
    for (spans, expected) in [
        (&[][..], b"".as_slice()),
        (&[(1u16, 3)][..], b"ab".as_slice()),
    ] {
        let owner: resident::Shared<'_> = storage::Shared::try_copy(b"_ab_")
            .map_err(|_| "page")?
            .into();
        let address = owner.as_ptr();
        let plan = ranges::Set::try_new(owner, spans, expected.len()).map_err(|_| "ranges")?;
        assert_eq!(plan.contiguous(), Some(expected));
        let (retained, counts) = Tracker::counts(|| Tracker::fail_after(0, || plan.try_retain()));
        let retained = retained.map_err(|_| "terminal")?;
        assert_eq!(counts, [0, usize::from(spans.is_empty())]);
        assert_eq!(retained.contiguous(), Some(expected));
        if !expected.is_empty() {
            assert_eq!(
                retained.front().ok_or("front")?.as_ptr(),
                address.wrapping_add(1)
            );
        }
        let mut copy = retained.normalize();
        let (done, activity) =
            Tracker::counts(|| Tracker::fail_after(0, || copy.try_step::<true>(NonZero::<usize>::MIN, &segments::Count::EMPTY)));
        let done = done
            .map_err(|_| "direct normalize")?
            .break_value()
            .ok_or("direct completion")?;
        assert_eq!(activity, [0, 0]);
        assert_eq!(done.as_slice(), expected);
        if !expected.is_empty() {
            assert_eq!(done.as_ptr(), address.wrapping_add(1));
        }
    }
    Ok(())
}

#[test]
fn append_failure_returns_the_same_owner() -> Result<(), &'static str> {
    let first: resident::Shared<'_> = storage::Shared::try_copy(b"first")
        .map_err(|_| "first")?
        .into();
    let second: resident::Shared<'_> = storage::Shared::try_copy(b"second")
        .map_err(|_| "second")?
        .into();
    let addresses = [first.as_ptr(), second.as_ptr()];
    let mut source = Source::from(first);
    let (result, counts) =
        Tracker::counts(|| Tracker::fail_after(0, || source.try_append(Source::from(second))));
    let rejected = result.err().ok_or("metadata failure")?;
    let (second, cause) = rejected.into_parts();
    assert!(matches!(
        cause,
        segments::assembly::Error::Metadata(o3::alloc::Error::Exhausted)
    ));
    assert_eq!(counts, [0, 0]);
    assert_eq!(source.front().ok_or("first front")?.as_ptr(), addresses[0]);
    assert_eq!(second.front().ok_or("second front")?.as_ptr(), addresses[1]);
    assert_eq!(source.contiguous(), Some(b"first".as_slice()));
    source.try_append(second).map_err(|_| "append retry")?;
    assert!(source.segments().map(|s| s.as_ptr()).eq(addresses));
    assert!(source.segments().flatten().eq(b"firstsecond"));
    Ok(())
}

#[test]
fn native_cursor_preserves_ranges() -> Result<(), &'static str> {
    let page: resident::Shared<'_> = storage::Shared::try_copy(b"_abcdef_")
        .map_err(|_| "page")?
        .into();
    let spans = [(1u16, 3), (3, 5), (6, 7)];
    let mut source = ranges::Set::try_new(page, &spans, 5)
        .map_err(|_| "ranges")?
        .try_retain()
        .map_err(|_| "retained")?;
    source
        .try_append(Source::from(resident::Shared::from(b"gh".as_slice())))
        .map_err(|_| "mixed")?;
    let whole = b"abcdfgh";
    for offset in 0..=whole.len() {
        for limit in [1, 2, 5, usize::MAX] {
            let ((), activity) = Tracker::measure(|| {
                let mut cursor = source.chunks();
                let _ = cursor.take_bytes(offset).count();
                assert_eq!(cursor.remaining(), whole.len() - offset);
                assert!(
                    cursor
                        .take_bytes(limit)
                        .flat_map(|part| part.bytes().iter())
                        .eq(whole[offset..offset + limit.min(whole.len() - offset)].iter())
                );
            });
            assert_eq!(activity, [0; 4]);
        }
    }
    let mut position = segments::scatter::raw::Position::new();
    for offset in [0, 3, 5, 2, 6, 4] {
        let moved = source;
        let ((), activity) = Tracker::measure(|| {
            // SAFETY: this checkpoint belongs to the same moved source;
            // every offset is below its unchanged length.
            assert!(
                unsafe { moved.resume(&mut position, offset) }
                    .flatten()
                    .eq(&whole[offset..])
            );
        });
        assert_eq!(activity, [0; 4]);
        source = moved;
    }
    let mut removed = segments::scatter::raw::Position::new();
    // SAFETY: both positions refer to this unchanged retained source.
    unsafe {
        let _ = source.resume(&mut position, 4);
        let _ = source.resume(&mut removed, 1);
    }
    // SAFETY: the unchanged first logical span has length two; no sum is retained.
    unsafe { segments::source::raw::pop_front::<false, 0>(&mut source, 2, []) };
    // SAFETY: the complete first logical span was removed; all remaining
    // range identities, physical parts and bytes are unchanged.
    unsafe {
        let consumed = NonZero::<usize>::MIN.saturating_add(1);
        position.rebase_prefix(consumed);
        removed.rebase_prefix(consumed);
        assert!(source.resume(&mut position, 2).flatten().eq(b"fgh"));
        assert!(source.resume(&mut removed, 0).flatten().eq(b"cdfgh"));
    }
    Ok(())
}

#[test]
fn splits_prefixes_without_moving_payload() -> Result<(), &'static str> {
    Capacity(12)
        .try_scope(|budget| -> Result<(), &'static str> {
            for layout in 0..3 {
                for amount in 0..=9 {
                    let mut source = match layout {
                        0 => Source::from(
                            resident::Exact::try_copy(&budget, b"abcdefghi")
                                .map_err(|_| "contiguous")?
                                .into_shared(),
                        ),
                        1 => {
                            let owner = resident::Exact::try_copy(&budget, b"_ab_cde_fghi")
                                .map_err(|_| "compact")?
                                .into_shared();
                            let spans = [(1u16, 3), (4, 7), (8, 12)];
                            ranges::Set::try_new(owner, &spans, 9)
                                .map_err(|_| "ranges")?
                                .try_retain()
                                .map_err(|_| "compact owner")?
                        }
                        _ => {
                            let first = resident::Exact::try_copy(&budget, b"abcde")
                                .map_err(|_| "first")?
                                .into_shared();
                            let second = resident::Exact::try_copy(&budget, b"fghi")
                                .map_err(|_| "second")?
                                .into_shared();
                            let mut source = Source::from(first);
                            source
                                .try_append(Source::from(second))
                                .map_err(|_| "mixed")?;
                            source
                        }
                    };
                    let mut addresses = [ptr::null(); 9];
                    for (address, byte) in addresses.iter_mut().zip(source.segments().flatten()) {
                        *address = ptr::from_ref(byte);
                    }
                    if amount == 0 {
                        let error = source.try_take::<false>(10).err().ok_or("oversized prefix")?;
                        assert!(matches!(error, segments::Error::Boundary(error)
                        if error.into_parts() == (NonZero::<usize>::MIN.saturating_add(9), 9)));
                    }
                    let (prefix, activity) = Tracker::counts(|| source.try_take::<false>(amount));
                    let prefix = prefix.map_err(|_| "prefix")?;
                    assert_eq!(activity[0], 0);
                    assert!(prefix.segments().flatten().eq(&b"abcdefghi"[..amount]));
                    assert!(source.segments().flatten().eq(&b"abcdefghi"[amount..]));
                    assert!(
                        prefix
                            .segments()
                            .flatten()
                            .map(ptr::from_ref)
                            .eq(addresses[..amount].iter().copied())
                    );
                    assert!(
                        source
                            .segments()
                            .flatten()
                            .map(ptr::from_ref)
                            .eq(addresses[amount..].iter().copied())
                    );
                    drop(source);
                    let held = match (layout, amount) {
                        (_, 0) => 0,
                        (0, _) => 9,
                        (1, _) => 12,
                        (2, 1..=5) => 5,
                        _ => 9,
                    };
                    assert_eq!(budget.resident(), held);
                    assert!(prefix.segments().flatten().eq(&b"abcdefghi"[..amount]));
                    drop(prefix);
                    assert_eq!(budget.resident(), 0);
                }
            }
            let mut source = Source::EMPTY;
            let parts = [b"ab", b"cd", b"ef", b"gh"];
            for part in parts {
                source
                    .try_append(Source::from(resident::Shared::from(part.as_slice())))
                    .map_err(|_| "parts")?;
            }
            let (failed, counts) = Tracker::counts(|| source.try_take::<false>(4));
            assert!(
                matches!(failed, Err(segments::Error::ChainCapacity(shortage))
            if shortage.requested.get() == 1 && shortage.available == 0)
            );
            assert_eq!(counts, [0, 0]);
            assert!(
                source
                    .segments()
                    .map(|s| s.as_ptr())
                    .eq(parts.map(|s| s.as_ptr()))
            );
            assert!(source.segments().flatten().eq(b"abcdefgh"));
            let (whole, counts) = Tracker::counts(|| source.try_take::<false>(8));
            let whole = whole.map_err(|_| "whole")?;
            assert_eq!(counts, [0, 0]);
            assert!(source.is_empty());
            assert!(
                whole
                    .segments()
                    .map(|s| s.as_ptr())
                    .eq(parts.map(|s| s.as_ptr()))
            );
            Ok(())
        })
        .map_err(|_| "domain")?
}

#[test]
fn normalization_releases_completed_inputs() -> Result<(), &'static str> {
    Capacity(6)
        .try_scope(|budget| -> Result<(), &'static str> {
            let first = resident::Exact::try_copy(&budget, b"abc")
                .map_err(|_| "first")?
                .into_shared();
            let second = resident::Exact::try_copy(&budget, b"def")
                .map_err(|_| "second")?
                .into_shared();
            let mut source = Source::from(first);
            source
                .try_append(Source::from(second))
                .map_err(|_| "mixed")?;
            assert_eq!(budget.resident(), 6);
            let mut copy = source.normalize();
            let (failed, allocations) =
                Tracker::counts(|| Tracker::fail_after(0, || copy.try_step::<true>(NonZero::<usize>::MIN, &segments::Count::EMPTY)));
            assert!(matches!(failed, Err(storage::AllocError::Exhausted(_))));
            assert_eq!(allocations, [0, 0]);
            assert_eq!(budget.resident(), 6);
            let (first, allocations) = Tracker::count(|| copy.try_step::<true>(NonZero::<usize>::MIN, &segments::Count::EMPTY));
            assert!(matches!(first, Ok(ControlFlow::Continue(()))));
            assert_eq!(allocations, 1);
            assert_eq!(budget.resident(), 6);
            assert!(matches!(
                copy.try_step::<true>(NonZero::<usize>::MIN.saturating_add(1), &segments::Count::EMPTY),
                Ok(ControlFlow::Continue(()))
            ));
            assert_eq!(budget.resident(), 3);
            let (done, allocations) =
                Tracker::count(|| copy.try_step::<true>(NonZero::<usize>::MIN.saturating_add(2), &segments::Count::EMPTY));
            let output = done
                .map_err(|_| "completion")?
                .break_value()
                .ok_or("complete")?;
            assert_eq!(allocations, 0);
            assert_eq!(output.as_slice(), b"abcdef");
            assert_eq!(budget.resident(), 0);
            let owner = resident::Exact::try_copy(&budget, b"_ab_cd")
                .map_err(|_| "cancel source")?
                .into_shared();
            let spans = [(1u16, 3), (4, 6)];
            let source = ranges::Set::try_new(owner, &spans, 4)
                .map_err(|_| "cancel ranges")?
                .try_retain()
                .map_err(|_| "cancel owner")?;
            let mut pending = source.normalize();
            assert!(matches!(
                pending.try_step::<true>(NonZero::<usize>::MIN, &segments::Count::EMPTY),
                Ok(ControlFlow::Continue(()))
            ));
            assert_eq!(budget.resident(), 6);
            assert_eq!(Tracker::counts(|| drop(pending)).1, [0, 3]);
            assert_eq!(budget.resident(), 0);
            Ok(())
        })
        .map_err(|_| "domain")?
}

#[test]
fn prepared_move_retries_without_consuming_sources() -> Result<(), &'static str> {
    Capacity(9)
        .try_scope(|budget| -> Result<(), &'static str> {
            let pool = segments::source::Pool::try_new(segments::Plan {
                segments: 3,
                chains: 1,
            })
            .map_err(|_| "pool")?;
            let first = resident::Exact::try_copy(&budget, b"abcdef")
                .map_err(|_| "input")?
                .into_shared();
            let second = resident::Exact::try_copy(&budget, b"gh")
                .map_err(|_| "target")?
                .into_shared();
            let blocked = resident::Exact::try_copy(&budget, b"x")
                .map_err(|_| "blocker")?
                .into_shared();
            let addresses = [first.as_ptr(), second.as_ptr()];
            let mut input = Source::EMPTY;
            let mut target = Source::EMPTY;
            let mut blocker = Source::EMPTY;
            for (destination, owner) in [
                (&mut input, first),
                (&mut target, second),
                (&mut blocker, blocked),
            ] {
                let mut incoming = Source::from(owner);
                pool.try_append(destination, &mut incoming)
                    .map_err(|_| "prepared node")?;
                assert!(incoming.is_empty());
            }
            let available = pool.available();
            let charges = [
                buffer::hold::Charge::from(&input),
                buffer::hold::Charge::from(&target),
            ];
            let (failed, activity) = Tracker::counts(|| pool.try_move(&mut input, &mut target, 2));
            assert!(
                matches!(failed, Err(segments::Error::SegmentCapacity(shortage))
                if shortage.requested.get() == 1 && shortage.available == 0)
            );
            assert_eq!(activity, [0, 0]);
            assert!(pool.available() == available);
            assert_eq!(budget.resident(), 9);
            assert_eq!(
                [
                    buffer::hold::Charge::from(&input),
                    buffer::hold::Charge::from(&target),
                ],
                charges
            );
            assert_eq!(input.contiguous(), Some(b"abcdef".as_slice()));
            assert_eq!(target.contiguous(), Some(b"gh".as_slice()));
            assert_eq!(input.front().ok_or("input front")?.as_ptr(), addresses[0]);
            assert_eq!(target.front().ok_or("target front")?.as_ptr(), addresses[1]);

            drop(blocker);
            assert_eq!(pool.available().segments, 1);
            let (moved, activity) = Tracker::counts(|| pool.try_move(&mut input, &mut target, 2));
            moved.map_err(|_| "retry")?;
            assert_eq!(activity, [0, 0]);
            assert_eq!(budget.resident(), 8);
            assert_eq!(input.contiguous(), Some(b"cdef".as_slice()));
            assert_eq!(
                input.front().ok_or("suffix")?.as_ptr(),
                addresses[0].wrapping_add(2)
            );
            assert!(target.segments().eq([b"gh".as_slice(), b"ab"]));
            assert!(
                target
                    .segments()
                    .map(|s| s.as_ptr())
                    .eq([addresses[1], addresses[0]])
            );
            assert_eq!(pool.usage(&input).segments, 1);
            assert_eq!(pool.usage(&target).segments, 2);
            assert_eq!(pool.available().chains, 0);
            drop(target);
            assert_eq!(budget.resident(), 6);
            drop(input);
            assert!(pool.is_idle());
            assert_eq!(budget.resident(), 0);
            Ok(())
        })
        .map_err(|_| "domain")?
}

#[test]
fn prefix_policies_release_prepared_slots() -> Result<(), &'static str> {
    for keep in [false, true] {
        let page = storage::Shared::try_copy(b"abcdef").map_err(|_| "page")?;
        // SAFETY: the unchanged page owns this repr(C) Shared's first field.
        // Its backing keeps the transparent Count live throughout both selections.
        let count = unsafe {
            let tag = &*ptr::from_ref(&page).cast::<Option<storage::regions::Tag>>();
            let tag = tag.as_ref().ok_or("owned page")?;
            &*ptr::from_ref(o3::mem::raw::Edge::count(tag)).cast::<Cell<u32>>()
        };
        let pool = segments::source::Pool::try_new(segments::Plan {
            segments: 2,
            chains: 1,
        })
        .map_err(|_| "pool")?;
        let mut source = Source::EMPTY;
        for range in [0..3, 3..6] {
            let owner = page.try_get(range).map_err(|_| "view")?.ok_or("range")?;
            let mut incoming = Source::from(resident::Shared::from(owner));
            pool.try_append(&mut source, &mut incoming)
                .map_err(|_| "prepared parts")?;
        }
        let refs = count.get();
        let available = pool.available();
        let activity = Tracker::begin();
        {
            let selected = source.prefix::<1>(3).map_err(|_| "charged selection")?;
            assert_eq!(
                selected.charge(),
                buffer::hold::Charge::from_commit(3, 6, 1)
            );
            assert_eq!(count.get(), refs);
            assert!(selected.as_ref().segments().flatten().eq(b"abcdef"));
            assert!(pool.available() == available);
        }
        {
            let selected = source.prefix::<0>(3).map_err(|_| "uncharged selection")?;
            assert_eq!(count.get(), refs);
            assert!(selected.as_ref().segments().flatten().eq(b"abcdef"));
            assert!(pool.available() == available);
        }
        let activity = activity.finish();
        assert_eq!([activity.allocations, activity.deallocations], [0, 0]);
        let selected = source.prefix::<0>(3).map_err(|_| "selected prefix")?;
        let prefix = if keep {
            selected.try_commit::<true>()
        } else {
            selected.try_commit::<false>()
        }
        .map_err(|_| "commit")?;
        assert_eq!(prefix.contiguous(), Some(b"abc".as_slice()));
        assert_eq!(source.contiguous(), Some(b"def".as_slice()));
        assert_eq!(prefix.front().ok_or("prefix")?.as_ptr(), page.as_ptr());
        assert_eq!(
            source.front().ok_or("suffix")?.as_ptr(),
            page.as_ptr().wrapping_add(3)
        );
        assert_eq!(pool.usage(&prefix).segments, 0);
        assert_eq!(pool.usage(&source).segments, usize::from(keep));
        assert_eq!(pool.available().segments, 2 - usize::from(keep));
        assert_eq!(pool.available().chains, 1);
        assert_eq!(count.get(), refs);
        if keep {
            source.try_consume::<true>(1)
        } else {
            source.try_consume::<false>(1)
        }
        .map_err(|_| "consume suffix")?;
        assert_eq!(source.contiguous(), Some(b"ef".as_slice()));
        assert_eq!(pool.available().segments, 2 - usize::from(keep));
        let mut released = buffer::hold::Charge::default();
        // SAFETY: the unchanged final span is two bytes and its charge fits an empty total.
        let resident = unsafe {
            if keep {
                segments::source::raw::pop_front::<true, 1>(&mut source, 2, [&mut released])
            } else {
                segments::source::raw::pop_front::<false, 1>(&mut source, 2, [&mut released])
            }
        };
        assert_eq!(resident, 6);
        assert_eq!(released, buffer::hold::Charge::from_commit(2, 6, 1));
        assert!(pool.is_idle());
        drop(prefix);
        assert_eq!(count.get(), 1);
    }
    let mut prepared = segments::source::ContiguousPool::try_new(segments::Plan {
        segments: 1,
        chains: 0,
    })
    .map_err(|_| "reusable pool")?
    .into_partition();
    prepared
        .try_push(resident::Shared::from(b"abc".as_slice()))
        .map_err(|_| "first data")?;
    let activity = Tracker::begin();
    let first = prepared.try_take(3).map_err(|_| "complete prefix")?;
    assert!(prepared.is_empty());
    assert_eq!(first.len(), 3);
    drop(first);
    prepared
        .try_push(resident::Shared::from(b"def".as_slice()))
        .map_err(|_| "next data")?;
    assert_eq!(prepared.contiguous(), Some(b"def".as_slice()));
    prepared
        .try_consume(3)
        .map_err(|_| "complete consumption")?;
    assert!(prepared.is_empty());
    let activity = activity.finish();
    assert_eq!([activity.allocations, activity.deallocations], [0, 0]);
    assert_eq!(Tracker::counts(|| drop(prepared)).1, [0, 1]);
    Ok(())
}