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
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
use std::num;

use crate::{
    alloc::{self, tail},
    depot,
    depot::map::compact::{self, Found, Layout, Removed, Value},
};

cfg_select! {
    all(target_arch = "aarch64", target_feature = "neon") => {
        mod aarch64;
        use aarch64::group_masks;
    }
    all(target_arch = "x86_64", target_feature = "sse2") => {
        mod x86_64;
        use x86_64::group_masks;
    }
    _ => {
        mod scalar;
        use scalar::group_masks;
    }
}

/// # Safety
/// Layout and initialized storage, including mirrored controls, must stay stable.
/// Found buckets hold unique live bounded payloads in Robin Hood order, with at least one spare bucket.
pub unsafe trait Read: Sized {
    fn layout(&self) -> Layout;
    fn bytes(&self) -> &[u8];
}

/// Resolves records in this source to their canonical, stable hashes.
///
/// # Safety
/// Every stored or admitted payload must retain the hash that places it in this directory.
pub unsafe trait Source: Read {
    fn hash(value: Value<'_, Self>) -> u64;
}

/// # Safety
/// Returned items must retain every source borrow they expose and must not permit directory invalidation.
pub unsafe trait Query: Source {
    type Item;
    fn get(value: Value<'_, Self>) -> Self::Item;
}

/// Mutably borrows only this owner's directory; the associated records stay stable.
///
/// # Safety
/// The mutable bytes must be the same exclusively owned plane returned by `bytes`.
pub unsafe trait Write: Read {
    /// # Safety
    /// Mutation preserves this exact member, hash, and directory bucket positions.
    /// Implementations must return this entry's exact retained owner.
    unsafe fn owner_mut(entry: &mut Found<Self>) -> &mut Self {
        &mut entry.owner
    }
    /// # Safety
    /// Mutations must preserve or consume this source's directory invariants.
    unsafe fn bytes_mut(&mut self) -> &mut [u8];

    /// Resets the control mirror retained by this exact directory owner.
    /// # Safety
    /// Retire this directory's indexed memberships before exposing its owner again.
    unsafe fn clear(&mut self) {
        let layout = self.layout();
        // SAFETY: Write retains this layout and its exclusively owned initialized extent.
        unsafe { init(layout, self.bytes_mut()) };
    }
}

/// Exclusively owns one live record and its membership in this directory.
///
/// # Safety
/// `input` must retain the same indexed member for this operation's entire lifetime.
pub unsafe trait Member: Remove {
    fn input(&self) -> Value<'_, Self>;
}

/// Consumes removal evidence into this source owner's next state.
///
/// # Safety
/// Completion must retire the removed membership before exposing the owner again.
pub unsafe trait Remove: Write + Source {
    /// # Safety
    /// Consume removal into its corresponding record-state transition before exposing the owner.
    /// Implementations must return this removed entry's exact retained owner.
    unsafe fn into_owner(removed: Removed<Self>) -> Self {
        removed.owner
    }
    type Output;
    fn removed(removed: Removed<Self>) -> Self::Output;
}

/// # Safety
/// Owns one stable, bounded, initialized record absent from this nonempty directory.
/// Insertion must preserve an empty bucket; completion publishes the record exactly once.
pub unsafe trait Insert: Write + Source {
    type Output;
    fn input(&self) -> Value<'_, Self>;
    /// # Safety
    /// The directory must have just indexed this operation's record exactly once.
    unsafe fn inserted(self) -> Self::Output;
}

/// One admitted header-and-byte-tail allocation ending at this directory.
/// The prefix and payload bytes start zeroed; controls and mirrors start empty.
pub struct Plan<H> {
    layout: compact::Layout,
    memory: tail::Plan<H, u8>,
}

impl<H> Plan<H> {
    pub fn new(layout: compact::Layout) -> Result<Self, alloc::Overflow> {
        Ok(Self {
            layout,
            memory: tail::Plan::try_new(layout.end())?,
        })
    }

    pub fn try_allocate(self, header: H) -> Result<tail::raw::Block<H, u8>, alloc::Exhausted> {
        let mut block = self.memory.try_allocate()?.repeat(header, 0);
        // SAFETY: admission binds this layout's complete extent to this exact
        // allocation. Its initialized tail is exclusive and not yet published.
        unsafe { init(self.layout, block.as_mut_slice()) };
        Ok(block)
    }
}

impl<H> Clone for Plan<H> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<H> Copy for Plan<H> {}

// SAFETY: callers retain the exact admitted extent and exclusive initialized bytes.
unsafe fn init(layout: Layout, bytes: &mut [u8]) {
    if layout.buckets != 0 {
        unsafe {
            bytes
                .as_mut_ptr()
                .add(layout.start as usize)
                .write_bytes(compact::EMPTY, layout.control_len());
        }
    }
}

pub(in crate::depot::map::compact) struct Store<Q: compact::raw::Read> {
    owner: Q,
    layout: compact::Layout,
}

impl<Q: compact::raw::Read> Store<Q> {
    pub(in crate::depot::map::compact) fn new(owner: Q) -> Self {
        let layout = owner.layout();
        Self { owner, layout }
    }
}

impl<Q: compact::raw::Read> Store<Q> {
    fn bucket(&self, index: usize) -> Bucket {
        Bucket {
            index: index & (self.layout.buckets as usize - 1),
        }
    }

