arctic-wt 0.1.5

Lock-free adaptive radix tree
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
//! Support for owned dynamically sized keys ([`Vec<u8>`], [`Box<[u8]>`][Box]).

use core::borrow::Borrow;
use core::fmt::Debug;
use core::marker::PhantomData;
use core::ops::Deref;
use core::ptr::NonNull;
use std::ffi::CString;

#[cfg(feature = "proptest")]
use proptest::prelude::Strategy;
use ribbit::u6;

use crate::Key;
#[cfg(feature = "proptest")]
use crate::key::Invariant;
use crate::key::Terminated;
use crate::raw::edge;
use crate::raw::edge::Len as _;
use crate::raw::edge::Meta as _;
use crate::raw::key;
use crate::raw::key::Byte;
use crate::raw::key::Len as _;
use crate::raw::key::Read as _;
use crate::raw::key::r#unsized;
use crate::raw::key::r#unsized::Terminate;
use crate::raw::key::r#unsized::slice::Slice;

/// An owned, dynamically sized key that satisfies an [`Invariant`][crate::key::unsized::Invariant].
#[repr(transparent)]
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct BoxedSlice<I, R: ?Sized = [u8]> {
    invariant: PhantomData<I>,
    raw: Box<R>,
}

impl<I, R: ?Sized> Clone for BoxedSlice<I, R>
where
    Box<R>: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            invariant: PhantomData,
            raw: self.raw.clone(),
        }
    }
}

impl<I, R: ?Sized> Default for BoxedSlice<I, R>
where
    Box<R>: Default,
{
    fn default() -> Self {
        Self {
            invariant: PhantomData,
            raw: Default::default(),
        }
    }
}

impl<I, R> BoxedSlice<I, R>
where
    I: r#unsized::Invariant,
    R: ?Sized + r#unsized::slice::Raw,
{
    /// Construct a boxed slice after validating.
    ///
    /// Returns `Ok` if the input boxed slice satisfies the invariant.
    #[inline]
    pub fn new(key: impl Into<Box<R>>) -> Result<Self, (Box<R>, I::Error)> {
        let key = key.into();
        match Slice::<I, R>::new(&key) {
            Ok(_) => Ok(unsafe { Self::new_unchecked(key) }),
            Err(error) => Err((key, error)),
        }
    }
}

impl<I, R: ?Sized> BoxedSlice<I, R> {
    /// Construct a boxed slice without validating.
    ///
    /// # SAFETY
    ///
    /// Caller must guarantee that `raw` satisfies the invariant, i.e.,
    /// `I::validate(key)` would return `Ok(())`.
    #[inline]
    pub const unsafe fn new_unchecked(key: Box<R>) -> Self {
        Self {
            invariant: PhantomData,
            raw: key,
        }
    }

    /// Get a borrowed [`Slice`] that preserves the invariant.
    #[inline]
    pub const fn as_slice(&self) -> &Slice<I, R> {
        unsafe { Slice::new_unchecked(&self.raw) }
    }

    /// Get an owned boxed slice.
    #[inline]
    pub fn into_boxed_slice(self) -> Box<R> {
        self.raw
    }
}

impl<I, R: ?Sized> Deref for BoxedSlice<I, R> {
    type Target = Slice<I, R>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<I, R: ?Sized> Borrow<Slice<I, R>> for BoxedSlice<I, R> {
    #[inline]
    fn borrow(&self) -> &Slice<I, R> {
        self.as_slice()
    }
}

impl<I, R: ?Sized> AsRef<Slice<I, R>> for BoxedSlice<I, R> {
    #[inline]
    fn as_ref(&self) -> &Slice<I, R> {
        self.as_slice()
    }
}

impl From<CString> for BoxedSlice<Terminated<0>, [u8]> {
    fn from(string: CString) -> Self {
        // SAFETY: `CString` is null terminated
        unsafe { Self::new_unchecked(string.into_bytes_with_nul().into_boxed_slice()) }
    }
}

#[cfg(feature = "proptest")]
impl<I, R> proptest::arbitrary::Arbitrary for BoxedSlice<I, R>
where
    I: Invariant,
    R: ?Sized + r#unsized::slice::Raw + core::fmt::Debug,
    Box<R>: proptest::arbitrary::Arbitrary,
{
    type Parameters = <Box<R> as proptest::arbitrary::Arbitrary>::Parameters;
    type Strategy = proptest::strategy::BoxedStrategy<Self>;

    fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
        <Box<R>>::arbitrary_with(args)
            .prop_filter_map("Invariant violated", |boxed_slice| {
                Self::new(boxed_slice).ok()
            })
            .boxed()
    }
}

