o3 0.61.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
pub mod common;

use common::alloc::system::Tracker;

#[global_allocator]
static ALLOCATOR: Tracker = Tracker;

use std::{mem::MaybeUninit, pin::Pin};

use o3::{
    base::cell::region,
    buffer::{
        hold, resident,
        segments::{
            self, queue,
            source::raw::{Header, Key, clear_key},
        },
        storage::{self, Shared},
        write::consume::Consume as _,
    },
    depot::capacity::Count,
};

#[test]
fn borrows_prefixes() {
    let mut queue = queue::Fifo::try_with(queue::Capacity::new(Count::new(4), Count::new(2)))
        .expect("source queue");
    assert!(queue.prefix(usize::MAX).is_empty());
    for bytes in [b"ab", b"cd"] {
        queue
            .try_push(resident::Shared::from(bytes.as_slice()))
            .as_ref()
            .expect("source owner");
    }
    queue.try_consume(2).expect("release first slot");
    queue
        .try_push(resident::Shared::from(b"ef".as_slice()))
        .as_ref()
        .expect("reuse wrapped slot");
    assert!(queue.prefix(3).fragments().flatten().eq(b"cde"));
    assert!(queue.prefix(usize::MAX).fragments().flatten().eq(b"cdef"));
}

#[test]
fn projects_suffixes() {
    let mut queue = queue::Fifo::try_with(queue::Capacity::new(Count::new(9), Count::new(3)))
        .expect("source queue");
    let retain = hold::Retention::<resident::Shared<'_>>::default();
    let pool = Header::<storage::NonEmpty<resident::Shared<'_>>>::try_new(segments::Plan {
        segments: 3,
        chains: 1,
    })
    .expect("metadata");
    let mut edge = MaybeUninit::uninit();
    let mut key = Key::EMPTY;
    let empty = queue.get(0..0).expect("empty range");
    // SAFETY: the empty key and uninitialized edge are the final destination of this slice.
    unsafe {
        pool.get().try_bound(
            &empty,
            &retain,
            hold::Policy::compact(),
            &mut edge,
            &mut key,
        )
    }
    .expect("empty projection needs no copy authority");
    // SAFETY: the empty result still belongs to this root; no edge was initialized.
    assert_eq!(unsafe { pool.get().count(&key) }, segments::Count::EMPTY);
    assert!(key.is_empty());

    for bytes in [b"abc", b"def", b"ghi"] {
        queue
            .try_push(resident::Shared::from(bytes.as_slice()))
            .as_ref()
            .expect("source owner");
    }
    for (wrapped, bytes) in [(false, b"abcdefghi"), (true, b"defghijkl")] {
        if wrapped {
            queue.try_consume(3).expect("release first slot");
            queue
                .try_push(resident::Shared::from(b"jkl".as_slice()))
                .as_ref()
                .expect("reuse wrapped slot");
        }
        let suffix = queue.get(4..9).expect("middle-owner suffix");
        let short = Header::<storage::NonEmpty<resident::Shared<'_>>>::try_new(segments::Plan {
            segments: 1,
            chains: 0,
        })
        .expect("insufficient metadata");
        // SAFETY: failed admission leaves this empty key and uninitialized edge unchanged.
        let error = unsafe {
            short.get().try_bound(
                &suffix,
                &retain,
                hold::Policy::compact(),
                &mut edge,
                &mut key,
            )
        }
        .expect_err("segment shortage precedes descriptor and copy failures");
        assert!(matches!(
            error,
            queue::RetainError::Segments(segments::Error::SegmentCapacity(cause))
                if cause.requested.get() == 2 && cause.available == 1
        ));
        assert!(short.get().is_idle());
        // SAFETY: the preceding failure did not initialize the destination.
        let error = unsafe {
            pool.get().try_bound(
                &suffix,
                &retain,
                hold::Policy::compact(),
                &mut edge,
                &mut key,
            )
        }
        .expect_err("nonempty copy requires authority");
        assert_eq!(
            error,
            queue::RetainError::Copy(hold::CopyError::Authority(resident::BindError::Unbound))
        );
        assert!(pool.get().is_idle());

        for (range, count) in [(0..9, 3), (3..9, 2), (4..9, 2), (9..9, 0)] {
            let slice = queue.get(range.clone()).expect("suffix range");
            let mut edge = MaybeUninit::uninit();
            let mut key = Key::EMPTY;
            // SAFETY: this unchanged slice publishes into its empty final fields.
            unsafe {
                pool.get()
                    .try_bound(&slice, &retain, hold::Policy::share(), &mut edge, &mut key)
            }
            .expect("metadata and source remain reusable");
            if count == 0 {
                // SAFETY: an empty slice publishes no edge or nodes.
                assert_eq!(unsafe { pool.get().count(&key) }.into_raw(), count);
                assert!(
                    unsafe { pool.get().runs(&key) }
                        .1
                        .flat_map(|owner| owner.as_ref().iter())
                        .eq(&bytes[range])
                );
            } else {
                // SAFETY: successful nonempty admission initialized this exact retained edge.
                let held = unsafe { edge.assume_init() };
                // SAFETY: key and retained root remain paired until clear_key.
                assert_eq!(unsafe { held.get().count(&key) }.into_raw(), count);
                assert!(
                    unsafe { held.get().runs(&key) }
                        .1
                        .flat_map(|owner| owner.as_ref().iter())
                        .eq(&bytes[range])
                );
                // SAFETY: all byte loans ended and this key is not used after clearing.
                unsafe { clear_key(held.get(), &key) };
                drop(held);
            }
        }
    }
}