    fn control(&self, bucket: Bucket) -> Control {
        let value = unsafe {
            *self
                .owner
                .bytes()
                .as_ptr()
                .add(self.layout.start as usize + bucket.index)
        };
        Control { bucket, value }
    }

    fn read(&self, resident: Resident) -> Entry {
        let bucket = resident.0.bucket;
        let width = compact::Width::new(self.layout.domain);
        let start = self.layout.plane() + bucket.index * width as usize;
        let bytes = unsafe { self.owner.bytes().as_ptr().add(start) };
        let index = unsafe {
            match width {
                compact::Width::One => u32::from(bytes.read()),
                compact::Width::Two => {
                    u32::from(u16::from_le(bytes.cast::<u16>().read_unaligned()))
                }
                compact::Width::Four => u32::from_le(bytes.cast::<u32>().read_unaligned()),
            }
        };
        Entry {
            bucket,
            payload: Payload { index },
        }
    }

    fn value(&self, payload: Payload) -> compact::Value<'_, Q> {
        compact::Value::new(unsafe { depot::raw::Proof::new((&self.owner, payload.index)) })
    }
}

impl<Q: compact::raw::Write> Store<Q> {
    fn write(&mut self, bucket: Bucket, control: u8, payload: Payload) {
        self.mark(bucket, control);
        let width = compact::Width::new(self.layout.domain);
        let start = self.layout.plane() + bucket.index * width as usize;
        let bytes = unsafe { self.owner.bytes_mut().as_mut_ptr().add(start) };
        unsafe {
            match width {
                compact::Width::One => bytes.write(payload.index as u8),
                compact::Width::Two => bytes
                    .cast::<u16>()
                    .write_unaligned((payload.index as u16).to_le()),
                compact::Width::Four => bytes.cast::<u32>().write_unaligned(payload.index.to_le()),
            }
        }
    }

    fn mark(&mut self, bucket: Bucket, value: u8) {
        let index = self.layout.start as usize + bucket.index;
        let bytes = unsafe { self.owner.bytes_mut().as_mut_ptr() };
        unsafe { bytes.add(index).write(value) };
        if bucket.index < 32 {
            unsafe { bytes.add(index + self.layout.buckets as usize).write(value) };
        }
    }
}

impl<Q: compact::raw::Insert> Store<Q> {
    pub(in crate::depot::map::compact) fn insert(mut self) -> Q::Output {
        let mut payload = Payload {
            index: self.owner.input().index,
        };
        let hash = Q::hash(self.value(payload));
        let mut bucket = self.bucket(hash as usize);
        let mut home = bucket;
        let mut control = (hash >> 57) as u8;
        loop {
            let Some(resident) = self.control(bucket).occupied() else {
                self.write(bucket, control, payload);
                return unsafe { self.owner.inserted() };
            };
            let current = resident.0.value;
            let stored = self.read(resident).payload;
            let origin = self.bucket(Q::hash(self.value(stored)) as usize);
            if (bucket.index.wrapping_sub(home.index) & (self.layout.buckets as usize - 1))
                > (bucket.index.wrapping_sub(origin.index) & (self.layout.buckets as usize - 1))
            {
                self.write(bucket, control, payload);
                control = current;
                payload = stored;
                home = origin;
            }
            bucket = self.bucket(bucket.index + 1);
        }
    }
}

impl<Q: compact::raw::Member> Store<Q> {
    pub(in crate::depot::map::compact) fn locate(self) -> compact::Found<Q> {
        let payload = Payload {
            index: self.owner.input().index,
        };
        let hash = Q::hash(self.value(payload));
        let mut bucket = self.bucket(hash as usize);
        loop {
            if let Some(resident) = self.control(bucket).matching(hash) {
                let entry = self.read(resident);
                if entry.payload == payload {
                    return entry.finish(self);
                }
            }
            bucket = self.bucket(bucket.index + 1);
        }
    }
}

impl<Q: compact::raw::Remove> Store<Q> {
    pub(in crate::depot::map::compact) fn remove(occupied: compact::Found<Q>) -> Q::Output {
        let mut store = Self::new(occupied.owner);
        let mut hole = Bucket {
            index: occupied.bucket.get() as usize - 1,
        };
        while let Some(resident) = store.control(store.bucket(hole.index + 1)).occupied() {
            let control = resident.0.value;
            let entry = store.read(resident);
            let home = store.bucket(Q::hash(store.value(entry.payload)) as usize);
            if entry.bucket.index == home.index {
                break;
            }
            store.write(hole, control, entry.payload);
            hole = entry.bucket;
        }
        store.mark(hole, compact::EMPTY);
        Q::removed(compact::Removed {
            owner: store.owner,
            payload: occupied.payload,
        })
    }
}

#[derive(Clone, Copy)]
struct Bucket {
    index: usize,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct Payload {
    index: u32,
}

struct Resident(Control);

struct Control {
    bucket: Bucket,
    value: u8,
}

impl Control {
    fn occupied(self) -> Option<Resident> {
        if self.value == compact::EMPTY {
            return None;
        }
        Some(Resident(self))
    }

