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
use std::{convert::Infallible, marker, mem, num};

use crate::depot::{capacity, map};

mod flat;
mod layout;
mod table;

pub use flat::Flat;
pub use layout::Layout;
pub use table::Table;

pub(in crate::depot::map) fn scan<D: Directory, E, O: Copy, const SPARE: bool>(
    owner: &D,
    hash: u64,
    matches: impl Fn(D::Occupied) -> Result<Option<O>, E>,
) -> Result<Option<map::Entry<O, Vacant>>, E> {
    let width = owner.buckets();
    if width == 0 {
        return Ok(None);
    }
    let mask = width - 1;
    if SPARE {
        // SAFETY: SPARE retains a vacancy in this nonempty directory.
        return unsafe { scan_spare(owner, hash, mask, matches) }.map(Some);
    }
    let start = hash as usize & mask;
    let mut index = start;
    loop {
        if let Some(entry) = unsafe { at(owner, index, hash, &matches) }? {
            return Ok(Some(entry));
        }
        index = (index + 1) & mask;
        if index == start {
            return Ok(None);
        }
    }
}

/// # Safety
/// The mask is the nonempty directory's bucket count minus one; it retains a vacancy.
unsafe fn scan_spare<D: Directory, E, O: Copy>(
    owner: &D,
    hash: u64,
    mask: usize,
    matches: impl Fn(D::Occupied) -> Result<Option<O>, E>,
) -> Result<map::Entry<O, Vacant>, E> {
    let mut index = hash as usize & mask;
    loop {
        if let Some(entry) = unsafe { at(owner, index, hash, &matches) }? {
            return Ok(entry);
        }
        index = (index + 1) & mask;
    }
}

/// # Safety
/// The index is in this directory.
unsafe fn at<D: Directory, E, O: Copy>(
    owner: &D,
    index: usize,
    hash: u64,
    matches: &impl Fn(D::Occupied) -> Result<Option<O>, E>,
) -> Result<Option<map::Entry<O, Vacant>>, E> {
    Ok(match unsafe { owner.candidate(index, hash) } {
        Candidate::Vacant => Some(map::Entry::Vacant(unsafe { Vacant::new(index) })),
        Candidate::Occupied(slot) => matches(slot)?.map(map::Entry::Occupied),
        Candidate::Skip => None,
    })
}

/// # Safety
/// This exact directory retains an occupied bucket admitted by matches and hash.
pub(in crate::depot::map) unsafe fn member<D: Directory>(
    owner: &D,
    hash: u64,
    matches: impl Fn(D::Occupied) -> bool,
) -> map::raw::Occupied {
    let mask = owner.buckets() - 1;
    let mut index = hash as usize & mask;
    loop {
        if let Candidate::Occupied(slot) = unsafe { owner.candidate(index, hash) }
            && matches(slot)
        {
            return unsafe { Occupied::new(index) };
        }
        index = (index + 1) & mask;
    }
}

/// # Safety
/// The hole belongs to this nonempty directory, which retains a spare bucket.
pub(in crate::depot::map) unsafe fn close<D: Shift>(owner: &mut D, mut hole: map::raw::Vacant) {
    let mask = owner.directory().buckets() - 1;
    let mut next = hole.index();
    loop {
        next = (next + 1) & mask;
        let Some(hash) = (unsafe { owner.directory().hash(next) }) else {
            return;
        };
        let home = hash as usize & mask;
        if next.wrapping_sub(home) & mask > hole.index().wrapping_sub(home) & mask {
            let occupied = unsafe { Occupied::new(next) };
            unsafe { owner.shift(&hole, &occupied, hash) };
            hole = unsafe { Vacant::new(next) };
        }
    }
}

/// # Safety
/// The owner loan retains the same directory and occupied payloads. Projection must preserve their exact owner, bucket, and initialized lifetime.
/// If `SPARE` is true, every nonempty directory retains a vacancy; if `NONEMPTY` is true, its bucket count is nonzero throughout the query.
pub unsafe trait Query: Sized {
    /// Carries the owner's nonempty-directory vacancy guarantee into probing.
    const SPARE: bool = false;
    const NONEMPTY: bool = false;

    type Payload;
    type Value;
    type Occupied;

    fn table(&self) -> &map::raw::Table<Self::Payload>;

    fn value(entry: map::Found<&Self>) -> &Self::Value;

    fn occupied(entry: map::Found<Self>) -> Self::Occupied;

    fn find(self, hash: u64, matches: impl Fn(&Self::Value) -> bool) -> Option<Self::Occupied> {
        self.try_find(hash, move |value| Ok::<_, Infallible>(matches(value)))
            .unwrap_or_else(|never| match never {})
    }