#[test]
fn projects_mixed_owners() {
    let first = Shared::try_copy(b"ab").expect("small owner");
    let large = Shared::try_copy(&[b'x'; 64]).expect("large owner");
    let first_at = first.as_slice().as_ptr();
    let large_at = large.as_slice().as_ptr();
    let mut queue = queue::Fifo::try_with(queue::Capacity::new(Count::new(66), Count::new(2)))
        .expect("source queue");
    queue.try_push(first).as_ref().expect("first owner");
    queue.try_push(large).as_ref().expect("large owner");
    let pool = Header::<storage::NonEmpty<resident::Shared<'_>>>::try_new(segments::Plan {
        segments: 2,
        chains: 1,
    })
    .expect("projected metadata");
    let retain = hold::Retention::<Shared>::default();
    let slice = queue.get(0..4).expect("mixed range");
    let mut edge = MaybeUninit::uninit();
    let mut key = Key::EMPTY;
    // SAFETY: this valid nonempty slice publishes into its empty final fields.
    unsafe {
        pool.get().try_bound(
            &slice,
            &retain,
            hold::Policy::new(1, 2),
            &mut edge,
            &mut key,
        )
    }
    .expect("share small owner and copy large projection");
    // SAFETY: successful nonempty admission initialized this exact retained edge.
    let held = unsafe { edge.assume_init() };
    // SAFETY: each read uses the unchanged key from this root.
    assert!(
        unsafe { held.get().runs(&key) }
            .1
            .flat_map(|owner| owner.as_ref().iter())
            .eq(b"abxx")
    );
    assert_eq!(unsafe { held.get().resident(&key) }, 4);
    {
        // SAFETY: no mutation occurs while these owner loans are used.
        let mut owners = unsafe { held.get().runs(&key) }.1;
        assert_eq!(
            owners.next().expect("shared owner").as_ref().as_ptr(),
            first_at
        );
        assert_ne!(
            owners.next().expect("copied owner").as_ref().as_ptr(),
            large_at
        );
    }
    // SAFETY: all byte loans ended and this key is not used after clearing.
    unsafe { clear_key(held.get(), &key) };
    drop(held);
    assert!(pool.get().is_idle());
}