    fn matching(self, hash: u64) -> Option<Resident> {
        if self.value != (hash >> 57) as u8 {
            return None;
        }
        Some(Resident(self))
    }
}

struct Entry {
    bucket: Bucket,
    payload: Payload,
}

impl Entry {
    fn finish<Q: compact::raw::Read>(self, store: Store<Q>) -> compact::Found<Q> {
        // SAFETY: Entry retains this bounded occupied bucket and its exact payload.
        let bucket = unsafe { num::NonZero::new_unchecked(self.bucket.index as u32 + 1) };
        compact::Found {
            owner: store.owner,
            bucket,
            payload: self.payload.index,
        }
    }
}

pub struct Iter<Q: compact::raw::Read> {
    store: Store<Q>,
    hash: u64,
    start: usize,
    bits: u32,
    done: bool,
}

impl<Q: compact::raw::Read> Iter<Q> {
    pub fn empty(owner: Q, hash: u64) -> Self {
        Self {
            store: Store::new(owner),
            hash,
            start: 0,
            bits: 0,
            done: true,
        }
    }

    pub(in crate::depot::map::compact) fn new(owner: Q, hash: u64) -> Self {
        let mut iter = Self::empty(owner, hash);
        let buckets = iter.store.layout.buckets;
        if buckets != 0 {
            iter.start = hash as usize & (buckets as usize - 1);
            iter.load();
        }
        iter
    }

    fn load(&mut self) {
        let start = self.store.layout.start as usize + self.start;
        // SAFETY: this retained nonempty owner admits the complete mirrored
        // group at start; only new and nonterminal advancement load a group.
        let bytes = unsafe {
            &*self
                .store
                .owner
                .bytes()
                .as_ptr()
                .add(start)
                .cast::<[u8; 32]>()
        };
        let (vacant, matched) = group_masks(bytes, (self.hash >> 57) as u8);
        self.bits = matched & (vacant.wrapping_sub(1) & !vacant);
        self.done = vacant != 0;
    }

    pub fn into_owner(self) -> Q {
        self.store.owner
    }
}

impl<Q: compact::raw::Source> Iter<Q> {
    fn next_entry(&mut self) -> Option<Entry> {
        loop {
            let Some(bits) = num::NonZero::new(self.bits) else {
                if self.done {
                    return None;
                }
                self.start = self.store.bucket(self.start + 32).index;
                self.load();
                continue;
            };
            self.bits = bits.get() & (bits.get() - 1);
            let bucket = self
                .store
                .bucket(self.start + bits.trailing_zeros() as usize);
            // SAFETY: this matching control and payload belong to the same
            // retained owner. Its admitted plane contains the complete word.
            let width = compact::Width::new(self.store.layout.domain) as usize;
            let offset = bucket.index * width;
            let start = self.store.layout.plane() + (offset & !3);
            let bytes = unsafe { self.store.owner.bytes().as_ptr().add(start) };
            let word = u32::from_le(unsafe { bytes.cast::<u32>().read_unaligned() });
            let mask = u32::MAX >> (32 - width * 8);
            let entry = Entry {
                bucket,
                payload: Payload {
                    index: (word >> ((offset & 3) * 8)) & mask,
                },
            };
            if Q::hash(self.store.value(entry.payload)) == self.hash {
                return Some(entry);
            }
        }
    }
}

impl<Q: compact::raw::Query> Iterator for Iter<Q> {
    type Item = Q::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let entry = self.next_entry()?;
        Some(Q::get(self.store.value(entry.payload)))
    }
}

const _: () = assert!(size_of::<Payload>() == size_of::<u32>());

impl<Q: compact::raw::Query> Store<Q> {
    pub(in crate::depot::map::compact) fn find(
        self,
        hash: u64,
        key: &Q::Item,
    ) -> Option<compact::Found<Q>>
    where
        Q: compact::raw::Remove,
        Q::Item: Eq,
    {
        if self.layout.buckets == 0 {
            return None;
        }
        let store = self;
        let tag = (hash >> 57) as u8;
        let mut bucket = store.bucket(hash as usize);
        loop {
            let resident = store.control(bucket).occupied()?;
            if resident.0.value == tag {
                let entry = store.read(resident);
                let payload = entry.payload;
                if Q::hash(store.value(payload)) == hash && Q::get(store.value(payload)) == *key {
                    return Some(entry.finish(store));
                }
            }
            bucket = store.bucket(bucket.index + 1);
        }
    }
}

impl<Q: compact::raw::Query> Iter<Q> {
    pub(in crate::depot::map::compact) fn entry(mut self, key: &Q::Item) -> compact::Entry<Q>
    where
        Q::Item: Eq,
    {
        while let Some(entry) = self.next_entry() {
            if Q::get(self.store.value(entry.payload)) == *key {
                return compact::Entry::Occupied(entry.finish(self.store));
            }
        }
        compact::Entry::Vacant(self.into_owner())
    }
}