viaptr 0.1.0

An experimental library for packing complex types into pointer-sized fields
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
#![feature(associated_const_equality)]
#![feature(doc_cfg)]
#![feature(ptr_mask)]
#![feature(strict_provenance)]
#![warn(unsafe_op_in_unsafe_fn)]
#![no_std]
#![doc = include_str!("../README.md")]

use core::{
    borrow::Borrow,
    marker::PhantomData,
    mem,
    mem::{align_of, ManuallyDrop},
    num::NonZeroUsize,
    ops::{Deref, DerefMut},
    ptr,
};

#[cfg(feature = "alloc")]
extern crate alloc;

pub mod compact;
pub mod shy_atomic;

#[cfg(feature = "alloc")]
#[doc(cfg(feature = "alloc"))]
mod impl_alloc;

#[cfg(feature = "triomphe")]
#[doc(cfg(feature = "triomphe"))]
mod impl_triomphe;

/// Conversion to and from `*const ()`.
pub unsafe trait Pointer: Sized {
    const NON_NULL: bool = false;
    const ALIGNMENT: usize = 1;
    const CLONE_IN_PLACE: bool = false;

    fn into_ptr(value: Self) -> *const ();
    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self>;

    fn as_ptr(value: &Self) -> *const () {
        Self::into_ptr(unsafe { ptr::read(value) })
    }
}


/// Require non-null pointers from [`Pointer::into_ptr`].
pub trait NonNull: Pointer<NON_NULL = true> {}
impl<T: Pointer<NON_NULL = true>> NonNull for T {}

/// Verify [`Pointer`] alignment validity and magnitude.
pub trait VerifyAlignment<const N: usize>: Pointer {
    const VALID: bool = Self::ALIGNMENT.is_power_of_two() && N.is_power_of_two();
    const SUFFICIENT: bool = Self::ALIGNMENT >= N;
}

impl<T: Pointer, const N: usize> VerifyAlignment<N> for T {}

/// Require minimum [`Pointer`] alignment.
pub trait AlignedTo<const N: usize>: VerifyAlignment<N, VALID = true, SUFFICIENT = true> {}

impl<T, const N: usize> AlignedTo<N> for T where
    T: VerifyAlignment<N, VALID = true, SUFFICIENT = true>
{
}

/// A trait for types which can be cloned in place.
pub trait CloneInPlace: Pointer<CLONE_IN_PLACE = true> + Clone {
    fn clone_in_place(value: &Self) {
        mem::forget(value.clone());
    }

    unsafe fn clone_from_ptr(ptr: *const ()) -> Self {
        unsafe { Self::from_ptr(ptr) }.clone()
    }

    unsafe fn clone_by_ptr(ptr: *const ()) {
        mem::forget(unsafe { Self::clone_from_ptr(ptr) })
    }

    unsafe fn drop_one(ptr: *const ()) {
        unsafe { Self::from_ptr(ptr).assume_owned() };
    }
}

impl<T: Pointer<CLONE_IN_PLACE = true> + Clone> CloneInPlace for T {}

/// Predicate evaluation trait.
pub trait Eval {
    const RESULT: bool;
}


/// A wrapper type to construct values which might not own their contents.
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaybeOwned<T>(ManuallyDrop<T>);

impl<T> MaybeOwned<T> {
    pub const fn new(x: T) -> Self {
        Self(ManuallyDrop::new(x))
    }

    pub const unsafe fn assume_owned(self) -> T {
        ManuallyDrop::into_inner(self.0)
    }

    pub unsafe fn drop(slot: &mut Self) {
        unsafe { ManuallyDrop::drop(&mut slot.0) };
    }

    pub unsafe fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwned<U> {
        MaybeOwned::new(f(unsafe { self.assume_owned() }))
    }
}

impl<T> Deref for MaybeOwned<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.0.deref()
    }
}

impl<T> Borrow<T> for MaybeOwned<T> {
    fn borrow(&self) -> &T {
        self.0.borrow()
    }
}


unsafe impl<T> Pointer for *const T {
    fn into_ptr(value: Self) -> *const () {
        value.cast()
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        MaybeOwned::new(ptr.cast())
    }
}


