@@ -47,6 +47,55 @@ impl<T: ?Sized> *mut T {
47
47
self as _
48
48
}
49
49
50
+ /// Casts a pointer to its raw bits.
51
+ ///
52
+ /// This is equivalent to `as usize`, but is more specific to enhance readability.
53
+ /// The inverse method is [`from_bits`](#method.from_bits-1).
54
+ ///
55
+ /// In particular, `*p as usize` and `p as usize` will both compile for
56
+ /// pointers to numeric types but do very different things, so using this
57
+ /// helps emphasize that reading the bits was intentional.
58
+ ///
59
+ /// # Examples
60
+ ///
61
+ /// ```
62
+ /// #![feature(ptr_to_from_bits)]
63
+ /// let mut array = [13, 42];
64
+ /// let mut it = array.iter_mut();
65
+ /// let p0: *mut i32 = it.next().unwrap();
66
+ /// assert_eq!(<*mut _>::from_bits(p0.to_bits()), p0);
67
+ /// let p1: *mut i32 = it.next().unwrap();
68
+ /// assert_eq!(p1.to_bits() - p0.to_bits(), 4);
69
+ /// ```
70
+ #[ unstable( feature = "ptr_to_from_bits" , issue = "91126" ) ]
71
+ pub fn to_bits ( self ) -> usize
72
+ where
73
+ T : Sized ,
74
+ {
75
+ self as usize
76
+ }
77
+
78
+ /// Creates a pointer from its raw bits.
79
+ ///
80
+ /// This is equivalent to `as *mut T`, but is more specific to enhance readability.
81
+ /// The inverse method is [`to_bits`](#method.to_bits-1).
82
+ ///
83
+ /// # Examples
84
+ ///
85
+ /// ```
86
+ /// #![feature(ptr_to_from_bits)]
87
+ /// use std::ptr::NonNull;
88
+ /// let dangling: *mut u8 = NonNull::dangling().as_ptr();
89
+ /// assert_eq!(<*mut u8>::from_bits(1), dangling);
90
+ /// ```
91
+ #[ unstable( feature = "ptr_to_from_bits" , issue = "91126" ) ]
92
+ pub fn from_bits ( bits : usize ) -> Self
93
+ where
94
+ T : Sized ,
95
+ {
96
+ bits as Self
97
+ }
98
+
50
99
/// Decompose a (possibly wide) pointer into its address and metadata components.
51
100
///
52
101
/// The pointer can be later reconstructed with [`from_raw_parts_mut`].
0 commit comments