#[test]
fn restores_projection() {
    let mut domain = resident::Domain::new();
    region::Token::scope_pinned(Pin::new(&mut domain), |token, domain| {
        let budget = domain
            .get_mut()
            .try_budget(2, token.proof())
            .expect("two copied bytes");
        let mut retain = hold::Retention::<resident::Shared<'_>>::default();
        retain.try_bind(budget).expect("copy authority");
        let mut queue = queue::Fifo::try_with(queue::Capacity::new(Count::new(76), Count::new(4)))
            .expect("source queue");
        for owner in [
            resident::Shared::from(b"abcdefgh".as_slice()),
            resident::Shared::from(b"ij".as_slice()),
            resident::Shared::from(b"kl".as_slice()),
            resident::Shared::from(Shared::try_copy(&[b'm'; 64]).expect("owned source")),
        ] {
            queue.try_push(owner).as_ref().expect("source owner");
        }
        let pool = Header::<storage::NonEmpty<resident::Shared<'_>>>::try_new(segments::Plan {
            segments: 5,
            chains: 1,
        })
        .expect("projected metadata");
        let mut sibling = Key::EMPTY;
        let owner = storage::NonEmpty::try_new(resident::Shared::from(b"x".as_slice()))
            .expect("nonempty sibling");
        // SAFETY: sibling is this root's empty final key and is held until clearing.
        unsafe { pool.get().try_insert(&mut sibling, owner) }
            .as_ref()
            .expect("independent source");
        let available = pool.get().available();
        let slice = queue.get(0..14).expect("one unread owner after failure");
        let mut edge = MaybeUninit::uninit();
        let mut key = Key::EMPTY;
        // SAFETY: this valid slice publishes only to the empty key and uninitialized edge.
        let error = unsafe {
            pool.get().try_bound(
                &slice,
                &retain,
                hold::Policy::new(8, 2),
                &mut edge,
                &mut key,
            )
        }
        .expect_err("second copy exceeds the unchanged budget");
        assert!(matches!(
            error,
            queue::RetainError::Copy(hold::CopyError::Resident(
                resident::AllocError::Budget(cause)
            )) if cause.into_parts().0.get() == 2 && cause.into_parts().1 == 0
        ));
        assert_eq!(budget.resident(), 0);
        assert!(pool.get().available() == available);
        let mut bytes = [0; 14];
        queue::Array::try_new(&queue.cursor(), 0)
            .expect("unchanged source range")
            .copy(&mut bytes);
        assert_eq!(&bytes, b"abcdefghijklmm");

        // SAFETY: failed retention restored the same uninitialized destination.
        unsafe {
            pool.get()
                .try_bound(&slice, &retain, hold::Policy::share(), &mut edge, &mut key)
        }
        .expect("all metadata was returned");
        // SAFETY: the successful nonempty retry initialized this exact edge.
        let shared = unsafe { edge.assume_init() };
        // SAFETY: key and shared still name this same root and its four published nodes.
        assert_eq!(unsafe { shared.get().count(&key) }.into_raw(), 4);
        assert_eq!(pool.get().available().segments, 0);
        assert_eq!(pool.get().available().chains, 0);
        // SAFETY: this key is no longer read after clearing; sibling remains independent.
        unsafe { clear_key(shared.get(), &key) };
        drop(shared);
        // SAFETY: sibling is the unchanged key inserted in this root above.
        assert_eq!(
            unsafe { pool.get().runs(&sibling) }
                .1
                .next()
                .map(|owner| owner.as_ref()),
            Some(b"x".as_slice())
        );
        // SAFETY: the last sibling loan ended and its key is no longer used.
        unsafe { clear_key(pool.get(), &sibling) };
        assert!(pool.get().is_idle());
    });
}

#[test]
fn recycles_owner_slots() {
    let cap = queue::Capacity::new(Count::new(3), Count::new(2));
    let mut queue =
        queue::Fifo::<Shared>::try_with(cap).expect("the two-owner recycle queue must allocate");
    let first = (storage::Shared::try_copy(&[1])).expect("the first recycle owner must allocate");
    let second = (storage::Shared::try_copy(&[2])).expect("the second recycle owner must allocate");
    let third =
        (storage::Shared::try_copy(&[3])).expect("the rejected recycle owner must allocate");
    let address = third.as_slice().as_ptr();
    queue
        .try_push(first)
        .as_ref()
        .expect("required fixture outcome");
    queue
        .try_push(second)
        .as_ref()
        .expect("required fixture outcome");
    let rejected = queue.try_push(third).expect_err("the segment ring is full");
    let (third, error) = rejected.into_parts();
    assert_eq!(error, queue::Error::Segments { capacity: 2 });
    assert_eq!(third.as_slice().as_ptr(), address);

    let () = (queue.try_consume(1)).expect("the queued one-byte prefix must be consumable");
    queue
        .try_push(third)
        .as_ref()
        .expect("required fixture outcome");
    assert_eq!(queue.segments(), 2);
    assert_eq!(queue.spare_len(), 1);
}

