movable_ref/offset/delta.rs
1use std::ptr::NonNull;
2
3/// A nullable pointer, using `NonNull<T>`
4pub type Ptr<T> = Option<NonNull<T>>;
5
6/// Trait for types that can represent pointer differences.
7///
8/// Generalizes pointer arithmetic to integer types like `i8`, `i16`, `i32`.
9/// Used internally by `SelfRef` for offset-based pointer storage.
10///
11/// # Safety
12///
13/// Implementations must maintain these invariants:
14/// - `sub(a, a) == ZERO` for all pointers `a`
15/// - `add(sub(a, b), b) == a` when `sub(a, b)` succeeds
16/// - `add(ZERO, a) == a` for all pointers `a`
17pub unsafe trait Offset: Copy + Eq {
18 /// Error type returned when pointer difference cannot be represented.
19 type Error;
20
21 /// Computes the difference between two pointers.
22 ///
23 /// Returns `Err` if the difference cannot be represented in `Self`.
24 fn sub(a: *mut u8, b: *mut u8) -> Result<Self, Self::Error>;
25
26 /// Computes pointer difference without bounds checking.
27 ///
28 /// # Safety
29 ///
30 /// The difference between `a` and `b` must be representable in `Self`.
31 unsafe fn sub_unchecked(a: *mut u8, b: *mut u8) -> Self;
32
33 /// Adds the offset to a base pointer.
34 ///
35 /// # Safety
36 ///
37 /// The resulting pointer must be valid for the intended use.
38 unsafe fn add(self, a: *const u8) -> *mut u8;
39}
40
41/// A `Delta` type that has a null/zero value.
42///
43/// # Safety
44///
45/// Must satisfy: `add(NULL, ptr) == ptr` for all pointers.
46pub trait Nullable: Offset {
47 /// The null/zero offset value.
48 const NULL: Self;
49}