unsafe impl<T> Pointer for ptr::NonNull<T> {
    const NON_NULL: bool = true;

    fn into_ptr(value: Self) -> *const () {
        value.as_ptr() as *const ()
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        MaybeOwned::new(unsafe { ptr::NonNull::new_unchecked(ptr as *mut T) })
    }
}


unsafe impl<T> Pointer for &'static T {
    const NON_NULL: bool = true;
    const ALIGNMENT: usize = align_of::<T>();
    const CLONE_IN_PLACE: bool = true;

    fn into_ptr(value: Self) -> *const () {
        ptr::from_ref(value).cast()
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        MaybeOwned::new(unsafe { &*ptr.cast() })
    }
}

unsafe impl<T: Pointer<NON_NULL = true>> Pointer for Option<T> {
    const ALIGNMENT: usize = T::ALIGNMENT;
    const CLONE_IN_PLACE: bool = T::CLONE_IN_PLACE;

    fn into_ptr(value: Self) -> *const () {
        match value {
            Some(x) => T::into_ptr(x),
            None => ptr::null(),
        }
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        if ptr.is_null() {
            MaybeOwned::new(None)
        } else {
            unsafe { T::from_ptr(ptr).map(Some) }
        }
    }
}


unsafe impl<T, E> Pointer for Result<T, E>
where
    T: Pointer + AlignedTo<2>,
    E: Pointer + AlignedTo<2>,
{
    const NON_NULL: bool = T::NON_NULL;
    const ALIGNMENT: usize = min(T::ALIGNMENT, E::ALIGNMENT) >> 1;
    const CLONE_IN_PLACE: bool = T::CLONE_IN_PLACE && E::CLONE_IN_PLACE;

    fn into_ptr(value: Self) -> *const () {
        let (ptr, tag) = match value {
            Ok(x) => (T::into_ptr(x), 0),
            Err(x) => (E::into_ptr(x), Self::ALIGNMENT),
        };

        ptr.map_addr(|a| a | tag)
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        let tag = ptr.addr() & Self::ALIGNMENT;
        let ptr = ptr.mask(!((Self::ALIGNMENT << 1) - 1));

        if tag == 0 {
            unsafe { T::from_ptr(ptr).map(Ok) }
        } else {
            unsafe { E::from_ptr(ptr).map(Err) }
        }
    }
}


unsafe impl Pointer for usize {
    const CLONE_IN_PLACE: bool = true;

    fn into_ptr(value: Self) -> *const () {
        ptr::without_provenance(value)
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        MaybeOwned::new(ptr.addr())
    }
}


unsafe impl Pointer for NonZeroUsize {
    const NON_NULL: bool = true;
    const CLONE_IN_PLACE: bool = true;

    fn into_ptr(value: Self) -> *const () {
        ptr::without_provenance(value.into())
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        MaybeOwned::new(unsafe { NonZeroUsize::new_unchecked(ptr.addr()) })
    }
}


unsafe impl Pointer for () {
    const NON_NULL: bool = true;
    const ALIGNMENT: usize = 1 << (usize::BITS - 1);
    const CLONE_IN_PLACE: bool = true;

    fn into_ptr(_: Self) -> *const () {
        ptr::without_provenance(Self::ALIGNMENT)
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        debug_assert!(ptr.addr() == Self::ALIGNMENT);
        MaybeOwned::new(())
    }
}


/// A predicate checking if [`usize`] has at least `N` bits.
pub struct FitsInUsize<const N: u32>;

impl<const N: u32> Eval for FitsInUsize<N> {
    const RESULT: bool = N <= usize::BITS;
}


/// Unsigned integers at most `N` bits long.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bits<const N: u32>(usize);

impl<const N: u32> Bits<N>
where
    FitsInUsize<N>: Eval<RESULT = true>,
{
    pub const MASK: usize = (1 << N) - 1;
    const PTR_SHIFT: u32 = usize::BITS - N;

    pub const fn new(value: usize) -> Option<Self> {
        if value & Self::MASK != value {
            None
        } else {
            Some(Self(value))
        }
    }

    pub const fn new_masked(value: usize) -> Self {
        Self(value & Self::MASK)
    }

    pub const fn value(self) -> usize {
        self.0
    }
}

