blart 0.5.0

An implementation of an adaptive radix tree packaged as a BTreeMap replacement
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use alloc::{
    borrow::{Cow, ToOwned},
    boxed::Box,
    ffi::CString,
    rc::Rc,
    string::String,
    sync::Arc,
    vec::Vec,
};
use core::{
    ffi::CStr,
    mem::ManuallyDrop,
    num::{
        NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
        NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
    },
};
#[cfg(feature = "std")]
use std::{
    ffi::{OsStr, OsString},
    io::{IoSlice, IoSliceMut},
    path::{Path, PathBuf},
};

mod mapped;
pub use mapped::*;

/// Any type implementing `AsBytes` can be decomposed into bytes.
///
/// The primary purpose of this trait is to allow different types to be used as
/// keys on the [`crate::TreeMap`] and `TreeSet` types.
pub trait AsBytes {
    /// View the current value as a byte array.
    fn as_bytes(&self) -> &[u8];
}

/// This trait is used to mark types which have a byte representation which is
/// guaranteed to not be a prefix of any other value of the same type.
///
/// # Safety
///  - This trait can only be implemented if the above condition holds.
pub unsafe trait NoPrefixesBytes: AsBytes {}

/// This trait is used to mark types where the lexicographic ordering of their
/// byte representation (as output by [`AsBytes::as_bytes`]) matches their
/// normal ordering (as determined by [`Ord`]).
///
/// # Safety
///  - This trait can only be implemented if the above condition holds.
pub unsafe trait OrderedBytes: AsBytes + Ord {}

macro_rules! as_bytes_for_integer_like_types {
    ($($type:ty),*) => {
        $(
            impl AsBytes for $type {
                fn as_bytes(&self) -> &[u8] {
                    <$type as zerocopy::IntoBytes>::as_bytes(self)
                }
            }

            // SAFETY: This trait is safe to implement because all the byte
            // representations for this type have the same length, ensuring there
            // can't be any prefixes
            unsafe impl NoPrefixesBytes for $type {}

            impl AsBytes for [$type] {
                fn as_bytes(&self) -> &[u8] {
                    <[$type] as zerocopy::IntoBytes>::as_bytes(self)
                }
            }

            impl AsBytes for Vec<$type> {
                fn as_bytes(&self) -> &[u8] {
                    <[$type] as zerocopy::IntoBytes>::as_bytes(self.as_slice())
                }
            }
        )*
    };
}

as_bytes_for_integer_like_types!(
    u8,
    i8,
    u16,
    i16,
    u32,
    i32,
    u64,
    i64,
    u128,
    i128,
    usize,
    isize,
    char,
    bool,
    NonZeroU8,
    NonZeroI8,
    NonZeroU16,
    NonZeroI16,
    NonZeroU32,
    NonZeroI32,
    NonZeroU64,
    NonZeroI64,
    NonZeroU128,
    NonZeroI128,
    NonZeroUsize,
    NonZeroIsize
);

/// SAFETY: Since `u8` is a single byte, there are no concerns about endian
/// ordering
unsafe impl OrderedBytes for u8 {}

macro_rules! as_bytes_for_integer_arrays {
    ($($type:ty),*) => {
        $(
            impl<const N: usize> AsBytes for [$type; N] {
                fn as_bytes(&self) -> &[u8] {
                    <[$type; N] as zerocopy::IntoBytes>::as_bytes(self)
                }
            }

            // SAFETY: This trait is safe to implement because all the byte
            // representations for this type have the same length, ensuring there
            // can't be any prefixes
            unsafe impl<const N: usize> NoPrefixesBytes for [$type; N] {}
        )*
    };
}

as_bytes_for_integer_arrays!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);

/// SAFETY: The lexicographic ordering of `[u8; N]` converted to bytes is the
/// same as its normal representation.
unsafe impl<const N: usize> OrderedBytes for [u8; N] {}

/// SAFETY: The lexicographic ordering of `[u8; N]` converted to bytes is the
/// same as its normal representation.
unsafe impl OrderedBytes for [u8] {}

/// SAFETY: Same reasoning as the `OrderedBytes for [u8]`
unsafe impl OrderedBytes for Vec<u8> {}

