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
use crate::{
    buffer::{
        self, resident,
        segments::Count,
        storage::{self, inline},
    },
    depot::arena::linked,
    mem::{self, Rejected},
};
use std::{
    convert::Infallible,
    mem::{MaybeUninit, replace},
    num::NonZero,
    ops::ControlFlow,
    ptr,
};
mod cursor;
mod cut;
mod data;
mod header;
mod iter;
mod key;
mod part;
mod view;
pub use cursor::Cursor;
pub use cut::Cut;
use cut::{Boundary, Prefix, Selection, Split};
pub use data::Data;
pub use header::Header;
pub(super) use header::Space;
use header::{Descriptor, Logical, Totals};
pub use iter::Iter;
pub use key::Key;
use key::{Occupied, State};
pub use part::Part;
use part::{Group, add_charge, charge_key, release_key};
pub use view::View;

pub struct Normalize<'d, R: Copy = ()> {
    source: Option<Data<'d, (), R>>,
    progress: Progress,
}

impl<'d, R: Copy> From<Option<Data<'d, (), R>>> for Normalize<'d, R> {
    fn from(source: Option<Data<'d, (), R>>) -> Self {
        Self {
            source,
            progress: Progress::Input,
        }
    }
}

impl<'d, R: Copy> Normalize<'d, R> {
    pub fn try_step<const RETAIN: bool>(
        &mut self,
        budget: NonZero<usize>,
        parts: &Count,
    ) -> Result<ControlFlow<storage::Shared<resident::State<'d>>, ()>, storage::AllocError> {
        // SAFETY: these private fields remain one unchanged normalization.
        unsafe {
            self.progress
                .try_step::<RETAIN>(&mut self.source, budget, parts)
        }
    }
}

type Run<'d> = storage::NonEmpty<storage::Shared<resident::State<'d>>>;
type Plain<'d> = Header<Run<'d>>;
type Ranged<'d> = Header<Part<'d>, NonZero<u32>>;

/// A segment partition which retains its pool only while it contains bytes.
#[derive(Debug)]
pub struct Retained<'d> {
    root: MaybeUninit<mem::raw::Owner<Plain<'d>>>,
    key: Key,
}

impl<'d> Retained<'d> {
    pub const fn new() -> Self {
        Self {
            root: MaybeUninit::uninit(),
            key: Key::EMPTY,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.key.is_empty()
    }

    fn pool(&self) -> Option<&Plain<'d>> {
        if self.key.is_empty() {
            None
        } else {
            // SAFETY: publishing the first key installs its edge in the same partition.
            Some(unsafe { self.root.assume_init_ref() }.get())
        }
    }

    pub fn len(&self) -> usize {
        match self.pool() {
            Some(pool) => unsafe { pool.len(&self.key) },
            None => 0,
        }
    }

    pub fn count(&self) -> Count {
        match self.pool() {
            Some(pool) => unsafe { pool.count(&self.key) },
            None => Count::EMPTY,
        }
    }

    pub fn usage(&self) -> super::Plan {
        let (segments, chains) = match self.key.state() {
            None => (0, 0),
            Some(Occupied::Single(_)) => (1, 0),
            Some(Occupied::Multi(index)) => {
                // SAFETY: this key owns this live descriptor in the retained pool.
                let pool = unsafe { self.root.assume_init_ref() }.get();
                (
                    unsafe { pool.rows.value(index) }.totals.nodes.get() as usize,
                    1,
                )
            }
        };
        super::Plan { segments, chains }
    }

    pub fn contiguous(&self) -> Option<&[u8]> {
        match self.pool() {
            Some(pool) => unsafe { pool.contiguous(&self.key) },
            None => Some(&[]),
        }
    }

    pub fn chunks(&self) -> Cursor<'_, 'd, Infallible> {
        match self.pool() {
            Some(pool) => unsafe { Cursor::from_key(pool, &self.key) },
            None => Cursor::empty(),
        }
    }

