o3 0.62.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
use crate::{
    buffer::{self, segments, storage, write::consume},
    depot::{
        arena::linked::{self, fifo::ends},
        capacity,
    },
    mem::{self, Rejected},
};
use std::{
    convert::Infallible,
    mem::{ManuallyDrop, MaybeUninit, replace},
    num::NonZero,
    ptr,
};

mod chain;
mod links;
mod state;
use chain::{grow_converted, grow_inline, grow_pair, promote_inline};
use links::{admit, append_input, append_links, initial_pair};
use links::{insert_one, move_owner, try_existing};
pub(super) use state::State;

/// Portable tagged index for Empty, Single, and Multi states.
#[derive(Debug)]
#[repr(transparent)]
pub struct Key(usize);

/// A decoded key whose retained owner is known to be nonempty.
pub(super) enum Occupied {
    Single(linked::raw::Index),
    Multi(linked::raw::Index),
}
impl Occupied {
    pub(super) unsafe fn head<T, L>(&self, root: &super::Header<T, L>) -> linked::raw::Index {
        match *self {
            Occupied::Single(index) => index,
            Occupied::Multi(index) => unsafe { root.rows.value(index) }.links.head_raw(),
        }
    }

    pub(super) fn row(&self) -> Option<linked::raw::Index> {
        match *self {
            Self::Single(_) => None,
            Self::Multi(index) => Some(index),
        }
    }
    pub(super) unsafe fn links<T, L>(
        &self,
        root: &super::Header<T, L>,
    ) -> ends::Exclusive<linked::raw::Index> {
        match *self {
            Self::Single(index) => unsafe { ends::Exclusive::from_ends(index, index) },
            Self::Multi(index) => unsafe { ptr::read(&root.rows.value(index).links) },
        }
    }
}

impl Key {
    const MULTI: usize = 1usize << (usize::BITS - 1);

    pub const EMPTY: Self = Self(0);

    pub const fn is_empty(&self) -> bool {
        self.0 == 0
    }

    pub(super) const fn state(&self) -> Option<Occupied> {
        if self.0 == 0 {
            return None;
        }
        // SAFETY: the empty key was excluded above.
        Some(unsafe { self.occupied() })
    }

    /// # Safety
    /// This key retains a live single node or multi row, never Empty.
    pub(super) const unsafe fn occupied(&self) -> Occupied {
        let index = unsafe { self.index() };
        if self.0 & Self::MULTI == 0 {
            Occupied::Single(index)
        } else {
            Occupied::Multi(index)
        }
    }

    pub(super) fn single(index: linked::raw::Index) -> Self {
        let value = index.raw() as usize + 1;
        Self(value)
    }

    pub(super) fn multi(index: linked::raw::Index) -> Self {
        let value = index.raw() as usize + 1;
        Self(Self::MULTI | value)
    }

    /// # Safety
    /// This key is nonempty, so its encoded index is positive.
    pub(super) const unsafe fn index(&self) -> linked::raw::Index {
        linked::raw::Index::new(((self.0 & !Self::MULTI) - 1) as u32)
    }