#[cfg(feature = "rand")]
impl rand::distr::Distribution<BoxedSlice<r#unsized::NonNull, str>>
    for rand::distr::StandardUniform
{
    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> BoxedSlice<r#unsized::NonNull, str> {
        let uniform = rand::distr::Uniform::new_inclusive(1 as char, char::MAX).unwrap();
        let string = rand::distr::SampleString::sample_string(&uniform, rng, 32);
        unsafe { BoxedSlice::new_unchecked(string.into_boxed_str()) }
    }
}

impl<I, R> Key for BoxedSlice<I, R>
where
    I: r#unsized::Invariant,
    R: ?Sized + r#unsized::slice::Raw,
{
    type Read<'k> = Reader<'k, I::Terminate>;
    type Write = Writer;
    type Borrowed = Slice<I, R>;
    type Insert<'k> = &'k Slice<I, R>;
    type Edge = edge::Le;
    type Len = Byte;

    #[inline]
    fn as_insert(&self) -> Self::Insert<'_> {
        self.as_slice()
    }

    #[inline]
    fn insert_as_read<'k>(insert: Self::Insert<'k>) -> Self::Read<'k>
    where
        Self: 'k,
    {
        Reader::from(insert)
    }

    #[inline]
    fn insert_to_key<'k>(insert: Self::Insert<'k>) -> Self
    where
        Self: 'k,
    {
        insert.to_owned()
    }

    #[inline]
    unsafe fn write_as_insert<'k>(writer: &'k Self::Write) -> Self::Insert<'k>
    where
        Self: 'k,
    {
        unsafe { writer.as_slice_unchecked() }
    }
}

impl<'k, I, R> From<&'k Slice<I, R>> for Reader<'k, I::Terminate>
where
    I: r#unsized::Invariant,
    R: ?Sized + r#unsized::slice::Raw,
{
    #[inline]
    fn from(slice: &'k Slice<I, R>) -> Self {
        let slice = slice.as_raw().as_ref();
        Self {
            terminate: I::Terminate::TRUE,
            ..Self::new_prefix(slice)
        }
    }
}

impl<'k, T: Terminate> From<&'k [u8]> for Reader<'k, T> {
    #[inline]
    fn from(prefix: &'k [u8]) -> Self {
        Reader::new_prefix(prefix)
    }
}

impl<'k, T: Terminate> From<&'k str> for Reader<'k, T> {
    #[inline]
    fn from(prefix: &'k str) -> Self {
        Self::from(prefix.as_bytes())
    }
}

impl<'k, const N: usize, T: Terminate> From<&'k [u8; N]> for Reader<'k, T> {
    #[inline]
    fn from(prefix: &'k [u8; N]) -> Self {
        Self::from(prefix.as_slice())
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Reader<'k, T> {
    // Not using slices in order to preserve the
    // pointer provenance of the original slice for
    // `crate::raw::key::slice::Writer` and `crate::raw::edge::Slice`.
    ptr: NonNull<u8>,
    pub(crate) len: usize,
    pub(super) terminate: T,
    slice: PhantomData<&'k [u8]>,
}

impl<'k, T: Default> Reader<'k, T> {
    #[inline]
    pub(crate) fn new_prefix(prefix: &'k [u8]) -> Self {
        Self {
            ptr: NonNull::from(prefix).cast::<u8>(),
            len: prefix.len(),
            terminate: T::default(),
            slice: PhantomData,
        }
    }
}

#[expect(private_bounds)]
impl<'k, T: Terminate> Reader<'k, T> {
    #[inline]
    pub(crate) fn get_byte(&self, index: usize) -> Option<u8> {
        if let Some(byte) = self.as_slice().get(index) {
            return Some(*byte);
        }

        (self.terminate.get() && index == self.len).then_some(0)
    }

    #[inline]
    pub(crate) fn as_slice(&self) -> &'k [u8] {
        // SAFETY: `self.ptr` and `self.len` form a valid slice for lifetime 'k
        unsafe { &*core::ptr::slice_from_raw_parts(self.ptr.as_ptr().cast_const(), self.len) }
    }

    #[inline]
    pub(super) fn as_non_null(&self) -> NonNull<u8> {
        self.ptr
    }
}