    fn try_find<E>(
        self,
        hash: u64,
        matches: impl Fn(&Self::Value) -> Result<bool, E>,
    ) -> Result<Option<Self::Occupied>, E> {
        let Some(map::Entry::Occupied(bucket)) = query(&self, hash, &matches)? else {
            return Ok(None);
        };
        Ok(Some(Self::occupied(map::Found {
            owner: self,
            bucket,
        })))
    }
}

/// Carries the original owner into its insertion capability.
/// # Safety
/// Insertion must retain the vacancy in the same owner and publish its exact hash and payload before making the bucket occupied.
pub unsafe trait Insertion: Query {
    type Vacant;

    fn vacant(entry: map::Vacancy<Self>, hash: u64) -> Option<Self::Vacant>;

    fn entry(
        self,
        hash: u64,
        matches: impl Fn(&Self::Value) -> bool,
    ) -> map::Entry<Self::Occupied, Option<Self::Vacant>> {
        self.try_entry(hash, move |value| Ok::<_, Infallible>(matches(value)))
            .unwrap_or_else(|never| match never {})
    }

    fn try_entry<E>(
        self,
        hash: u64,
        matches: impl Fn(&Self::Value) -> Result<bool, E>,
    ) -> Result<map::Entry<Self::Occupied, Option<Self::Vacant>>, E> {
        let entry = query(&self, hash, &matches)?;
        drop(matches);
        Ok(match entry {
            Some(map::Entry::Occupied(bucket)) => {
                map::Entry::Occupied(Self::occupied(map::Found {
                    owner: self,
                    bucket,
                }))
            }
            Some(map::Entry::Vacant(bucket)) => map::Entry::Vacant(bucket.admit(self, hash)),
            None => map::Entry::Vacant(None),
        })
    }

    fn reserve(
        self,
        hash: u64,
        matches: impl Fn(&Self::Value) -> bool,
    ) -> map::Entry<(), Option<Self::Vacant>> {
        let entry = query(&self, hash, |value| Ok::<_, Infallible>(matches(value)))
            .unwrap_or_else(|never| match never {});
        match entry {
            Some(map::Entry::Occupied(_)) => map::Entry::Occupied(()),
            Some(map::Entry::Vacant(bucket)) => map::Entry::Vacant(bucket.admit(self, hash)),
            None => map::Entry::Vacant(None),
        }
    }
}

#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct Occupied(num::NonZero<u32>);

#[repr(transparent)]
pub struct Vacant(u32);

impl Occupied {
    /// # Safety
    /// `index` is below the bucket count of the retained `Layout` directory (at most 2^31).
    /// That exact directory retains its initialized occupied bucket until use.
    pub const unsafe fn new(index: usize) -> Self {
        Self(unsafe { num::NonZero::<u32>::new_unchecked(index as u32 + 1) })
    }

    pub const fn index(&self) -> usize {
        self.0.get() as usize - 1
    }
}

impl Vacant {
    pub const fn index(&self) -> usize {
        self.0 as usize
    }

    /// `index` identifies a vacant bucket in a directory made by `Plan`.
    pub(crate) const unsafe fn new(index: usize) -> Self {
        Self(index as u32)
    }
}

/// Physical access retained by one scalar directory owner.
/// # Safety
/// The extent is zero or a power of two at most 2^31; occupied buckets retain initialized same-owner records and stable identities under shared loans. Hashes select placement, not initialization.
pub(in crate::depot::map) unsafe trait Directory {
    type Occupied: Copy;

    fn buckets(&self) -> usize;

    /// # Safety
    /// The index is below this directory's bucket count.
    unsafe fn hash(&self, index: usize) -> Option<u64>;

    /// Vacant names an empty bucket; Occupied and Skip name initialized same-owner records.
    /// # Safety
    /// The index is below the retained bucket count; Occupied may include hash false positives.
    unsafe fn candidate(&self, index: usize, hash: u64) -> Candidate<Self::Occupied>;
}

pub(in crate::depot::map) enum Candidate<O> {
    Occupied(O),
    Vacant,
    Skip,
}

/// Exclusive bucket mutation under the original directory owner.
///
/// # Safety
/// Shifting preserves every live record and updates any reverse directory.
pub(in crate::depot::map) unsafe trait Shift {
    fn directory(&self) -> &impl Directory;

    /// # Safety
    /// Both buckets belong to this owner; next is occupied and hole is vacant.
    unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64);
}