    pub(super) unsafe fn join<'d>(
        &mut self,
        root: &super::Plain<'d>,
        left: Occupied,
        right: Occupied,
    ) -> Result<(), segments::Error> {
        // SAFETY: both occupied keys were read from distinct partitions of this pool.
        unsafe {
            let total = root.totals(&left).try_join(root.totals(&right))?;
            links::append::<_, _, 0, 0>(root, self, Some(left), right, [], [], total)
        }
    }

    /// # Safety
    /// target and source's pooled key are sole, disjoint, and unborrowed.
    /// N is zero for the same root and one for a distinct source root.
    pub unsafe fn try_append<'d, const N: usize, I: Copy>(
        &mut self,
        root: &super::Plain<'d>,
        source: super::Data<'d, I, Infallible>,
    ) -> Result<(), Rejected<super::Data<'d, I, Infallible>, segments::Error>> {
        let target = self;
        let mut source = ManuallyDrop::new(source);
        match unsafe { links::append_input::<N, I>(root, target, &mut source) } {
            Ok(()) => Ok(()),
            Err(error) => Err(Rejected::new(ManuallyDrop::into_inner(source), error)),
        }
    }

    /// # Safety
    /// key exclusively owns its live partition in this root; no node loans remain.
    pub unsafe fn try_insert<'d>(
        &mut self,
        pool: &super::Plain<'d>,
        owner: super::Run<'d>,
    ) -> Result<(), Rejected<super::Run<'d>, segments::Error>> {
        let key = self;
        let mut owner = ManuallyDrop::new(owner);
        match unsafe { links::insert_node(pool, key, &mut owner) } {
            Ok(()) => Ok(()),
            Err(error) => Err(Rejected::new(ManuallyDrop::into_inner(owner), error)),
        }
    }

    /// # Safety
    /// key solely owns this root's partition and no node loans remain.
    pub unsafe fn try_take<'d>(
        &mut self,
        pool: &super::Plain<'d>,
        amount: usize,
    ) -> Result<Option<super::Data<'d, (), Infallible>>, segments::Error> {
        let key = self;
        let whole = unsafe { pool.len(key) };
        consume::Error::check(amount, whole).map_err(segments::Error::Boundary)?;
        let Some(amount) = NonZero::new(amount) else {
            return Ok(None);
        };
        if amount.get() == whole {
            let state = match unsafe { key.occupied() } {
                Occupied::Single(index) => {
                    let owner = unsafe { pool.nodes.take::<_, true>(index) };
                    *key = Key::EMPTY;
                    super::State::Contiguous { owner, inline: () }
                }
                Occupied::Multi(_) => {
                    let root = pool.try_hold().map_err(segments::Error::Retain)?;
                    let key = replace(key, Key::EMPTY);
                    super::State::Plain { root, key }
                }
            };
            return Ok(Some(super::Data { state }));
        }
        let (selected, []) = unsafe { super::Selection::new::<0>(pool, key, amount) };
        let cut = selected.boundary.map(super::Boundary::retain).transpose()?;
        if selected.prefix.total.nodes.get() == 1 {
            let owner = match cut {
                Some(split) => split.take(),
                None => unsafe { pool.nodes.take::<_, true>(selected.prefix.first) },
            };
            unsafe { selected.prefix.suffix(pool, key, None) };
            return Ok(Some(super::Data {
                state: super::State::Contiguous { owner, inline: () },
            }));
        }
        let root = pool.try_hold().map_err(segments::Error::Retain)?;
        pool.nodes
            .check(capacity::Count::new(u32::from(cut.is_some())))
            .map_err(segments::Error::SegmentCapacity)?;
        let donor = if selected.prefix.rest.get() == 1 {
            unsafe { key.occupied() }.row()
        } else {
            None
        };
        if donor.is_none() {
            pool.rows
                .check(capacity::Count::new(1))
                .map_err(segments::Error::ChainCapacity)?;
        }
        let split = unsafe { super::Split::insert(cut, pool) };
        unsafe {
            selected.prefix.suffix(pool, key, donor);
        }
        let key = unsafe { selected.prefix.publish(pool, split, donor) };
        Ok(Some(super::Data {
            state: super::State::Plain { root, key },
        }))
    }

    /// # Safety
    /// key is the sole unchanged partition and whole is its exact length.
    /// output.len() <= whole; output does not overlap the retained source bytes.
    pub(super) unsafe fn copy_prefix<'d>(
        &mut self,
        pool: &super::Plain<'d>,
        output: &mut [u8],
        whole: usize,
    ) {
        let key = self;
        let Some(amount) = NonZero::new(output.len()) else {
            return;
        };
        let original = unsafe { key.occupied() };
        if amount.get() == whole {
            unsafe { copy_whole(pool, key, original, output.as_mut_ptr()) };
            return;
        }
        match original {
            Occupied::Single(index) => {
                let owner = unsafe { &mut *pool.nodes.value_ptr(index) };
                unsafe {
                    ptr::copy_nonoverlapping(
                        owner.as_ref().as_ptr(),
                        output.as_mut_ptr(),
                        amount.get(),
                    );
                }
                unsafe { storage::raw::consume(owner, amount) };
            }
            Occupied::Multi(index) => {
                let row = unsafe { pool.rows.value(index) };
                let first = row.links.head_raw();
                let before = row.totals.nodes;
                let mut next = first;
                let mut last = linked::raw::Index::NONE;
                let mut taken = 0;
                let mut retained = 0;
                let mut left = amount;
                let boundary = loop {
                    let owner = unsafe { pool.nodes.value(next) };
                    let len = owner.len().get();
                    let used = left.get().min(len);
                    unsafe {
                        ptr::copy_nonoverlapping(
                            owner.as_ref().as_ptr(),
                            output.as_mut_ptr().add(amount.get() - left.get()),
                            used,
                        );
                    }
                    if left.get() < len {
                        break Some(left);
                    }
                    taken += 1;
                    retained += buffer::Residency::resident(owner);
                    last = next;
                    next = unsafe { pool.nodes.next(next) };
                    match NonZero::new(left.get() - len) {
                        Some(rest) => left = rest,
                        None => break None,
                    }
                };
                if let Some(boundary) = boundary {
                    unsafe { storage::raw::consume(&mut *pool.nodes.value_ptr(next), boundary) };
                }
                let rest = unsafe { NonZero::new_unchecked(before.get() - taken) };
                unsafe {
                    super::Prefix::update(pool, key, next, rest, amount.get(), retained, None)
                };
                unsafe { super::Prefix::retire(&pool.nodes, first, last, taken) };
            }
        }
    }

    /// # Safety
    /// key is the sole unchanged partition, whole is its exact length, and amount <= whole.
    pub unsafe fn consume<'d>(
        &mut self,
        pool: &super::Plain<'d>,
        amount: NonZero<usize>,
        whole: usize,
    ) {
        let key = self;
        match unsafe { key.occupied() } {
            Occupied::Single(index) => {
                if amount.get() == whole {
                    unsafe { links::clear::<false, _, _>(pool, index) };
                    *key = Key::EMPTY;
                } else {
                    unsafe { storage::raw::consume(&mut *pool.nodes.value_ptr(index), amount) };
                }
            }
            Occupied::Multi(index) => {
                if amount.get() == whole {
                    unsafe { links::clear::<true, _, _>(pool, index) };
                    *key = Key::EMPTY;
                } else {
                    let (selected, []) = unsafe { super::Selection::new::<0>(pool, key, amount) };
                    unsafe { selected.discard(pool, key) };
                }
            }
        }
    }

    /// # Safety
    /// key solely owns this root's partition, with no outstanding node loans.
    pub unsafe fn pop<'d>(&mut self, pool: &super::Plain<'d>) -> Option<super::Run<'d>> {
        let key = self;
        let original = key.state()?;
        let head = match original {
            Occupied::Single(index) => {
                *key = Key::EMPTY;
                index
            }
            Occupied::Multi(index) => {
                let row = unsafe { &mut *pool.rows.value_ptr(index) };
                let head = row.links.head_raw();
                if row.totals.nodes.get() == 2 {
                    *key = Key::single(row.links.tail_raw());
                    drop(unsafe { linked::raw::Live::detached(&pool.rows, index) });
                } else {
                    let owner = unsafe { pool.nodes.value(head) };
                    unsafe {
                        row.remove_front(
                            pool.nodes.next(head),
                            owner.len().get(),
                            buffer::Residency::resident(owner),
                        )
                    };
                }
                head
            }
        };
        Some(unsafe { pool.nodes.take::<_, true>(head) })
    }

    /// # Safety
    /// Keys are sole and disjoint in distinct roots; 0 < amount <= whole, the exact source length.
    /// EDGE is zero for a retained root or one for an empty target and disjoint uninitialized edge.
    pub(super) unsafe fn try_move<'d, const EDGE: usize>(
        &mut self,
        pool: &super::Plain<'d>,
        input: &super::Plain<'d>,
        source: &mut Key,
        amount: NonZero<usize>,
        whole: usize,
        slot: [&mut MaybeUninit<mem::raw::Owner<super::Plain<'d>>>; EDGE],
    ) -> Result<(), segments::Error> {
        let target = self;
        let left = target.state();
        if amount.get() == whole {
            let right = unsafe { source.occupied() };
            let added = unsafe { input.totals(&right) };
            let total = match &left {
                None => added,
                Some(left) => unsafe { pool.totals(left) }.try_join(added)?,
            };
            unsafe {
                links::append::<_, _, 1, EDGE>(
                    pool,
                    target,
                    left,
                    right,
                    [(input, capacity::Count::new(added.nodes.get()))],
                    slot,
                    total,
                )
            }?;
            *source = Key::EMPTY;
            return Ok(());
        }
        let (selected, []) = unsafe { super::Selection::new::<0>(input, source, amount) };
        let cut = selected.boundary.map(super::Boundary::retain).transpose()?;
        let total = match &left {
            None => selected.prefix.total,
            Some(left) => unsafe { pool.totals(left) }.try_join(selected.prefix.total)?,
        };
        pool.nodes
            .check(capacity::Count::new(selected.prefix.total.nodes.get()))
            .map_err(segments::Error::SegmentCapacity)?;
        let donor = match left {
            Some(Occupied::Multi(index)) => Some(index),
            _ => None,
        };
        if total.nodes.get() > 1 && donor.is_none() {
            pool.rows
                .check(capacity::Count::new(1))
                .map_err(segments::Error::ChainCapacity)?;
        }
        if const { EDGE != 0 } {
            slot[0].write(pool.try_hold().map_err(segments::Error::Retain)?);
        }
        let split = unsafe { super::Split::insert(cut, pool) };
        let moved = unsafe { selected.prefix.transfer(input, source, pool, split) };
        unsafe {
            links::append_links::<_, _, false>(pool, target, left.as_ref(), moved, total, donor)
        };
        Ok(())
    }

    /// # Safety
    /// key solely owns this unborrowed partition; root remains live through its return.
    /// Afterward the consumed key may only be overwritten or dropped.
    pub unsafe fn clear<T, L>(&self, root: &super::Header<T, L>) {
        match self.state() {
            None => {}
            Some(Occupied::Single(index)) => unsafe { links::clear::<false, _, _>(root, index) },
            Some(Occupied::Multi(index)) => unsafe { links::clear::<true, _, _>(root, index) },
        }
    }

    /// # Safety
    /// key is nonempty, sole in root, with no outstanding node or byte loans.
    pub unsafe fn into_data<'d>(
        self,
        root: mem::raw::Owner<super::Plain<'d>>,
    ) -> super::Data<'d, Infallible, Infallible> {
        super::Data {
            state: super::State::Plain { root, key: self },
        }
    }
}

unsafe fn copy_whole<'d>(
    root: &super::Plain<'d>,
    key: &mut super::Key,
    original: super::Occupied,
    mut output: *mut u8,
) {
    *key = super::Key::EMPTY;
    match original {
        super::Occupied::Single(index) => {
            let owner = unsafe { linked::raw::Live::detached(&root.nodes, index) };
            let bytes = owner.get().as_ref();
            unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), output, bytes.len()) };
        }
        super::Occupied::Multi(index) => {
            let row = unsafe { linked::raw::Live::detached(&root.rows, index) };
            let nodes = unsafe { linked::raw::Drain::new(&root.nodes, row.get().links.head_raw()) };
            for owner in nodes {
                let bytes = owner.get().as_ref();
                unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), output, bytes.len()) };
                output = unsafe { output.add(bytes.len()) };
            }
            drop(row);
        }
    }
}