impl<T: Default> Default for Reader<'_, T> {
    #[inline]
    fn default() -> Self {
        Self::new_prefix(&[])
    }
}

impl<T: Terminate> key::Read for Reader<'_, T> {
    const LEN: Option<Self::Len> = None;
    type Edge = edge::Le;
    type Len = Byte;

    #[inline]
    fn len(&self) -> Self::Len {
        Byte(self.len + self.terminate.get() as usize)
    }

    #[inline]
    fn get_edge(
        &self,
        len: <ribbit::Packed<Self::Edge> as edge::Meta>::Len,
    ) -> ribbit::Packed<Self::Edge> {
        let len = u6::new((self.len().bits()).min(len.bits()) as u8);
        edge::Le::new(r#unsized::read_u64(self.as_slice()), len)
    }

    #[inline]
    fn get_byte(&self, index: u6) -> Option<u8> {
        self.get_byte(index.bytes())
    }

    #[inline]
    fn match_exact(
        &self,
        edge: <Self::Edge as ribbit::Pack>::Packed,
    ) -> Option<<ribbit::Packed<Self::Edge> as edge::Meta>::Len> {
        // Avoid bit <-> byte conversion
        let len_edge = edge.len();
        let len_match = (edge.raw() ^ r#unsized::read_u64(self.as_slice())).trailing_zeros() as u8;
        (len_match >= len_edge.value()).then_some(len_edge)
    }

    #[inline]
    fn match_prefix(&self, edge: <Self::Edge as ribbit::Pack>::Packed) -> Self::Len {
        Byte(((edge.raw() ^ r#unsized::read_u64(self.as_slice())).trailing_zeros() as usize) >> 3)
    }

    #[inline]
    fn prefix(self, end: Self::Len) -> Self {
        validate!(end <= self.len());
        let end = end.bytes();

        Self {
            ptr: self.ptr,
            len: self.len.min(end),
            terminate: T::new(self.terminate.get() && (end > self.len)),
            slice: PhantomData,
        }
    }

    #[inline]
    fn suffix(self, start: Self::Len) -> Self {
        validate!(start <= self.len());
        let start = start.bytes();
        let offset = self.len.min(start);

        Self {
            len: self.len - offset,
            // NOTE: slice key implementation requires us to preserve the
            // `self.slice` pointer, even if the slice is empty.
            ptr: unsafe { self.ptr.byte_add(offset) },
            terminate: T::new(self.terminate.get() && (start <= self.len)),
            slice: PhantomData,
        }
    }

    #[inline]
    fn common_prefix(self, other: Self) -> Self {
        let index = r#unsized::common_prefix(self.as_slice(), other.as_slice());

        Self {
            ptr: self.ptr,
            len: index,
            terminate: T::new(
                self.terminate.get()
                    && other.terminate.get()
                    && index == self.len
                    && index == other.len,
            ),
            slice: PhantomData,
        }
    }
}

#[doc(hidden)]
#[repr(transparent)]
#[derive(Debug, Default)]
pub struct Writer(Vec<u8>);

impl Writer {
    unsafe fn as_slice_unchecked<I: r#unsized::Invariant, R: ?Sized>(&self) -> &Slice<I, R> {
        let raw = I::Terminate::trim(self.0.as_slice());
        unsafe { Slice::<I, R>::new_unchecked(core::mem::transmute_copy::<&[u8], &R>(&raw)) }
    }
}

impl<'k, T: Terminate> key::Write<Reader<'k, T>> for Writer {
    type Len = Byte;

    #[inline]
    fn new(prefix: Reader<'k, T>, key: ribbit::Packed<edge::Le>) -> (Self, Self::Len) {
        let len = prefix.len() + key.len().into();
        let mut buffer = Vec::new();
        buffer.extend_from_slice(prefix.as_slice());
        if prefix.terminate.get() {
            buffer.push(u8::MIN);
            validate_eq!(key.len().bits(), 0);
        } else {
            buffer.extend(key);
        }
        (Writer(buffer), len)
    }

    #[inline]
    fn replace(&mut self, start: Self::Len, node: u8, edge: ribbit::Packed<edge::Le>) -> Self::Len {
        validate!(start.0 <= self.0.len());
        self.0.truncate(start.0);
        self.0.push(node);
        self.0.extend(edge);
        Byte(self.0.len())
    }
}