#[test]
fn rejects_byte_overflow() {
    let cap = queue::Capacity::new(Count::new(2), Count::new(1));
    let mut queue = (queue::Fifo::try_with(cap)).expect("the byte-overflow queue must allocate");
    let (first, rejected) = (
        (storage::Shared::try_copy(b"ab")).expect("the byte-overflow owners must allocate"),
        (storage::Shared::try_copy(b"c")).expect("the byte-overflow owners must allocate"),
    );
    let address = rejected.as_slice().as_ptr();
    queue
        .try_push(first)
        .as_ref()
        .expect("required fixture outcome");
    queue
        .try_push(Shared::new())
        .as_ref()
        .expect("empty owner bypasses both exhausted capacities");
    let rejected = queue
        .try_push(rejected)
        .expect_err("byte overflow precedes the exhausted segment ring");
    let (rejected, error) = rejected.into_parts();
    assert!(
        matches!(error, queue::Error::Bytes { requested, available: 0 } if requested.get() == 1)
    );
    assert_eq!(rejected.as_slice(), b"c");
    assert_eq!(rejected.as_slice().as_ptr(), address);
    assert_eq!(queue.segments(), 1);
    assert_eq!(queue.len(), 2);
}

#[test]
fn keeps_owner_boundaries() {
    let first =
        (storage::Shared::try_copy(b"first")).expect("the first boundary owner must allocate");
    let alloc = first.as_slice().as_ptr();
    let cap = queue::Capacity::new(Count::new(11), Count::new(2));
    let mut queue = (queue::Fifo::try_with(cap)).expect("the boundary queue must allocate");
    queue
        .try_push(first)
        .as_ref()
        .expect("required fixture outcome");
    let second =
        (storage::Shared::try_copy(b"second")).expect("the second boundary owner must allocate");
    queue
        .try_push(second)
        .as_ref()
        .expect("required fixture outcome");

    let contig = queue
        .get(1..4)
        .expect("range lies within the first segment")
        .contiguous()
        .expect("range has one owner");
    assert_eq!(contig, b"irs");
    assert_eq!(contig.as_ptr(), alloc.wrapping_add(1));
    assert!(
        queue
            .get(4..7)
            .expect("range spans the segment boundary")
            .contiguous()
            .is_none()
    );
    assert_eq!(
        queue
            .get(4..7)
            .expect("range spans the segment boundary")
            .fragments()
            .collect::<Vec<_>>(),
        [b"t".as_slice(), b"se".as_slice()]
    );
}

#[test]
fn advances_cursor() {
    let cap = queue::Capacity::new(Count::new(9), Count::new(3));
    let mut queue = (queue::Fifo::try_with(cap)).expect("the cursor queue must allocate");
    let first = (storage::Shared::try_copy(b"abc")).expect("the first cursor owner must allocate");
    let second =
        (storage::Shared::try_copy(b"def")).expect("the second cursor owner must allocate");
    queue
        .try_push(first)
        .as_ref()
        .expect("required fixture outcome");
    queue
        .try_push(second)
        .as_ref()
        .expect("required fixture outcome");
    let third = storage::Shared::try_copy(b"ghi").expect("third cursor owner");
    queue
        .try_push(third)
        .as_ref()
        .expect("third cursor segment");

    let mut cursor = queue.cursor();
    cursor.seek(1).expect("first segment");
    let mut copied = [0; 4];
    queue::Array::try_new(&cursor, 2)
        .expect("required fixture outcome")
        .copy(&mut copied);
    assert_eq!(&copied, b"cdef");

    cursor.seek(3).expect("second segment");
    let rejected = queue::Array::<_, 1>::try_new(&cursor, 2);
    let bounds = rejected.err().expect("assertion failed: rejected.is_err()");
    assert_eq!(bounds.offset, 2);
    assert_eq!(bounds.amount, 1);
    assert_eq!(bounds.floor, 3);
    assert_eq!(bounds.ceiling, 9);

    cursor.seek(9).expect("queue end");
    queue::Array::<_, 0>::try_new(&cursor, 9)
        .expect("required fixture outcome")
        .copy(&mut []);
    assert!(cursor.seek(5).is_err());
}