unsafe impl<const N: u32> Pointer for Bits<N>
where
    FitsInUsize<N>: Eval<RESULT = true>,
{
    const ALIGNMENT: usize = 1 << Self::PTR_SHIFT;
    const CLONE_IN_PLACE: bool = true;

    fn into_ptr(value: Self) -> *const () {
        ptr::without_provenance(value.0 << Self::PTR_SHIFT)
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        MaybeOwned::new(Self(ptr.addr() >> Self::PTR_SHIFT))
    }
}


/// A predicate checking if `P` is aligned enough to fit `N` bits.
pub struct FreeBits<P, const N: u32>(PhantomData<P>);

impl<P: Pointer, const N: u32> Eval for FreeBits<P, N> {
    const RESULT: bool = P::ALIGNMENT >= (1 << N);
}

unsafe impl<P, const N: u32> Pointer for (P, Bits<N>)
where
    P: Pointer,
    FitsInUsize<N>: Eval<RESULT = true>,
    FreeBits<P, N>: Eval<RESULT = true>,
{
    const NON_NULL: bool = P::NON_NULL;
    const ALIGNMENT: usize = P::ALIGNMENT >> N;
    const CLONE_IN_PLACE: bool = P::CLONE_IN_PLACE;

    fn into_ptr(value: Self) -> *const () {
        let ptr = P::into_ptr(value.0);
        let tag = value.1.value() << Self::ALIGNMENT.trailing_zeros();
        ptr.map_addr(|a| a | tag)
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        let tag = Bits::<N>::new_masked(ptr.addr() >> Self::ALIGNMENT.trailing_zeros());
        let ptr = ptr.mask(!(P::ALIGNMENT - 1));
        unsafe { P::from_ptr(ptr).map(|p| (p, tag)) }
    }
}


/// Like [`Option`], but preserves [`Pointer`] implementation when nested.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NestOption<T>(pub Option<T>);

impl<T> From<Option<T>> for NestOption<T> {
    fn from(value: Option<T>) -> Self {
        Self(value)
    }
}

impl<T> From<NestOption<T>> for Option<T> {
    fn from(value: NestOption<T>) -> Self {
        value.0
    }
}

impl<T> Deref for NestOption<T> {
    type Target = Option<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for NestOption<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> Borrow<Option<T>> for NestOption<T> {
    fn borrow(&self) -> &Option<T> {
        &self.0
    }
}

unsafe impl<T> Pointer for NestOption<T>
where
    T: Pointer + AlignedTo<2>,
{
    const NON_NULL: bool = T::NON_NULL;
    const ALIGNMENT: usize = T::ALIGNMENT >> 1;
    const CLONE_IN_PLACE: bool = T::CLONE_IN_PLACE;

    fn into_ptr(value: Self) -> *const () {
        match value.into() {
            Some(x) => T::into_ptr(x),
            None => ptr::without_provenance(Self::ALIGNMENT),
        }
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        let tag = ptr.addr() & Self::ALIGNMENT;
        let ptr = ptr.mask(!((Self::ALIGNMENT << 1) - 1));

        if tag == 0 {
            unsafe { T::from_ptr(ptr).map(|p| Self(Some(p))) }
        } else {
            MaybeOwned::new(Self(None))
        }
    }
}


/// A value always encoded as a null pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Null;

unsafe impl Pointer for Null {
    const ALIGNMENT: usize = 1 << (usize::BITS - 1);
    const CLONE_IN_PLACE: bool = true;

    fn into_ptr(_: Self) -> *const () {
        ptr::null()
    }

    unsafe fn from_ptr(ptr: *const ()) -> MaybeOwned<Self> {
        debug_assert!(ptr.is_null());
        MaybeOwned::new(Null)
    }
}


pub(crate) const fn min(x: usize, y: usize) -> usize {
    if x < y {
        x
    } else {
        y
    }
}

pub(crate) const fn max(x: usize, y: usize) -> usize {
    if x > y {
        x
    } else {
        y
    }
}