├── .gitignore ├── Cargo.toml ├── src ├── fmt.rs ├── unreachable.rs ├── error.rs ├── nightly.rs ├── traits.rs ├── tests.rs └── lib.rs ├── MIT-LICENSE ├── README.md └── APACHE-LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | __* -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rel-ptr" 3 | version = "0.2.4" 4 | authors = ["Ozaren "] 5 | repository = "https://github.com/KrishnaSannasi/rel-ptr" 6 | description = "A tool for building movable self-referential types" 7 | keywords = ["relative", "pointer", "ptr", "smart"] 8 | categories = ["no-std"] 9 | license = "MIT" 10 | readme = "README.md" 11 | edition = "2018" 12 | 13 | [features] 14 | default = [] 15 | no_std = [] 16 | nightly = [] 17 | 18 | [dependencies] 19 | -------------------------------------------------------------------------------- /src/fmt.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | use std::fmt::*; 4 | 5 | impl Pointer for RelPtr { 6 | fn fmt(&self, f: &mut Formatter<'_>) -> Result { 7 | write!(f, "{:p}({:?})", self, self.0) 8 | } 9 | } 10 | 11 | impl Debug for RelPtr { 12 | fn fmt(&self, f: &mut Formatter<'_>) -> Result { 13 | f.debug_struct("RelPtr") 14 | .field("ptr", &(self as *const Self)) 15 | .field("offset", &self.0) 16 | .finish() 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/unreachable.rs: -------------------------------------------------------------------------------- 1 | 2 | pub(crate) const OVERFLOW_SUB: &str = "Attempted to subtract with overflow, this is UB in release mode!"; 3 | 4 | /// Adds an unchecked unwrap, this unwrap is UB if self is None 5 | pub(crate) trait UncheckedOptionExt { 6 | type T; 7 | 8 | unsafe fn unchecked_unwrap(self, err: &str) -> Self::T; 9 | } 10 | 11 | impl UncheckedOptionExt for Option { 12 | type T = T; 13 | 14 | #[inline] 15 | #[allow(clippy::assertions_on_constants)] 16 | unsafe fn unchecked_unwrap(self, err: &str) -> T { 17 | match self { 18 | Some(value) => value, 19 | None if cfg!(debug_assertions) => 20 | panic!("{}", err), 21 | None => std::hint::unreachable_unchecked() 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /MIT-LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Krishna Sannasi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * If an integer's range is too small to store an offset, then 4 | * this error is generated 5 | */ 6 | #[derive(Debug)] 7 | pub struct IntegerDeltaError(pub(crate) IntegerDeltaErrorImpl); 8 | 9 | /// All types of errors, this is internal and so protected 10 | /// behind a wrapper struct 11 | #[derive(Debug)] 12 | pub(crate) enum IntegerDeltaErrorImpl { 13 | /// Failed to convert isize to given integer type 14 | Conversion(isize), 15 | 16 | /// Failed to subtract the two usizes (overflowed isize) 17 | Sub(usize, usize), 18 | 19 | /// Got a zero when a non-zero value was expected (for `NonZero*`) 20 | InvalidNonZero 21 | } 22 | 23 | #[cfg(not(feature = "no_std"))] 24 | impl std::error::Error for IntegerDeltaError {} 25 | 26 | mod fmt { 27 | use super::*; 28 | use std::fmt; 29 | 30 | impl fmt::Display for IntegerDeltaError { 31 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 32 | match self.0 { 33 | IntegerDeltaErrorImpl::Conversion(del) => write!( 34 | f, 35 | "Offset could not be stored (offset of {} is too large)", 36 | del 37 | ), 38 | IntegerDeltaErrorImpl::Sub(a, b) => { 39 | write!(f, "Difference is beween {} and {} overflows `isize`", a, b) 40 | }, 41 | 42 | IntegerDeltaErrorImpl::InvalidNonZero => { 43 | write!(f, "Difference was zero when a `NonZero*` type was specified") 44 | } 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src/nightly.rs: -------------------------------------------------------------------------------- 1 | use std::raw::TraitObject as TORepr; 2 | 3 | use super::{MetaData, IntegerDeltaError, IntegerDeltaErrorImpl, Delta, Ptr}; 4 | use crate::unreachable::UncheckedOptionExt as _; 5 | 6 | /// Union to reinterpret bits 7 | union Trans { 8 | t: T, 9 | u: U, 10 | } 11 | 12 | unsafe impl MetaData for TraitObject { 13 | type Data = *mut (); 14 | 15 | #[inline] 16 | fn data(t: &Self) -> Self::Data { 17 | unsafe { Trans::<&Self, TORepr> { t }.u.vtable } 18 | } 19 | 20 | #[inline] 21 | unsafe fn compose(ptr: Ptr, vtable: Self::Data) -> Ptr { 22 | Trans { 23 | u: TORepr { 24 | data: ptr?.as_ptr() as *mut (), 25 | vtable, 26 | }, 27 | }.t 28 | } 29 | } 30 | 31 | /// This takes the place of any trait, this is to allow 32 | /// generalizing over all trait objects 33 | trait Trait {} 34 | 35 | /** 36 | * `TraitObject` represents a trait object generically 37 | * 38 | * You can use trait objects with `RelPtr` like so, 39 | * 40 | * ```rust 41 | * fn main() { 42 | * use rel_ptr::{RelPtr, TraitObject}; 43 | * 44 | * type RelPtrTO = RelPtr>; 45 | * 46 | * // value to store in `RelPtr` 47 | * let mut value: [u8; 10] = [0; 10]; 48 | * 49 | * // setup `RelPtr` 50 | * let mut ptr: RelPtrTO = RelPtr::null(); 51 | * 52 | * // This is safe because `dyn std::any::Any` is a trait object 53 | * // make `&mut TraitObject` 54 | * let to = unsafe { TraitObject::from_mut( 55 | * &mut value as &mut dyn std::any::Any 56 | * ) }; 57 | * 58 | * // set `RelPtr` 59 | * ptr.set(to); 60 | * 61 | * // ... use `RelPtr` 62 | * } 63 | * ``` 64 | * 65 | * # Safety 66 | * 67 | * It is unsafe to use TraitObject with anything other than an actual trait object 68 | */ 69 | #[repr(transparent)] 70 | pub struct TraitObject(dyn Trait); 71 | 72 | impl TraitObject { 73 | /** 74 | * make a new `TraitObject` for use in `RelPtr` 75 | * 76 | * # Safety 77 | * 78 | * This is only safe if `T` is a trait object 79 | */ 80 | pub unsafe fn from_ref(t: &T) -> &Self { 81 | Trans::<&T, &Self> { t: t as _ }.u 82 | } 83 | 84 | /** 85 | * make a new `TraitObject` for use in `RelPtr` 86 | * 87 | * # Safety 88 | * 89 | * This is only safe if `T` is a trait object 90 | */ 91 | pub unsafe fn from_mut(t: &mut T) -> &mut Self { 92 | &mut *(Trans::<*mut T, *mut Self> { t: t as _ }.u) 93 | } 94 | 95 | /// convert a `TraitObject` into the underlying trait object 96 | pub fn as_ref(&self) -> &T { 97 | unsafe { &*(Trans::<*const Self, *const T> { t: self as _ }.u) } 98 | } 99 | 100 | /// convert a `TraitObject` into the underlying trait object 101 | pub fn as_ref_mut(&mut self) -> &mut T { 102 | unsafe { &mut *(Trans::<*mut Self, *mut T> { t: self as _ }.u) } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/traits.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::ptr::NonNull; 3 | 4 | /// A nullable pointer, using NonNull 5 | pub type Ptr = Option>; 6 | 7 | /** 8 | * `Delta` trait generalizes differences in 9 | * memory locations to types like i8 and i16 10 | * 11 | * Note: certain invariants must be upheld to fulfill 12 | * the unsafe contract of this trait, these invariants 13 | * are detailed in each function 14 | * 15 | * This trait is intended to be used with `RelPtr` 16 | */ 17 | pub unsafe trait Delta: Copy + Eq { 18 | /// Error of `Delta::sub` 19 | type Error; 20 | 21 | /** 22 | * The difference between two pointers 23 | * 24 | * Note: for all values of `a: *mut u8`, 25 | * you must enforce that `Delta::sub(a, a) == Delta::ZERO` 26 | * and that the following function does not panic for all values 27 | * of `a` and `b` 28 | * 29 | * ```ignore 30 | * fn for_all_a_b(a: *mut u8, b: *mut u8) { 31 | * if let Some(x) = Self::sub(a, b) { 32 | * unsafe { assert_eq!(Self::add(x, b), a) } 33 | * } 34 | * } 35 | * ``` 36 | */ 37 | fn sub(a: *mut u8, b: *mut u8) -> Result; 38 | 39 | /** 40 | * The difference between two pointers 41 | * 42 | * Note: for all values of `a: *mut u8`, 43 | * you must enforce that `Delta::sub(a, a) == Delta::ZERO` 44 | * and that the following function does not panic for all values 45 | * of `a` and `b` if the difference between `a` and `b` is valid 46 | * 47 | * ```ignore 48 | * fn for_all_a_b(a: *mut u8, b: *mut u8) { 49 | * unsafe { assert_eq!(Self::add(Self::sub_unchecked(a, b), b), a) } 50 | * } 51 | * ``` 52 | * 53 | * Safety: 54 | * 55 | * If the difference between `a` and `b` is not 56 | * representable by `Self` is UB 57 | */ 58 | unsafe fn sub_unchecked(a: *mut u8, b: *mut u8) -> Self; 59 | 60 | /** 61 | * Adds the difference (in `self`) to the pointer `a` 62 | * 63 | * Note: for all values of `a: *mut u8`, 64 | * you must enforce that `Delta::add(Delta::ZERO, a) == a` 65 | * and that the following function does not panic for all values 66 | * of `a` and `b` 67 | * 68 | * ```ignore 69 | * fn for_all_a_b(a: *mut u8, b: *mut u8) { 70 | * if let Some(x) = Self::sub(a, b) { 71 | * unsafe { assert_eq!(Self::add(x, b), a) } 72 | * } 73 | * } 74 | * ``` 75 | * 76 | * # Safety 77 | * TODO 78 | */ 79 | unsafe fn add(self, a: *const u8) -> *mut u8; 80 | } 81 | 82 | /// A index which can contain null 83 | /// 84 | /// # Safety 85 | /// 86 | /// ```ignore 87 | /// fn for_all_a(a: *mut u8) { 88 | /// assert_eq!(a, ::add(Self::NULL, a)); 89 | /// assert_eq!(Self::NULL, ::sub(a, a)); 90 | /// assert_eq!(Self::NULL, ::sub_unchecked(a, a)); 91 | /// } 92 | /// ``` 93 | pub trait Nullable: Delta { 94 | /// The value No change in two pointer locations, 95 | const NULL: Self; 96 | } 97 | 98 | /** 99 | * A trait to abstract over the sizedness of types, 100 | * and to access metadata about a type 101 | * 102 | * If [Custom DST](https://github.com/rust-lang/rfcs/pull/2594) lands and stablizes, 103 | * then it will replace `MetaData` 104 | */ 105 | pub unsafe trait MetaData { 106 | /// the type of meta data a type carries 107 | type Data: Copy + Eq; 108 | 109 | /// decompose a type into a thin pointer and some metadata 110 | fn data(this: &Self) -> Self::Data; 111 | 112 | /// recompose a type from a thin pointer and some metadata 113 | /// 114 | /// it is guarenteed that the metadata is 115 | /// * `ptr == None` `Self::Data` is undefined 116 | /// * `ptr != None` generated from `MetaData::data` 117 | unsafe fn compose(ptr: Ptr, data: Self::Data) -> Ptr; 118 | } 119 | 120 | // Thin pointers 121 | unsafe impl MetaData for T { 122 | type Data = (); 123 | 124 | #[inline] 125 | fn data(_: &Self) -> Self::Data {} 126 | 127 | #[inline] 128 | unsafe fn compose(ptr: Ptr, (): Self::Data) -> Ptr { 129 | ptr.map(NonNull::cast) 130 | } 131 | } 132 | 133 | // slices = ptr + len 134 | unsafe impl MetaData for [T] { 135 | type Data = usize; 136 | 137 | #[inline] 138 | fn data(this: &Self) -> Self::Data { 139 | this.len() 140 | } 141 | 142 | #[inline] 143 | unsafe fn compose(ptr: Ptr, data: Self::Data) -> Ptr { 144 | Some(NonNull::from( 145 | std::slice::from_raw_parts_mut( 146 | ptr?.as_ptr() as *mut T, 147 | data 148 | ) 149 | )) 150 | } 151 | } 152 | 153 | // str slices = ptr + len 154 | unsafe impl MetaData for str { 155 | type Data = usize; 156 | 157 | #[inline] 158 | fn data(this: &Self) -> Self::Data { 159 | this.len() 160 | } 161 | 162 | #[inline] 163 | unsafe fn compose(ptr: Ptr, data: Self::Data) -> Ptr { 164 | Some(NonNull::from( 165 | std::str::from_utf8_unchecked_mut(std::slice::from_raw_parts_mut( 166 | ptr?.as_ptr(), 167 | data 168 | )) 169 | )) 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | struct SelfRef { 4 | t_ref: RelPtr, 5 | t: T, 6 | } 7 | 8 | fn id(t: &mut T) -> &mut T { 9 | t 10 | } 11 | 12 | impl SelfRef { 13 | pub fn new(t: T, f: fn(&mut T) -> &mut U) -> Self { 14 | let mut this = Self { 15 | t: t.into(), 16 | t_ref: RelPtr::null(), 17 | }; 18 | 19 | this.t_ref.set(f(&mut this.t)).unwrap(); 20 | 21 | this 22 | } 23 | 24 | pub fn t(&self) -> &T { 25 | &self.t 26 | } 27 | 28 | pub fn t_mut(&mut self) -> &mut T { 29 | &mut self.t 30 | } 31 | 32 | pub fn t_ref(&self) -> &U { 33 | unsafe { self.t_ref.as_ref_unchecked() } 34 | } 35 | 36 | #[allow(unused)] 37 | pub fn t_ref_mut(&mut self) -> &mut U { 38 | unsafe { self.t_ref.as_mut_unchecked() } 39 | } 40 | } 41 | 42 | #[inline(never)] 43 | fn block_opt(x: T) -> T { 44 | x 45 | } 46 | 47 | #[test] 48 | fn simple_test() { 49 | let mut s = SelfRef { 50 | t: "Hello World", 51 | t_ref: RelPtr::null(), 52 | }; 53 | 54 | s.t_ref.set(&mut s.t).unwrap(); 55 | 56 | assert_eq!(s.t(), s.t_ref()); 57 | assert_eq!(*s.t(), "Hello World"); 58 | assert_eq!(*s.t_ref(), "Hello World"); 59 | } 60 | 61 | #[test] 62 | fn simple_move() { 63 | let mut s = SelfRef { 64 | t: "Hello World", 65 | t_ref: RelPtr::null(), 66 | }; 67 | 68 | s.t_ref.set(&mut s.t).unwrap(); 69 | 70 | assert_eq!(s.t(), s.t_ref()); 71 | assert_eq!(*s.t(), "Hello World"); 72 | assert_eq!(*s.t_ref(), "Hello World"); 73 | 74 | let s = block_opt(s); 75 | 76 | assert_eq!(s.t(), s.t_ref()); 77 | assert_eq!(*s.t(), "Hello World"); 78 | assert_eq!(*s.t_ref(), "Hello World"); 79 | } 80 | 81 | #[test] 82 | fn simple_move_after_init() { 83 | let s = SelfRef::new("Hello World", id); 84 | 85 | assert_eq!(s.t(), s.t_ref()); 86 | assert_eq!(*s.t(), "Hello World"); 87 | assert_eq!(*s.t_ref(), "Hello World"); 88 | 89 | let s = block_opt(s); 90 | 91 | assert_eq!(s.t(), s.t_ref()); 92 | assert_eq!(*s.t(), "Hello World"); 93 | assert_eq!(*s.t_ref(), "Hello World"); 94 | } 95 | 96 | #[test] 97 | fn swap() { 98 | let mut s = SelfRef::new("Hello World", id); 99 | let mut x = SelfRef::new("Killer Move", id); 100 | 101 | assert_eq!(*s.t(), "Hello World"); 102 | assert_eq!(*x.t(), "Killer Move"); 103 | 104 | assert_eq!(*s.t_ref(), "Hello World"); 105 | assert_eq!(*x.t_ref(), "Killer Move"); 106 | 107 | std::mem::swap(&mut s, &mut x); 108 | 109 | assert_eq!(*s.t(), "Killer Move"); 110 | assert_eq!(*x.t(), "Hello World"); 111 | 112 | assert_eq!(*s.t_ref(), "Killer Move"); 113 | assert_eq!(*x.t_ref(), "Hello World"); 114 | } 115 | 116 | #[test] 117 | fn aliasing() { 118 | let mut s = SelfRef::new("Hello World", id); 119 | 120 | assert_eq!(s.t(), s.t_ref()); 121 | 122 | *s.t_mut() = "Killer Move"; 123 | 124 | assert_eq!(*s.t(), "Killer Move"); 125 | assert_eq!(*s.t_ref(), "Killer Move"); 126 | } 127 | 128 | #[test] 129 | fn sub_str() { 130 | #[inline(never)] 131 | fn get_move(s: SelfRef<[u8; 5], [u8]>) { 132 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 133 | assert_eq!(*s.t_ref(), [2, 3, 4]); 134 | } 135 | 136 | let s = SelfRef::new([0, 1, 2, 3, 4], |x| &mut x[2..]); 137 | 138 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 139 | assert_eq!(*s.t_ref(), [2, 3, 4]); 140 | 141 | get_move(s); 142 | } 143 | 144 | #[test] 145 | fn check_copy() { 146 | fn is_copy() {} 147 | 148 | #[allow(unused, path_statements)] 149 | fn check() { 150 | is_copy::>; 151 | } 152 | } 153 | 154 | #[cfg(feature = "nightly")] 155 | mod nightly { 156 | use super::*; 157 | 158 | #[test] 159 | fn check_trait_object_simple() { 160 | let s = SelfRef::<[u8; 5], TraitObject>>::new( 161 | [0, 1, 2, 3, 4], 162 | |x| unsafe { 163 | let x = &mut *(&mut x[2..] as *mut [u8] as *mut [u8; 3]); 164 | TraitObject::from_mut(x) 165 | } 166 | ); 167 | 168 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 169 | 170 | let eq: &[u8] = &[2, 3, 4]; 171 | assert!(s.t_ref().as_ref() == eq); 172 | } 173 | 174 | #[test] 175 | fn check_trait_object_after_move() { 176 | let s = SelfRef::<[u8; 5], TraitObject>>::new( 177 | [0, 1, 2, 3, 4], 178 | |x| unsafe { 179 | let x = &mut *(&mut x[2..] as *mut [u8] as *mut [u8; 3]); 180 | TraitObject::from_mut(x) 181 | } 182 | ); 183 | 184 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 185 | 186 | let eq: &[u8] = &[2, 3, 4]; 187 | assert!(s.t_ref().as_ref() == eq); 188 | 189 | #[inline(never)] 190 | fn force_move(t: T) -> T { 191 | t 192 | } 193 | 194 | let s = force_move(s); 195 | 196 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 197 | 198 | assert!(s.t_ref().as_ref() == eq); 199 | } 200 | 201 | #[test] 202 | #[cfg(not(feature = "no_std"))] 203 | fn check_trait_object_after_move_heap() { 204 | let s = SelfRef::<[u8; 5], TraitObject>>::new( 205 | [0, 1, 2, 3, 4], 206 | |x| unsafe { 207 | let x = &mut *(&mut x[2..] as *mut [u8] as *mut [u8; 3]); 208 | TraitObject::from_mut(x) 209 | } 210 | ); 211 | 212 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 213 | 214 | let eq: &[u8] = &[2, 3, 4]; 215 | assert!(s.t_ref().as_ref() == eq); 216 | 217 | let s = Box::new(s); 218 | 219 | assert_eq!(*s.t(), [0, 1, 2, 3, 4]); 220 | 221 | let eq: &[u8] = &[2, 3, 4]; 222 | assert!(s.t_ref().as_ref() == eq); 223 | } 224 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rel-ptr 2 | 3 | `rel-ptr` a library for relative pointers, which can be used to create 4 | moveable self-referential types. This library was inspired by 5 | Johnathan Blow's work on Jai, where he added relative pointers 6 | as a primitive into Jai. 7 | 8 | A relative pointer is a pointer that uses an offset and it's current location to 9 | calculate where it points to. 10 | 11 | Minimum Rust Version = 1.36.0 12 | 13 | ## Safety 14 | 15 | See the `RelPtr` type docs for safety information 16 | 17 | ## Features 18 | 19 | ### `no_std` 20 | 21 | This crate is `no-std` compatible, simply add the feature `no_std` to move into `no_std` mode. 22 | 23 | ### nightly 24 | 25 | with nightly you get the ability to use trait objects with relative pointers 26 | 27 | ## Example 28 | 29 | take the memory segment below 30 | 31 | `[.., 0x3a, 0x10, 0x02, 0xe4, 0x2b ..]` 32 | 33 | where `0x3a` has the address `0xff304050` (32-bit system) 34 | then `0x2b` has the address `0xff304054`. 35 | 36 | if we have a 1-byte relative pointer (`RelPtr<_, i8>`) 37 | at the address `0xff304052`, then that relative pointer points to 38 | `0x2b` as well, this is because its address `0xff304052`, plus its 39 | offset, `0x02` points to `0x2b`. 40 | 41 | There are three interesting things 42 | about this 43 | 1) it only took 1 byte to point to another value, 44 | 2) a relative pointer cannot access all memory, only memory near it 45 | 3) if both the relative pointer and the pointee move together, 46 | then the relative pointer will not be invalidated 47 | 48 | The third point is what makes moveable self-referential structs possible 49 | 50 | The type `RelPtr` is a relative pointer. `T` is what it points to, 51 | and `I` is what it uses to store its offset. In practice you can ignore `I`, 52 | which is defaulted to `isize`, because that will cover all of your cases for using 53 | relative pointers. But if you want to optimize the size of the pointer, you can use 54 | any type that implements `Delta`. Some types from std that do so are: 55 | `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`. Note that the trade off is that as you 56 | decrease the size of the offset, you decrease the range to which you can point to. 57 | `isize` will cover at least half of addressable memory, so it should work unless you do 58 | something really crazy. For self-referential structs use a type whose max value is atleast 59 | as big as your struct. i.e. `std::mem::size_of::() <= I::max_value()`. 60 | 61 | Note on usized types: these are harder to get working 62 | 63 | ## Self Referential Type Example 64 | 65 | ```rust 66 | struct SelfRef { 67 | value: (String, u32), 68 | ptr: RelPtr 69 | } 70 | 71 | impl SelfRef { 72 | pub fn new(s: String, i: u32) -> Self { 73 | let mut this = Self { 74 | value: (s, i), 75 | ptr: RelPtr::null() 76 | }; 77 | 78 | this.ptr.set(&mut this.value.0).unwrap(); 79 | 80 | this 81 | } 82 | 83 | pub fn fst(&self) -> &str { 84 | unsafe { self.ptr.as_ref_unchecked() } 85 | } 86 | 87 | pub fn snd(&self) -> u32 { 88 | self.value.1 89 | } 90 | } 91 | 92 | let s = SelfRef::new("Hello World".into(), 10); 93 | 94 | assert_eq!(s.fst(), "Hello World"); 95 | assert_eq!(s.snd(), 10); 96 | 97 | let s = Box::new(s); // force a move, note: relative pointers even work on the heap 98 | 99 | assert_eq!(s.fst(), "Hello World"); 100 | assert_eq!(s.snd(), 10); 101 | ``` 102 | 103 | This example is contrived, and only useful as an example. 104 | In this example, we can see a few important parts to safe moveable self-referential types, 105 | lets walk through them. 106 | 107 | First, the definition of `SelfRef`, it contains a value and a relative pointer, the relative pointer that will point into the tuple inside of `SelfRef.value` to the `String`. There are no lifetimes involved because they would either make `SelfRef` immovable, or they could not be resolved correctly. 108 | 109 | We see a pattern inside of `SelfRef::new`, first create the object, and use the sentinel `RelPtr::null()` and immediately afterwards assigning it a value using `RelPtr::set` and unwraping the result. This unwrapping is get quick feedback on whether or not the pointer was set, if it wasn't set then we can increase the size of the offset and resolve that. 110 | 111 | Once the pointer is set, moving the struct is still safe because it is using a *relative* pointer, so it doesn't matter where it is, only it's offset from its pointee. 112 | In `SelfRef::fst` we use `RelPtr::as_ref_unchecked` because it is impossible to invalidate the pointer. It is impossible because we cannot 113 | set the relative pointer directly, and we cannot change the offsets of the fields of `SelfRef` after the relative pointer is set. 114 | 115 | --- 116 | 117 | # License 118 | 119 | 120 | Licensed under either of Apache License, Version 121 | 2.0 or MIT license at your option. 122 | 123 | 124 |
125 | 126 | 127 | Unless you explicitly state otherwise, any contribution intentionally submitted 128 | for inclusion in `rel-ptr` by you, as defined in the Apache-2.0 license, shall be 129 | dual licensed as above, without any additional terms or conditions. 130 | 131 | 132 | --- 133 | # Release Notes 134 | 135 | ## 0.2.4 136 | 137 | ### Changes 138 | 139 | * Chaned to `std::mem::MaybeUnint` from a custom version because it is stable now on rustc version 1.36.0 140 | 141 | ## 0.2.3 142 | 143 | ### Changes 144 | 145 | * Moved `NonZero*` out of nightly due to rustc version 1.34.0 146 | 147 | ## 0.2.2 148 | 149 | ### Removals 150 | 151 | * dependency to `unreachable` 152 | * unnecessary in the presence of `std::hint::unreachable`, also it is safer to use the `std` version because `std` version is guarenteed to be optimized away 153 | * has a different behaviour on debug mode than I want, new impl panics on debug mode and is optimized away on release mode 154 | 155 | ## 0.2.1 156 | 157 | ### Additions 158 | 159 | * Documentation on `Nullable` and how it plays with `Delta` 160 | 161 | ### Changes 162 | 163 | * Fixed mutability bug, getting a raw ptr (`*mut T`) or a non-nullable ptr (`NonNull`) should require a unique lock on `RelPtr` 164 | 165 | 166 | ## 0.2.0 167 | 168 | ### Additions 169 | 170 | * Added constructors on `TraitObject`, now there is `from_ref` and `from_mut` to allow easier transitions to and from `TraitObject` 171 | * More documentation 172 | 173 | ### Removals 174 | 175 | * `Default` bound for `MetaData::Data` 176 | * It is now UB to access `MetaData::Data` before the relative pointer is set 177 | * `TraitObject::new` in favor of the new constructors 178 | 179 | ### Changes 180 | 181 | * Reworked `MetaData::decompose` 182 | * Chagned to `MetaData::data`, the pointer can be extracted via pointer casts, so only data was needed 183 | * Converted `MetaData` to use `std::mem::NonNull` as it is easier to work with 184 | * This is due to using `Option>` allows representing null even if `T: !Sized` 185 | 186 | ### Notes 187 | 188 | I am not anticipating any more large scale changes to the api, so this should be as the final api. I will wait and see if any there are any bugs, before releasing 1.0.0. I will also have to wait on the results of [this](https://github.com/rust-lang/unsafe-code-guidelines/issues/97) github discussion around the layouts of types, as it relates to how safe this model of moveable self-referential types are. 189 | 190 | ## 0.1.4 191 | 192 | ### Additions 193 | 194 | * Support for `NonZero*` integers 195 | * Formatting for all `RelPtr` whose idicies support formatting 196 | 197 | ### Changes 198 | 199 | * Converted api to use `&mut T` instead of `&T` 200 | * this better represents the semantics of `RelPtr` and was suggested by [Yandros](https://users.rust-lang.org/u/Yandros) 201 | * Moved `Delta::ZERO` to `Nullable::NULL` 202 | * This was to enable support for `NonZero*` types 203 | * Updated documentation to better explain possible UB 204 | 205 | * Changed from `TraitObject::into` to `TraitObject::as_ref` and `TraitObject::as_mut` 206 | -------------------------------------------------------------------------------- /APACHE-LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(feature = "no_std", no_std)] 2 | #![cfg_attr(feature = "nightly", feature(const_fn, raw))] 3 | #![allow(clippy::needless_doctest_main)] 4 | #![forbid(missing_docs)] 5 | 6 | /*! 7 | # rel-ptr 8 | 9 | `rel-ptr` a library for relative pointers, which can be used to create 10 | moveable self-referential types. This library was inspired by 11 | Johnathan Blow's work on Jai, where he added relative pointers 12 | as a primitive into Jai. 13 | 14 | A relative pointer is a pointer that uses an offset and it's current location to 15 | calculate where it points to. 16 | 17 | ## Safety 18 | 19 | See the `RelPtr` type docs for safety information 20 | 21 | ## Features 22 | 23 | ### `no_std` 24 | 25 | This crate is `no-std` compatible, simply add the feature `no_std` to move into `no_std` mode. 26 | 27 | ### nightly 28 | 29 | with nightly you get the ability to use trait objects with relative pointers 30 | 31 | ## Example 32 | 33 | take the memory segment below 34 | 35 | `[.., 0x3a, 0x10, 0x02, 0xe4, 0x2b ..]` 36 | 37 | where `0x3a` has the address `0xff304050` (32-bit system) 38 | then `0x2b` has the address `0xff304054`. 39 | 40 | if we have a 1-byte relative pointer (`RelPtr<_, i8>`) 41 | at the address `0xff304052`, then that relative pointer points to 42 | `0x2b` as well, this is because its address `0xff304052`, plus its 43 | offset, `0x02` points to `0x2b`. 44 | 45 | There are three interesting things 46 | about this 47 | 1) it only took 1 byte to point to another value, 48 | 2) a relative pointer cannot access all memory, only memory near it 49 | 3) if both the relative pointer and the pointee move together, 50 | then the relative pointer will not be invalidated 51 | 52 | The third point is what makes moveable self-referential structs possible 53 | 54 | The type `RelPtr` is a relative pointer. `T` is what it points to, 55 | and `I` is what it uses to store its offset. In practice you can ignore `I`, 56 | which is defaulted to `isize`, because that will cover all of your cases for using 57 | relative pointers. But if you want to optimize the size of the pointer, you can use 58 | any type that implements `Delta`. Some types from std that do so are: 59 | `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`. Note that the trade off is that as you 60 | decrease the size of the offset, you decrease the range to which you can point to. 61 | `isize` will cover at least half of addressable memory, so it should work unless you do 62 | something really crazy. For self-referential structs use a type whose max value is atleast 63 | as big as your struct. i.e. `std::mem::size_of::() <= I::max_value()`. 64 | 65 | Note on usized types: these are harder to get working 66 | 67 | ## Self Referential Type Example 68 | 69 | ```rust 70 | # fn main() { 71 | # use rel_ptr::RelPtr; 72 | struct SelfRef { 73 | value: (String, u32), 74 | ptr: RelPtr 75 | } 76 | 77 | impl SelfRef { 78 | pub fn new(s: String, i: u32) -> Self { 79 | let mut this = Self { 80 | value: (s, i), 81 | ptr: RelPtr::null() 82 | }; 83 | 84 | this.ptr.set(&mut this.value.0).unwrap(); 85 | 86 | this 87 | } 88 | 89 | pub fn fst(&self) -> &str { 90 | unsafe { self.ptr.as_ref_unchecked() } 91 | } 92 | 93 | pub fn snd(&self) -> u32 { 94 | self.value.1 95 | } 96 | } 97 | 98 | let s = SelfRef::new("Hello World".into(), 10); 99 | 100 | assert_eq!(s.fst(), "Hello World"); 101 | assert_eq!(s.snd(), 10); 102 | 103 | let s = Box::new(s); // force a move, note: relative pointers even work on the heap 104 | 105 | assert_eq!(s.fst(), "Hello World"); 106 | assert_eq!(s.snd(), 10); 107 | # } 108 | ``` 109 | 110 | This example is contrived, and only useful as an example. 111 | In this example, we can see a few important parts to safe moveable self-referential types, 112 | lets walk through them. 113 | 114 | First, the definition of `SelfRef`, it contains a value and a relative pointer, the relative pointer that will point into the tuple inside of `SelfRef.value` to the `String`. There are no lifetimes involved because they would either make `SelfRef` immovable, or they could not be resolved correctly. 115 | 116 | We see a pattern inside of `SelfRef::new`, first create the object, and use the sentinel `RelPtr::null()` and immediately afterwards assigning it a value using `RelPtr::set` and unwraping the result. This unwrapping is get quick feedback on whether or not the pointer was set, if it wasn't set then we can increase the size of the offset and resolve that. 117 | 118 | Once the pointer is set, moving the struct is still safe because it is using a *relative* pointer, so it doesn't matter where it is, only it's offset from its pointee. 119 | In `SelfRef::fst` we use `RelPtr::as_ref_unchecked` because it is impossible to invalidate the pointer. It is impossible because we cannot 120 | set the relative pointer directly, and we cannot change the offsets of the fields of `SelfRef` after the relative pointer is set. 121 | */ 122 | 123 | #[cfg(feature = "no_std")] 124 | extern crate core as std; 125 | 126 | #[cfg(test)] 127 | mod tests; 128 | 129 | #[cfg(feature = "nightly")] 130 | mod nightly; 131 | 132 | mod traits; 133 | mod error; 134 | mod fmt; 135 | 136 | mod unreachable; 137 | 138 | #[cfg(feature = "nightly")] 139 | pub use self::nightly::*; 140 | pub use self::traits::*; 141 | pub use self::error::*; 142 | 143 | use core::mem::MaybeUninit; 144 | 145 | use crate::unreachable::UncheckedOptionExt as _; 146 | 147 | use std::marker::PhantomData; 148 | use std::ptr::NonNull; 149 | use core::num::*; 150 | 151 | macro_rules! impl_delta_zeroable { 152 | ($($type:ty),* $(,)?) => {$( 153 | unsafe impl Delta for $type { 154 | type Error = IntegerDeltaError; 155 | 156 | fn sub(a: *mut u8, b: *mut u8) -> Result { 157 | let del = match isize::checked_sub(a as usize as _, b as usize as _) { 158 | Some(del) => del, 159 | None => return Err(IntegerDeltaError(IntegerDeltaErrorImpl::Sub(a as usize, b as usize))) 160 | }; 161 | 162 | if std::mem::size_of::() < std::mem::size_of::() && ( 163 | (Self::min_value() as isize) > del || 164 | (Self::max_value() as isize) < del 165 | ) 166 | { 167 | Err(IntegerDeltaError(IntegerDeltaErrorImpl::Conversion(del))) 168 | } else { 169 | Ok(del as _) 170 | } 171 | } 172 | 173 | unsafe fn sub_unchecked(a: *mut u8, b: *mut u8) -> Self { 174 | isize::checked_sub(a as usize as _, b as usize as _).unchecked_unwrap(unreachable::OVERFLOW_SUB) as _ 175 | } 176 | 177 | unsafe fn add(self, a: *const u8) -> *mut u8 { 178 | <*const u8>::offset(a, self as isize) as *mut u8 179 | } 180 | } 181 | 182 | impl Nullable for $type { 183 | const NULL: Self = 0; 184 | } 185 | )*}; 186 | } 187 | 188 | impl_delta_zeroable! { i8, i16, i32, i64, i128, isize } 189 | 190 | macro_rules! impl_delta_nonzero { 191 | ($($type:ident $base:ident),* $(,)?) => {$( 192 | unsafe impl Delta for $type { 193 | type Error = IntegerDeltaError; 194 | 195 | fn sub(a: *mut u8, b: *mut u8) -> Result { 196 | let del = match isize::checked_sub(a as usize as _, b as usize as _) { 197 | None => return Err(IntegerDeltaError(IntegerDeltaErrorImpl::Sub(a as usize, b as usize))), 198 | Some(0) => return Err(IntegerDeltaError(IntegerDeltaErrorImpl::InvalidNonZero)), 199 | Some(del) => del, 200 | }; 201 | 202 | if std::mem::size_of::() < std::mem::size_of::() && ( 203 | ($base::min_value() as isize) > del || 204 | ($base::max_value() as isize) < del 205 | ) 206 | { 207 | Err(IntegerDeltaError(IntegerDeltaErrorImpl::Conversion(del))) 208 | } else { 209 | // 0 case was checked in match before hand, so this is guarenteed ot be non zero 210 | unsafe { Ok(Self::new_unchecked(del as _)) } 211 | } 212 | } 213 | 214 | unsafe fn sub_unchecked(a: *mut u8, b: *mut u8) -> Self { 215 | Self::new_unchecked(isize::checked_sub(a as usize as _, b as usize as _).unchecked_unwrap(unreachable::OVERFLOW_SUB) as _) 216 | } 217 | 218 | unsafe fn add(self, a: *const u8) -> *mut u8 { 219 | <*mut u8>::offset(a as _, self.get() as isize) as *mut u8 220 | } 221 | } 222 | )*}; 223 | } 224 | 225 | impl_delta_nonzero! { NonZeroI8 i8, NonZeroI16 i16, NonZeroI32 i32, NonZeroI64 i64, NonZeroI128 i128, NonZeroIsize isize } 226 | 227 | /// It is always safe to cast between a 228 | /// `Option>` and a `*mut T` 229 | /// because they are the exact same in memory 230 | #[inline(always)] 231 | fn nn_to_ptr(nn: Ptr) -> *mut T { 232 | unsafe { std::mem::transmute(nn) } 233 | } 234 | 235 | /** 236 | * This represents a relative pointers 237 | * 238 | * A relative pointer stores an offset, and uses its 239 | * that in combination with its current position in memory 240 | * to point to a value 241 | * 242 | * See crate documentation for more information 243 | * 244 | * # Safety 245 | * 246 | * When using `core::num::NonZero*`, it is UB to have the `RelPtr` point to itself, this could be achieved 247 | * with 248 | * 249 | * If you use `RelPtr::from(offset)`, then you must ensure that the relative pointer is set with the 250 | * given functions to avoid UB 251 | * 252 | * When using `RelPtr` with packed structs it is important to keep in mind that packed struct move fields 253 | * to align them to drop them. For example, the below example is UB 254 | * 255 | * ```ignore 256 | * #[repr(packed)] 257 | * struct Base(String, UnsafeThing); 258 | * 259 | * struct UnsafeThing(RelPtr); // points into Base 260 | * 261 | * impl Drop for UnsafeThing { 262 | * fn drop(&mut self) { 263 | * // ... accessing `RelPtr` here is UB 264 | * } 265 | * } 266 | * ``` 267 | * 268 | * This is because when `Base` drops, all of the fields are moved to align them. So the offset between the `String` in 269 | * unsafe thing and the `RelPtr` in `UnsafeThing` could be changed. This will result in UB if you try to access 270 | * String inside of `UnsafeThing` even if you enforce drop order! 271 | */ 272 | pub struct RelPtr(I, MaybeUninit, PhantomData<*mut T>); 273 | 274 | // Ergonomics and ptr like impls 275 | 276 | impl Copy for RelPtr {} 277 | impl Clone for RelPtr { 278 | fn clone(&self) -> Self { 279 | *self 280 | } 281 | } 282 | 283 | impl Eq for RelPtr {} 284 | impl PartialEq for RelPtr { 285 | fn eq(&self, other: &Self) -> bool { 286 | std::ptr::eq(self, other) 287 | } 288 | } 289 | 290 | /// Convert an offset into a `RelPtr` 291 | impl From for RelPtr { 292 | fn from(i: I) -> Self { 293 | Self(i, MaybeUninit::uninit(), PhantomData) 294 | } 295 | } 296 | 297 | // Core api 298 | 299 | impl RelPtr { 300 | /// A null relative pointer has an offset of 0, (points to itself) 301 | #[inline(always)] 302 | pub fn null() -> Self { 303 | Self(I::NULL, MaybeUninit::uninit(), PhantomData) 304 | } 305 | 306 | /// Check if relative pointer is null 307 | #[inline(always)] 308 | pub fn is_null(&self) -> bool { 309 | self.0 == I::NULL 310 | } 311 | } 312 | 313 | impl RelPtr { 314 | /** 315 | * Set the offset of a relative pointer, 316 | * if the offset cannot be calculated using the given 317 | * `Delta`, then `Err` will be returned, and there will be 318 | * **no** change to the offset 319 | */ 320 | #[inline] 321 | pub fn set(&mut self, value: &mut T) -> Result<(), I::Error> { 322 | self.0 = I::sub(value as *mut T as _, self as *mut Self as _)?; 323 | self.1 = MaybeUninit::new(T::data(value)); 324 | 325 | Ok(()) 326 | } 327 | 328 | /** 329 | * Set the offset of a relative pointer, 330 | * 331 | * # Safety 332 | * 333 | * if the offset is out of bounds for the given `Delta` 334 | * then it's value is UB 335 | * 336 | * if the given pointer is null, this is UB 337 | */ 338 | #[inline] 339 | pub unsafe fn set_unchecked(&mut self, value: *mut T) { 340 | self.0 = I::sub_unchecked(value as *mut T as _, self as *mut Self as _); 341 | self.1 = MaybeUninit::new(T::data(&*value)); 342 | } 343 | 344 | /** 345 | * Converts the relative pointer into a normal raw pointer 346 | * 347 | * # Safety 348 | * 349 | * You must ensure that the relative pointer was successfully set before 350 | * calling this function and that the value pointed to does not change it's 351 | * offset relative to `RelPtr` 352 | * 353 | * if relative pointer was never set successfully, this function is UB 354 | */ 355 | #[inline] 356 | unsafe fn as_raw_unchecked_impl(&self) -> *const T { 357 | nn_to_ptr(T::compose( 358 | NonNull::new(self.0.add(self as *const Self as *const u8)), 359 | self.1.assume_init() 360 | )) 361 | } 362 | 363 | /** 364 | * Converts the relative pointer into a normal raw pointer 365 | * 366 | * # Safety 367 | * 368 | * You must ensure that the relative pointer was successfully set before 369 | * calling this function and that the value pointed to does not change it's 370 | * offset relative to `RelPtr` 371 | * 372 | * if relative pointer was never set successfully, this function is UB 373 | */ 374 | #[inline] 375 | pub unsafe fn as_raw_unchecked(&mut self) -> *mut T { 376 | self.as_raw_unchecked_impl() as _ 377 | } 378 | 379 | /** 380 | * Converts the relative pointer into a NonNull pointer 381 | * 382 | * # Safety 383 | * 384 | * Same as `RelPtr::as_raw_unchecked` 385 | */ 386 | #[inline] 387 | pub unsafe fn as_non_null_unchecked(&mut self) -> NonNull { 388 | T::compose( 389 | NonNull::new(self.0.add(self as *mut Self as *mut u8)), 390 | self.1.assume_init() 391 | ).unchecked_unwrap("Tried to use an unset relative pointer, this is UB in release mode!") 392 | } 393 | 394 | /** 395 | * Gets a reference from the relative pointer 396 | * 397 | * # Safety 398 | * 399 | * Same as `RelPtr::as_raw_unchecked` 400 | */ 401 | #[inline] 402 | pub unsafe fn as_ref_unchecked(&self) -> &T { 403 | &*self.as_raw_unchecked_impl() 404 | } 405 | 406 | /** 407 | * Gets a mutable reference from the relative pointer 408 | * 409 | * # Safety 410 | * 411 | * Same as `RelPtr::as_raw_unchecked` 412 | */ 413 | #[inline] 414 | pub unsafe fn as_mut_unchecked(&mut self) -> &mut T { 415 | &mut *self.as_raw_unchecked() 416 | } 417 | } 418 | 419 | macro_rules! as_non_null_impl { 420 | ($self:ident) => { 421 | if $self.is_null() { 422 | None 423 | } else { 424 | T::compose( 425 | NonNull::new($self.0.add($self as *const Self as *const u8)), 426 | $self.1.assume_init() 427 | ) 428 | } 429 | }; 430 | } 431 | 432 | impl RelPtr { 433 | /** 434 | * Converts the relative pointer into a normal raw pointer 435 | * 436 | * Note: if `self.is_null()` then a null pointer will be returned 437 | * 438 | * # Safety 439 | * 440 | * You must ensure that if the relative pointer was successfully set then 441 | * the value pointed to does not change it's offset relative to `RelPtr` 442 | * 443 | * if the relative pointer was not successfully set `RelPtr::as_raw` returns null, 444 | * this function is safe for all types where `size_of::<*mut T>() == size_of::()`, 445 | * otherwise this function is UB 446 | */ 447 | #[inline] 448 | pub unsafe fn as_raw(&mut self) -> *mut T { 449 | nn_to_ptr(self.as_non_null()) 450 | } 451 | 452 | /** 453 | * Converts the relative pointer into a NonNull pointer 454 | * 455 | * # Safety 456 | * 457 | * You must ensure that if the relative pointer was successfully set then 458 | * the value pointed to does not change it's offset relative to `RelPtr` 459 | * 460 | * if the relative pointer was never successfully set `RelPtr::as_non_null` returns None, 461 | */ 462 | #[inline] 463 | pub unsafe fn as_non_null(&mut self) -> Ptr { 464 | as_non_null_impl!(self) 465 | } 466 | 467 | /** 468 | * Gets a reference from the relative pointer, 469 | * if the relative pointer is null, then `None` is 470 | * returned 471 | * 472 | * # Safety 473 | * 474 | * You are not allows to alias another mutable reference, 475 | * as per the aliasing rules of references 476 | * 477 | * Same as `RelPtr::as_non_null` 478 | */ 479 | #[inline] 480 | pub unsafe fn as_ref(&self) -> Option<&T> { 481 | Some(&*as_non_null_impl!(self)?.as_ptr()) 482 | } 483 | 484 | /** 485 | * Gets a reference from the relative pointer, 486 | * if the relative pointer is null, then `None` is 487 | * returned 488 | * 489 | * # Safety 490 | * 491 | * You are not allows to alias this mutable reference, 492 | * as per the aliasing rules of references 493 | * 494 | * Same as `RelPtr::as_non_null` 495 | */ 496 | #[inline] 497 | pub unsafe fn as_mut(&mut self) -> Option<&mut T> { 498 | Some(&mut *self.as_non_null()?.as_ptr()) 499 | } 500 | } 501 | --------------------------------------------------------------------------------