#[test]
fn commits_bounded_prefix() -> Result<(), &'static str> {
    for amount in 0..=9 {
        let cap = queue::Capacity::new(Count::new(9), Count::new(3));
        let mut source = queue::Fifo::try_with(cap).map_err(|_| "queue")?;
        for bytes in [b"ab".as_slice(), b"cde", b"fghi"] {
            source
                .try_push(Shared::try_copy(bytes).map_err(|_| "owner")?)
                .map_err(|_| "slot")?;
        }
        let rejected = queue::Drain::try_new(&mut source, 10)
            .err()
            .ok_or("bounds")?;
        assert_eq!(
            rejected.into_parts(),
            (std::num::NonZero::<usize>::MIN.saturating_add(9), 9)
        );
        drop(queue::Drain::try_new(&mut source, amount).map_err(|_| "admission")?);
        assert_eq!(source.len(), 9);
        let drain = queue::Drain::try_new(&mut source, amount).map_err(|_| "retry")?;
        let ((), activity) = Tracker::measure(|| drain.commit());
        assert_eq!([activity[0], activity[1]], [0, 0]);
        assert_eq!(
            activity[2],
            [2, 5, 9].into_iter().filter(|&end| end <= amount).count()
        );
        assert!(
            source
                .prefix(usize::MAX)
                .fragments()
                .flatten()
                .eq(&b"abcdefghi"[amount..])
        );
        let result = queue::Array::<_, 1>::try_new(&source.cursor(), usize::MAX);
        assert!(
            matches!(result, Err(queue::Bounds { offset: usize::MAX, amount: 1, floor: 0, ceiling }) if ceiling == 9 - amount)
        );
        source
            .try_consume(9 - amount)
            .map_err(|_| "remaining prefix")?;
        source
            .try_push(Shared::try_copy(b"next").map_err(|_| "next")?)
            .map_err(|_| "reused slot")?;
        let mut bytes = [0; 4];
        queue::Array::try_new(&source.cursor(), 0)
            .map_err(|_| "reused range")?
            .copy(&mut bytes);
        assert_eq!(bytes, *b"next");
    }
    Ok(())
}

#[test]
fn queue_releases_only_its_edges() -> Result<(), &'static str> {
    let capacity = queue::Capacity::new(Count::new(8), Count::new(2));
    let mut fifo = queue::Fifo::try_with(capacity).map_err(|_| "queue")?;
    let first = Shared::try_copy(b"abc").map_err(|_| "first")?;
    let second = Shared::try_copy(b"def").map_err(|_| "second")?;
    let third = Shared::try_copy(b"gh").map_err(|_| "third")?;
    let measure = Tracker::begin();
    fifo.try_push(first.try_clone().map_err(|_| "first alias")?)
        .map_err(|_| "first slot")?;
    fifo.try_push(second.try_clone().map_err(|_| "second alias")?)
        .map_err(|_| "second slot")?;
    fifo.try_consume(4).map_err(|_| "prefix")?;
    fifo.try_push(third.try_clone().map_err(|_| "third alias")?)
        .map_err(|_| "reused slot")?;
    let mut output = [0; 4];
    queue::Array::try_new(&fifo.cursor(), 0)
        .map_err(|_| "range")?
        .copy(&mut output);
    assert_eq!(output, *b"efgh");
    assert_eq!(fifo.segments(), 2);
    let activity = measure.finish();
    assert_eq!(activity.allocations, 0);
    assert_eq!(activity.deallocations, 0);
    assert_eq!(Tracker::counts(|| drop(fifo)).1, [0, 1]);
    assert_eq!(
        (first.as_slice(), second.as_slice(), third.as_slice()),
        (b"abc".as_slice(), b"def".as_slice(), b"gh".as_slice())
    );
    Ok(())
}