    pub fn take(&mut self) -> Option<Data<'d, Infallible, Infallible>> {
        if self.key.is_empty() {
            return None;
        }
        let key = replace(&mut self.key, Key::EMPTY);
        // SAFETY: the nonempty key and its edge transfer together exactly once.
        Some(unsafe { key.into_data(self.root.assume_init_read()) })
    }

    /// # Safety
    /// Both nonempty partitions belong to the same pool.
    pub unsafe fn try_join(&mut self, source: &mut Self) -> Result<(), super::Error> {
        let Some(right) = source.key.state() else {
            return Ok(());
        };
        let Some(left) = self.key.state() else {
            self.root.write(unsafe { source.root.assume_init_read() });
            self.key = replace(&mut source.key, Key::EMPTY);
            return Ok(());
        };
        unsafe {
            let pool = self.root.assume_init_ref().get();
            self.key.join(pool, left, right)?;
            source.key = Key::EMPTY;
            source.root.assume_init_drop();
        }
        Ok(())
    }

    pub fn copy_prefix<const CAP: usize, L: buffer::raw::Length>(
        &mut self,
        bytes: &mut inline::Bytes<CAP, L>,
    ) {
        let whole = self.len();
        let mut output = bytes.fit(whole);
        let amount = output.as_mut().len();
        if amount == 0 {
            return;
        }
        unsafe {
            self.key
                .copy_prefix(self.root.assume_init_ref().get(), output.as_mut(), whole);
            if amount == whole {
                self.root.assume_init_drop();
            }
        }
        output.commit();
    }

    /// # Safety
    /// Source and destination pools are distinct. A nonempty target retains its original pool.
    pub unsafe fn try_move(
        &mut self,
        target: &mut Self,
        first: &Plain<'d>,
        limit: usize,
    ) -> Result<usize, super::Error> {
        let whole = self.len();
        let Some(amount) = NonZero::new(limit.min(whole)) else {
            return Ok(0);
        };
        unsafe {
            let source = self.root.assume_init_ref().get();
            if target.key.is_empty() {
                target.key.try_move::<1>(
                    first,
                    source,
                    &mut self.key,
                    amount,
                    whole,
                    [&mut target.root],
                )?;
            } else {
                let pool = target.root.assume_init_ref().get();
                target
                    .key
                    .try_move::<0>(pool, source, &mut self.key, amount, whole, [])?;
            }
            if amount.get() == whole {
                self.root.assume_init_drop();
            }
        }
        Ok(amount.get())
    }
}

impl Default for Retained<'_> {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for Retained<'_> {
    fn drop(&mut self) {
        if let Some(pool) = self.pool() {
            unsafe {
                self.key.clear(pool);
                self.root.assume_init_drop();
            }
        }
    }
}

/// One exclusively owned partition of a borrowed segment pool.
pub struct Partition<'pool, 'd> {
    root: &'pool Plain<'d>,
    key: Key,
}

impl<'pool, 'd> Partition<'pool, 'd> {
    pub fn new(root: &'pool Plain<'d>) -> Self {
        Self {
            root,
            key: Key::EMPTY,
        }
    }

    pub fn count(&self) -> Count {
        unsafe { self.root.count(&self.key) }
    }

    pub fn contiguous(&self) -> Option<&[u8]> {
        unsafe { self.root.contiguous(&self.key) }
    }

    pub fn len(&self) -> usize {
        unsafe { self.root.len(&self.key) }
    }

    pub fn is_empty(&self) -> bool {
        self.key.is_empty()
    }

    pub fn chunks(&self) -> Cursor<'_, 'd, Infallible> {
        unsafe { Cursor::from_key(self.root, &self.key) }
    }

    pub fn try_push(&mut self, owner: Run<'d>) -> Result<(), Rejected<Run<'d>, super::Error>> {
        unsafe { self.key.try_insert(self.root, owner) }
    }

    /// Reuses the last input slot when the replacement is nonempty.
    pub fn try_replace(
        &mut self,
        owner: Option<Run<'d>>,
    ) -> Result<(), Rejected<Run<'d>, super::Error>> {
        let Some(owner) = owner else {
            unsafe { replace(&mut self.key, Key::EMPTY).clear(self.root) };
            return Ok(());
        };
        match self.key.state() {
            None => return self.try_push(owner),
            Some(Occupied::Single(index)) => unsafe { *self.root.nodes.value_ptr(index) = owner },
            Some(Occupied::Multi(index)) => {
                let row = unsafe { linked::raw::Live::detached(&self.root.rows, index) };
                let mut head = row.get().links.head_raw();
                let tail = row.get().links.tail_raw();
                while head != tail {
                    let node = unsafe { linked::raw::Live::detached(&self.root.nodes, head) };
                    head = unsafe { self.root.nodes.next(head) };
                    drop(node);
                }
                unsafe { *self.root.nodes.value_ptr(tail) = owner };
                self.key = Key::single(tail);
            }
        }
        Ok(())
    }
}