impl AsBytes for str {
    fn as_bytes(&self) -> &[u8] {
        str::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
unsafe impl OrderedBytes for str {}

impl AsBytes for String {
    fn as_bytes(&self) -> &[u8] {
        str::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
unsafe impl OrderedBytes for String {}

impl AsBytes for CStr {
    fn as_bytes(&self) -> &[u8] {
        self.to_bytes_with_nul()
    }
}

// SAFETY: The `as_bytes` implementation for `CStr` is guaranteed to always have
// a '\0' byte at the end, that is not present anywhere else in the string. This
// ensures there will never be a prefix value
unsafe impl NoPrefixesBytes for CStr {}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
unsafe impl OrderedBytes for CStr {}

impl AsBytes for CString {
    fn as_bytes(&self) -> &[u8] {
        self.to_bytes_with_nul()
    }
}

// SAFETY: The `as_bytes` implementation for `CStr` is guaranteed to always have
// a '\0' byte at the end, that is not present anywhere else in the string. This
// ensures there will never be a prefix value
unsafe impl NoPrefixesBytes for CString {}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
unsafe impl OrderedBytes for CString {}

#[cfg(unix)]
#[cfg(feature = "std")]
impl AsBytes for OsStr {
    fn as_bytes(&self) -> &[u8] {
        use std::os::unix::prelude::OsStrExt;

        <OsStr as OsStrExt>::as_bytes(self)
    }
}

#[cfg(unix)]
#[cfg(feature = "std")]
impl AsBytes for OsString {
    fn as_bytes(&self) -> &[u8] {
        use std::os::unix::prelude::OsStrExt;

        <OsStr as OsStrExt>::as_bytes(self)
    }
}

#[cfg(feature = "std")]
#[cfg(target_os = "wasi")]
impl AsBytes for OsStr {
    fn as_bytes(&self) -> &[u8] {
        use std::os::wasi::prelude::OsStrExt;

        <OsStr as OsStrExt>::as_bytes(self)
    }
}

#[cfg(feature = "std")]
#[cfg(target_os = "wasi")]
impl AsBytes for OsString {
    fn as_bytes(&self) -> &[u8] {
        use std::os::wasi::prelude::OsStrExt;

        <OsStr as OsStrExt>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
#[cfg(any(unix, target_os = "wasi"))]
#[cfg(feature = "std")]
unsafe impl OrderedBytes for OsStr {}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
#[cfg(any(unix, target_os = "wasi"))]
#[cfg(feature = "std")]
unsafe impl OrderedBytes for OsString {}

#[cfg(any(unix, target_os = "wasi"))]
#[cfg(feature = "std")]
impl AsBytes for Path {
    fn as_bytes(&self) -> &[u8] {
        <OsStr as AsBytes>::as_bytes(self.as_os_str())
    }
}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
#[cfg(any(unix, target_os = "wasi"))]
#[cfg(feature = "std")]
unsafe impl OrderedBytes for Path {}

#[cfg(any(unix, target_os = "wasi"))]
#[cfg(feature = "std")]
impl AsBytes for PathBuf {
    fn as_bytes(&self) -> &[u8] {
        <OsStr as AsBytes>::as_bytes(self.as_os_str())
    }
}

// SAFETY: This trait is safe to implement because the lexicographic
// ordering of bytes and `Ord` implementation are the same
#[cfg(any(unix, target_os = "wasi"))]
#[cfg(feature = "std")]
unsafe impl OrderedBytes for PathBuf {}

impl<B> AsBytes for Cow<'_, B>
where
    B: ToOwned + AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <B as AsBytes>::as_bytes(self.as_ref())
    }
}

// SAFETY: This trait is safe to implement because the underlying owned/borrowed
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<'a, B> OrderedBytes for Cow<'a, B>
where
    B: OrderedBytes + 'a + ToOwned + ?Sized,
    Cow<'a, B>: AsBytes,
{
}

// SAFETY: This trait is safe to implement because the underlying owned/borrowed
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<'a, B> NoPrefixesBytes for Cow<'a, B>
where
    B: NoPrefixesBytes + ToOwned + ?Sized,
    Cow<'a, B>: AsBytes,
{
}

impl<T> AsBytes for &T
where
    T: AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <T as AsBytes>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<T> OrderedBytes for &T where T: OrderedBytes + ?Sized {}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<T> NoPrefixesBytes for &T where T: NoPrefixesBytes + ?Sized {}

impl<T> AsBytes for &mut T
where
    T: AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <T as AsBytes>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<T> OrderedBytes for &mut T where T: OrderedBytes + ?Sized {}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<T> NoPrefixesBytes for &mut T where T: NoPrefixesBytes + ?Sized {}

impl<T> AsBytes for Rc<T>
where
    T: AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <T as AsBytes>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<T> OrderedBytes for Rc<T> where T: OrderedBytes + ?Sized {}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<T> NoPrefixesBytes for Rc<T> where T: NoPrefixesBytes + ?Sized {}

impl<T> AsBytes for Arc<T>
where
    T: AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <T as AsBytes>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<T> OrderedBytes for Arc<T> where T: OrderedBytes + ?Sized {}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<T> NoPrefixesBytes for Arc<T> where T: NoPrefixesBytes + ?Sized {}

impl<T> AsBytes for Box<T>
where
    T: AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <T as AsBytes>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<T> OrderedBytes for Box<T> where T: OrderedBytes + ?Sized {}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<T> NoPrefixesBytes for Box<T> where T: NoPrefixesBytes + ?Sized {}

impl<T> AsBytes for ManuallyDrop<T>
where
    T: AsBytes + ?Sized,
{
    fn as_bytes(&self) -> &[u8] {
        <T as AsBytes>::as_bytes(self)
    }
}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `OrderedBytes`, and the `Ord` impl works the same
// way
unsafe impl<T> OrderedBytes for ManuallyDrop<T> where T: OrderedBytes + ?Sized {}

// SAFETY: This trait is safe to implement because the underlying
// type is already implements `NoPrefixesBytes`, and the wrapper type would not
// change that property
unsafe impl<T> NoPrefixesBytes for ManuallyDrop<T> where T: NoPrefixesBytes + ?Sized {}

#[cfg(feature = "std")]
impl AsBytes for IoSlice<'_> {
    fn as_bytes(&self) -> &[u8] {
        self
    }
}

#[cfg(feature = "std")]
impl AsBytes for IoSliceMut<'_> {
    fn as_bytes(&self) -> &[u8] {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn various_numeric_types_as_bytes() {
        assert_eq!(u8::MAX.as_bytes(), &[u8::MAX]);
        assert_eq!(i8::MAX.as_bytes(), &[i8::MAX as u8]);
        assert_eq!(65535u16.as_bytes(), 65535u16.to_ne_bytes());
        assert_eq!(32767i16.as_bytes(), 32767i16.to_ne_bytes());
        assert_eq!(2387u32.as_bytes(), 2387u32.to_ne_bytes());
        assert_eq!(2387i32.as_bytes(), 2387i32.to_ne_bytes());

        // numeric arrays
        assert_eq!(
            [26343u16, 0, u16::MAX].as_bytes(),
            &[
                26343u16.to_ne_bytes()[0],
                26343u16.to_ne_bytes()[1],
                0,
                0,
                255,
                255
            ]
        );
        assert_eq!(
            Box::<[u16]>::from([26343u16, 0, u16::MAX]).as_bytes(),
            &[
                26343u16.to_ne_bytes()[0],
                26343u16.to_ne_bytes()[1],
                0,
                0,
                255,
                255
            ]
        );
        assert_eq!(
            Vec::<u16>::from([26343u16, 0, u16::MAX]).as_bytes(),
            &[
                26343u16.to_ne_bytes()[0],
                26343u16.to_ne_bytes()[1],
                0,
                0,
                255,
                255
            ]
        );

        // sorta numeric types
        assert_eq!(
            NonZeroU32::try_from(u32::MAX).unwrap().as_bytes(),
            &[255, 255, 255, 255]
        );
        assert_eq!('Z'.as_bytes(), 90u32.to_ne_bytes());
        assert_eq!(false.as_bytes(), &[0]);
    }

    #[test]
    fn various_string_types_as_bytes() {
        assert_eq!(<str as AsBytes>::as_bytes("hello world"), b"hello world");
        assert_eq!(
            <String as AsBytes>::as_bytes(&"hello world".into()),
            b"hello world"
        );
        assert_eq!(
            <CStr as AsBytes>::as_bytes(c"hello world"),
            b"hello world\0"
        );
        assert_eq!(
            <CString as AsBytes>::as_bytes(&c"hello world".into()),
            b"hello world\0"
        );
        assert_eq!(
            <CString as AsBytes>::as_bytes(&c"hello world".into()),
            b"hello world\0"
        );
        #[cfg(feature = "std")]
        #[cfg(any(unix, target_os = "wasi"))]
        {
            assert_eq!(
                <OsStr as AsBytes>::as_bytes(OsStr::new("hello world")),
                b"hello world"
            );
            assert_eq!(
                <OsString as AsBytes>::as_bytes(&OsStr::new("hello world").into()),
                b"hello world"
            );
        }
        #[cfg(feature = "std")]
        #[cfg(any(unix, target_os = "wasi"))]
        {
            assert_eq!(
                <Path as AsBytes>::as_bytes(Path::new("hello/world")),
                b"hello/world"
            );
            assert_eq!(
                <PathBuf as AsBytes>::as_bytes(&Path::new("hello/world").into()),
                b"hello/world"
            );
        }
    }

    #[test]
    fn various_wrapper_types_as_bytes() {
        assert_eq!(
            <&[u8] as AsBytes>::as_bytes(&&b"hello world"[..]),
            b"hello world"
        );
        assert_eq!(
            <Box<&[u8]> as AsBytes>::as_bytes(&Box::new(b"hello world")),
            b"hello world"
        );
        assert_eq!(
            <Box<[u8]> as AsBytes>::as_bytes(&b"hello world".to_vec().into_boxed_slice()),
            b"hello world"
        );
        assert_eq!(
            <Arc<&[u8]> as AsBytes>::as_bytes(&Arc::new(b"hello world")),
            b"hello world"
        );
        assert_eq!(
            <Rc<&[u8]> as AsBytes>::as_bytes(&Rc::new(b"hello world")),
            b"hello world"
        );
        assert_eq!(
            <Cow<[u8]> as AsBytes>::as_bytes(&Cow::Borrowed(b"hello world")),
            b"hello world"
        );
        assert_eq!(
            <ManuallyDrop<&[u8]> as AsBytes>::as_bytes(&ManuallyDrop::new(b"hello world")),
            b"hello world"
        );
        #[cfg(feature = "std")]
        {
            assert_eq!(
                <IoSlice as AsBytes>::as_bytes(&IoSlice::new(b"hello world")),
                b"hello world"
            );
            let mut buffer = [104u8, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];
            assert_eq!(
                <IoSliceMut as AsBytes>::as_bytes(&IoSliceMut::new(&mut buffer)),
                b"hello world"
            )
        }
    }
}