Repository navigation
Expand file tree
/
Copy pathptr.rs
More file actions
87 lines (72 loc) · 2.15 KB
/
Copy pathptr.rs
File metadata and controls
87 lines (72 loc) · 2.15 KB
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
//! Polyfill for nightly Rust APIs.
#![allow(dead_code)]
#[inline]
pub(crate) const fn without_provenance_mut<T>(addr: usize) -> *mut T {
// SAFETY: Every valid `usize` is also a valid pointer.
unsafe { core::mem::transmute(addr) }
}
#[inline]
pub(crate) fn with_exposed_provenance_mut<T>(addr: usize) -> *mut T {
addr as *mut T
}
/// Replacement for `.addr()` for the relocation code which can't call trait
/// methods because they might not be relocated yet.
#[cfg(feature = "experimental-relocate")]
#[inline]
pub(crate) fn addr<T>(addr: *const T) -> usize {
// SAFETY: Every pointer is also a valid `usize`.
unsafe { core::mem::transmute(addr) }
}
pub(crate) trait Polyfill<T> {
fn addr(self) -> usize;
fn expose_provenance(self) -> usize;
fn with_addr(self, addr: usize) -> *mut T;
fn map_addr(self, f: impl FnOnce(usize) -> usize) -> *mut T;
fn cast_mut(self) -> *mut T;
}
impl<T> Polyfill<T> for *mut T {
#[inline]
fn addr(self) -> usize {
// SAFETY: Every pointer is also a valid `usize`.
unsafe { core::mem::transmute(self) }
}
#[inline]
fn expose_provenance(self) -> usize {
self as usize
}
#[inline]
fn with_addr(self, addr: usize) -> *mut T {
self.wrapping_byte_offset((addr as isize).wrapping_sub(self.addr() as isize))
}
#[inline]
fn map_addr(self, f: impl FnOnce(usize) -> usize) -> *mut T {
self.with_addr(f(self.addr()))
}
#[inline]
fn cast_mut(self) -> *mut T {
self
}
}
impl<T> Polyfill<T> for *const T {
#[inline]
fn addr(self) -> usize {
// SAFETY: Every pointer is also a valid `usize`.
unsafe { core::mem::transmute(self) }
}
#[inline]
fn expose_provenance(self) -> usize {
self as usize
}
#[inline]
fn with_addr(self, addr: usize) -> *mut T {
self.wrapping_byte_offset((addr as isize).wrapping_sub(self.addr() as isize)) as *mut T
}
#[inline]
fn map_addr(self, f: impl FnOnce(usize) -> usize) -> *mut T {
self.with_addr(f(self.addr())).cast_mut()
}
#[inline]
fn cast_mut(self) -> *mut T {
self as *mut T
}
}