impl Drop for Partition<'_, '_> {
    fn drop(&mut self) {
        // SAFETY: the original pool outlives the sole key and its last byte loan.
        unsafe { self.key.clear(self.root) };
    }
}

pub enum Progress {
    Input,
    Copying {
        offset: usize,
        output: storage::Owned,
    },
}

impl Progress {
    /// # Safety
    /// self is Input or the continuation issued for this same source by this
    /// function. Neither value was changed independently during Copying.
    pub unsafe fn try_step<'d, const RETAIN: bool>(
        &mut self,
        source: &mut Option<Data<'d, (), impl Copy>>,
        budget: NonZero<usize>,
        parts: &Count,
    ) -> Result<ControlFlow<storage::Shared<resident::State<'d>>, ()>, storage::AllocError> {
        loop {
            match &mut *self {
                Progress::Input => {
                    let input = ptr::from_mut(source);
                    let Some(value) = source.as_mut() else {
                        return Ok(ControlFlow::Break(
                            storage::Shared::<resident::State<'_>>::default(),
                        ));
                    };
                    let len = match &mut value.state {
                        State::Contiguous { owner, .. } => {
                            let len = owner.len().get();
                            if RETAIN
                                || *parts == Count::ONE
                                || len == buffer::Residency::resident(owner)
                            {
                                let owner = unsafe { ptr::read(owner) };
                                unsafe { ptr::write(input, None) };
                                return Ok(ControlFlow::Break(owner.into_storage()));
                            }
                            len
                        }
                        State::Ranges { owner, .. } => owner.len.get(),
                        State::Plain { root, key } => match unsafe { key.occupied() } {
                            Occupied::Single(index) => {
                                let owner = unsafe { root.get().nodes.take::<_, true>(index) };
                                let original = unsafe { ptr::read(root) };
                                unsafe { ptr::write(input, None) };
                                drop(original);
                                return Ok(ControlFlow::Break(owner.into_storage()));
                            }
                            Occupied::Multi(index) => {
                                unsafe { root.get().rows.value(index) }.totals.len.get()
                            }
                        },
                        State::Ranged { root, key, .. } => match unsafe { key.occupied() } {
                            Occupied::Single(index) => {
                                let metadata = unsafe { &*ptr::from_ref(root.get()) };
                                match unsafe { &mut *metadata.nodes.value_ptr(index) } {
                                    Part::Contiguous(owner) => {
                                        let owner = unsafe { ptr::read(owner) };
                                        let original = unsafe { ptr::read(root) };
                                        unsafe {
                                            ptr::write(input, None);
                                            metadata.nodes.set_next(index, index);
                                        }
                                        drop(unsafe {
                                            linked::raw::Vacant::detached(&metadata.nodes, index)
                                        });
                                        drop(original);
                                        return Ok(ControlFlow::Break(owner.into_storage()));
                                    }
                                    Part::Ranges(owner, _) => owner.len.get(),
                                }
                            }
                            Occupied::Multi(index) => {
                                unsafe { root.get().rows.value(index) }.totals.len.get()
                            }
                        },
                    };
                    let output = storage::Owned::try_with(len)?;
                    *self = Progress::Copying { offset: 0, output };
                }
                Progress::Copying { offset, output } => {
                    let mut left = budget.get();
                    while let Some(value) = source.as_ref() {
                        let bytes = value.front();
                        let len = bytes.len().get();
                        let rest = len - *offset;
                        let amount = left.min(rest);
                        let (written, spare) = buffer::raw::Exclusive::spare_parts(output);
                        let complete = amount == spare.len();
                        unsafe {
                            ptr::copy_nonoverlapping(
                                bytes.as_ref().as_ptr().add(*offset),
                                spare.as_mut_ptr().cast::<u8>(),
                                amount,
                            );
                        }
                        *written += amount as u32;
                        if complete {
                            break;
                        }
                        if amount < rest {
                            *offset += amount;
                            return Ok(ControlFlow::Continue(()));
                        }
                        unsafe { Data::pop_front::<0>(source, len, []) };
                        *offset = 0;
                        left -= amount;
                        if left == 0 {
                            return Ok(ControlFlow::Continue(()));
                        }
                    }
                    let output = unsafe { ptr::read(output) };
                    unsafe { ptr::write(self, Progress::Input) };
                    let output = output.freeze();
                    drop(source.take());
                    return Ok(ControlFlow::Break(output.into()));
                }
            }
        }
    }
}