/// # Safety
/// The retained owner has a nonempty directory with a vacant bucket until consumption.
/// A vacant result establishes physical position only.
pub(crate) unsafe fn spare<Q: map::raw::Query>(
    owner: Q,
    hash: u64,
    matches: impl Fn(&Q::Value) -> bool,
) -> map::Entry<Q::Occupied, map::Vacancy<Q>> {
    let buckets = &owner.table().directory;
    let Ok(entry) = unsafe {
        scan_spare(buckets, hash, buckets.buckets() - 1, |bucket| {
            let value = Q::value(map::Found {
                owner: &owner,
                bucket,
            });
            Ok::<_, Infallible>(matches(value).then_some(bucket))
        })
    };
    match entry {
        map::Entry::Occupied(bucket) => {
            drop(matches);
            map::Entry::Occupied(Q::occupied(map::Found { owner, bucket }))
        }
        map::Entry::Vacant(bucket) => map::Entry::Vacant(map::Vacancy {
            owner,
            bucket,
            phase: (),
        }),
    }
}

fn query<Q: map::raw::Query, E>(
    owner: &Q,
    hash: u64,
    matches: impl Fn(&Q::Value) -> Result<bool, E>,
) -> Result<Option<map::Entry<Occupied, Vacant>>, E> {
    let buckets = &owner.table().directory;
    let matches = |bucket| Ok(matches(Q::value(map::Found { owner, bucket }))?.then_some(bucket));
    if Q::NONEMPTY && Q::SPARE {
        // SAFETY: the same owner retains a nonempty directory and a physical vacancy.
        return unsafe { scan_spare(buckets, hash, buckets.buckets() - 1, matches) }.map(Some);
    }
    if Q::SPARE {
        scan::<_, _, _, true>(buckets, hash, matches)
    } else {
        scan::<_, _, _, false>(buckets, hash, matches)
    }
}

impl Vacant {
    fn admit<Q: map::raw::Insertion>(self, owner: Q, hash: u64) -> Option<Q::Vacant> {
        Q::vacant(
            map::Vacancy {
                owner,
                bucket: self,
                phase: (),
            },
            hash,
        )
    }
}

const _: () = {
    assert!(size_of::<map::raw::Occupied>() == size_of::<u32>());
    assert!(size_of::<Option<map::raw::Occupied>>() == size_of::<map::raw::Occupied>());
    assert!(size_of::<map::raw::Vacant>() == size_of::<u32>());
    assert!(size_of::<Option<map::Entry<Occupied, Vacant>>>() == size_of::<u64>());
};

#[repr(transparent)]
pub struct Shape<P> {
    plan: map::Plan,
    value: marker::PhantomData<fn() -> P>,
}

impl<P> Shape<P> {
    pub const fn capacity(self) -> capacity::Count {
        self.plan.capacity()
    }

    pub fn layout(self) -> Layout<P> {
        // SAFETY: this value-bound shape was admitted with the same recipe.
        unsafe { Layout::restore(self.plan) }
    }
}

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

impl<P> Copy for Shape<P> {}

/// Mutates one directory and its reverse indices under the same owner.
/// # Safety
/// Exclusive mutations must preserve the retained table allocation and every occupied payload. Shifts must update the exact directory and reverse indices.
pub unsafe trait Mutation: map::raw::Query {
    /// # Safety
    /// The caller preserves the exact directory and its live payloads.
    unsafe fn table_mut(&mut self) -> &mut Table<Self::Payload>;
    /// # Safety
    /// Both buckets belong to this owner; `next` is live with `hash`, and `hole` is vacant.
    unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64);
}

pub struct Hole<Q> {
    owner: Q,
}

impl<Q: Mutation> Hole<Q> {
    /// # Safety
    /// The bucket is occupied in this exact owner; a spare bucket terminates backshift.
    pub unsafe fn remove(mut owner: Q, bucket: map::raw::Occupied) -> Q::Payload {
        let value = unsafe { owner.table_mut().take(bucket) };
        Self::close(owner, bucket);
        value
    }

    pub(crate) unsafe fn retire(owner: Q, bucket: map::raw::Occupied)
    where
        Q::Payload: Copy,
    {
        Self::close(owner, bucket);
    }

    fn close(mut owner: Q, bucket: map::raw::Occupied) {
        let vacant = unsafe { owner.table_mut().directory.vacate(bucket) };
        // SAFETY: the original owner retains this exact directory after vacating its live bucket.
        unsafe { close(&mut Self { owner }, vacant) };
    }
}

// SAFETY: Mutation updates the exact retained directory and its reverse indices.
unsafe impl<Q: Mutation> Shift for Hole<Q> {
    fn directory(&self) -> &impl Directory {
        &self.owner.table().directory
    }

    unsafe fn shift(&mut self, hole: &Vacant, next: &Occupied, hash: u64) {
        unsafe { self.owner.shift(hole, next, hash) };
    }
}

const _: () = {
    assert!(mem::size_of::<Table<u64>>() == 4 * mem::size_of::<usize>());
    assert!(mem::size_of::<Hole<&mut Flat<u64>>>() == mem::size_of::<usize>());
};