constptr 0.3.1

NonNull without mutability
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#![doc = include_str!("../README.md")]
#![warn(clippy::cargo_common_metadata)]
#![warn(clippy::doc_markdown)]
#![warn(clippy::missing_panics_doc)]
#![warn(clippy::must_use_candidate)]
#![warn(clippy::semicolon_if_nothing_returned)]
#![warn(missing_docs)]
#![warn(rustdoc::missing_crate_level_docs)]
#![cfg_attr(not(feature = "std"), no_std)]

use core::cmp::Ordering;
use core::ptr::*;
use core::num::NonZeroUsize;

/// A pointer that references immutable data and is never `Null`.
#[repr(transparent)]
pub struct ConstPtr<T: ?Sized>(NonNull<T>);

/// `ConstPtr` pointers can be `Send` because they are constant.
unsafe impl<T: ?Sized + Send> Send for ConstPtr<T> {}

/// `ConstPtr` pointers can be `Sync` because they are constant.
unsafe impl<T: ?Sized + Send + Sync> Sync for ConstPtr<T> {}

impl<T: ?Sized> ConstPtr<T> {
    /// Creates a new `ConstPtr`. This is a const fn.
    ///
    /// # Safety
    ///
    /// `ptr` must be non-null.
    ///
    /// # Examples
    ///
    /// ```
    /// use constptr::ConstPtr;
    ///
    /// static x: u32 = 0u32;
    /// let ptr = unsafe { ConstPtr::new_unchecked(&x) };
    /// ```
    #[inline]
    pub const unsafe fn new_unchecked(ptr: *const T) -> Self {
        debug_assert!(!ptr.is_null(), "passed null pointer to ConstPtr::new_unchecked()");
        // SAFETY: the caller must guarantee that `ptr` is non-null.
        ConstPtr(core::mem::transmute::<*const T, NonNull<T>>(ptr))
    }

    /// Creates a new `ConstPtr` from a reference which makes it safe. This is a const fn.
    /// # Examples
    ///
    /// ```
    /// use constptr::ConstPtr;
    ///
    /// static x: u32 = 0u32;
    /// let ptr = ConstPtr::from(&x);
    /// ```
    // use this until const From becomes stable
    #[inline]
    pub const fn from(reference: &T) -> Self {
        // SAFETY: references are always valid pointers
        unsafe { ConstPtr::new_unchecked(reference) }
    }

    /// Creates a new `ConstPtr` if `ptr` is non-null.
    ///
    /// # Examples
    ///
    /// ```
    /// use constptr::ConstPtr;
    ///
    /// let x = 0u32;
    /// let ptr = ConstPtr::new(&x).expect("ptr is null!");
    ///
    /// if let Some(ptr) = ConstPtr::new(std::ptr::null::<u32>()) {
    ///     unreachable!();
    /// }
    /// ```
    // TODO: const fn once ptr.is_null() in const context is stable
    #[inline]
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    pub fn new(ptr: *const T) -> Option<Self> {
        if !ptr.is_null() {
            // SAFETY: The pointer is already checked and is not null
            Some(unsafe { ConstPtr(core::mem::transmute::<*const T, NonNull<T>>(ptr)) })
        } else {
            None
        }
    }

    // /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a
    // /// `ConstPtr` pointer is returned, as opposed to a raw `*const` pointer.
    // ///
    // /// See the documentation of [`std::ptr::from_raw_parts`] for more details.
    // ///
    // /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts
    // TODO: when stable #[unstable(feature = "ptr_metadata", issue = "81513")]
    // #[inline]
    // pub const fn from_raw_parts(
    //     data_address: ConstPtr<()>,
    //     metadata: <T as super::Pointee>::Metadata,
    // ) -> ConstPtr<T> {
    //     // SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_address` is.
    //     unsafe {
    //         ConstPtr::new_unchecked(super::from_raw_parts_mut(data_address.as_ptr(), metadata))
    //     }
    // }

    // /// Decompose a (possibly wide) pointer into its address and metadata components.
    // ///
    // /// The pointer can be later reconstructed with [`ConstPtr::from_raw_parts`].
    // TODO: when stable #[unstable(feature = "ptr_metadata", issue = "81513")]
    // #[must_use = "this returns the result of the operation, \
    //               without modifying the original"]
    // #[inline]
    // pub const fn to_raw_parts(self) -> (ConstPtr<()>, <T as super::Pointee>::Metadata) {
    //     (self.cast(), super::metadata(self.as_ptr()))
    // }

    /// Gets the "address" portion of the pointer.
    ///
    /// For more details see the equivalent method on a raw pointer `pointer::addr`.
    #[must_use]
    #[inline]
    pub fn addr(self) -> NonZeroUsize
    {
        self.0.addr()
    }

    // /// Creates a new pointer with the given address.
    // ///
    // /// For more details see the equivalent method on a raw pointer, [`pointer::with_addr`].
    // ///
    // /// This API and its claimed semantics are part of the Strict Provenance experiment,
    // /// see the [`ptr` module documentation][crate::ptr].
    // #[must_use]
    // #[inline]
    // TODO: when stable #[unstable(feature = "strict_provenance", issue = "95228")]
    // pub fn with_addr(self, addr: NonZeroUsize) -> Self
    // where
    //     T: Sized,
    // {
    //     // SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
    //     unsafe { ConstPtr::new_unchecked(self.pointer.with_addr(addr.get()) as *const _) }
    // }

    // /// Creates a new pointer by mapping `self`'s address to a new one.
    // ///
    // /// For more details see the equivalent method on a raw pointer, [`pointer::map_addr`].
    // ///
    // /// This API and its claimed semantics are part of the Strict Provenance experiment,
    // /// see the [`ptr` module documentation][crate::ptr].
    // #[must_use]
    // #[inline]
    // TODO: when stable #[unstable(feature = "strict_provenance", issue = "95228")]
    // pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self
    // where
    //     T: Sized,
    // {
    //     self.with_addr(f(self.addr()))
    // }

    /// Acquires the underlying `*const` pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use constptr::ConstPtr;
    ///
    /// let mut x = 0u32;
    /// let ptr = ConstPtr::new(&mut x).expect("ptr is null!");
    ///
    /// let x_value = unsafe { *ptr.as_ptr() };
    /// assert_eq!(x_value, 0);
    /// ```
    #[must_use]
    #[inline(always)]
    pub const fn as_ptr(self) -> *const T {
        self.0.as_ptr()
    }

    /// Returns a shared reference to the value.
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that all of the following is true:
    ///
    /// * The pointer must be properly aligned.
    ///
    /// * It must be "dereferenceable".
    ///
    /// * The pointer must point to an initialized instance of `T`.
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, while this reference exists, the memory the pointer points to must
    ///   not get mutated (except inside `UnsafeCell`).
    ///
    /// This applies even if the result of this method is unused!
    /// (The part about being initialized is not yet fully decided, but until
    /// it is, the only safe approach is to ensure that they are indeed initialized.)
    ///
    /// # Examples
    ///
    /// ```
    /// use constptr::ConstPtr;
    ///
    /// let x = 0u32;
    /// let ptr = ConstPtr::new(&x).expect("ptr is null!");
    ///
    /// let ref_x = unsafe { ptr.as_ref() };
    /// println!("{ref_x}");
    /// ```
    #[must_use]
    #[inline(always)]
    pub const unsafe fn as_ref<'a>(&self) -> &'a T {
        // SAFETY: the caller must guarantee that `self` meets all the
        // requirements for a reference.
        unsafe { &*self.0.as_ptr() }
    }

    /// Casts to a pointer of another type.
    ///
    /// # Examples
    ///
    /// ```
    /// use constptr::ConstPtr;
    ///
    /// let  x = 0u32;
    /// let ptr = ConstPtr::new(&x).expect("null pointer");
    ///
    /// let casted_ptr = ptr.cast::<i8>();
    /// let raw_ptr: *const i8 = casted_ptr.as_ptr();
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    #[inline]
    pub const fn cast<U>(self) -> ConstPtr<U> {
        // SAFETY: `self` is a `ConstPtr` pointer which is necessarily non-null
        unsafe { ConstPtr::new_unchecked(self.as_ptr() as *const U) }
    }
}

// TODO: the whole slices API isn't stable yet
impl<T> ConstPtr<[T]> {
    // /// Creates a non-null raw slice from a thin pointer and a length.
    // ///
    // /// The `len` argument is the number of **elements**, not the number of bytes.
    // ///
    // /// This function is safe, but dereferencing the return value is unsafe.
    // /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
    // ///
    // /// # Examples
    // ///
    // /// ```rust
    // /// #![feature(nonnull_slice_from_raw_parts)]
    // ///
    // /// use constptr::ConstPtr;
    // ///
    // /// // create a slice pointer when starting out with a pointer to the first element
    // /// let  x = [5, 6, 7];
    // /// let nonnull_pointer = ConstPtr::new(x.as_mut_ptr()).unwrap();
    // /// let slice = ConstPtr::slice_from_raw_parts(nonnull_pointer, 3);
    // /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
    // /// ```
    // ///
    // /// (Note that this example artificially demonstrates a use of this method,
    // /// but `let slice = ConstPtr::from(&x[..]);` would be a better way to write code like this.)
    // TODO: when stable  #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
    // #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
    // #[must_use]
    // #[inline]
    // pub const fn slice_from_raw_parts(data: ConstPtr<T>, len: usize) -> Self {
    //     // SAFETY: `data` is a `ConstPtr` pointer which is necessarily non-null
    //     unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
    // }
    //
    // /// Returns the length of a non-null raw slice.
    // ///
    // /// The returned value is the number of **elements**, not the number of bytes.
    // ///
    // /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
    // /// because the pointer does not have a valid address.
    // ///
    // /// # Examples
    // ///
    // /// ```rust
    // /// #![feature(nonnull_slice_from_raw_parts)]
    // /// use constptr::ConstPtr;
    // ///
    // /// let slice: ConstPtr<[i8]> = ConstPtr::slice_from_raw_parts(ConstPtr::dangling(), 3);
    // /// assert_eq!(slice.len(), 3);
    // /// ```
    // TODO: when stable #[stable(feature = "slice_ptr_len_nonnull", since = "1.63.0")]
    // #[rustc_const_stable(feature = "const_slice_ptr_len_nonnull", since = "1.63.0")]
    // #[rustc_allow_const_fn_unstable(const_slice_ptr_len)]
    // #[must_use]
    // #[inline]
    // pub const fn len(self) -> usize {
    //     self.as_ptr().len()
    // }
    //
    // /// Returns a non-null pointer to the slice's buffer.
    // ///
    // /// # Examples
    // ///
    // /// ```rust
    // /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
    // /// use constptr::ConstPtr;
    // ///
    // /// let slice: ConstPtr<[i8]> = ConstPtr::slice_from_raw_parts(ConstPtr::dangling(), 3);
    // /// assert_eq!(slice.as_non_null_ptr(), ConstPtr::<i8>::dangling());
    // /// ```
    // #[inline]
    // #[must_use]
    // TODO: when stable #[unstable(feature = "slice_ptr_get", issue = "74265")]
    // #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
    // pub const fn as_non_null_ptr(self) -> ConstPtr<T> {
    //     // SAFETY: We know `self` is non-null.
    //     unsafe { ConstPtr::new_unchecked(self.as_ptr().as_mut_ptr()) }
    // }

    // /// Returns a raw pointer to an element or subslice, without doing bounds
    // /// checking.
    // ///
    // /// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
    // /// is *[undefined behavior]* even if the resulting pointer is not used.
    // ///
    // /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    // ///
    // /// # Examples
    // ///
    // /// ```
    // /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
    // /// use constptr::ConstPtr;
    // ///
    // /// let x = &mut [1, 2, 4];
    // /// let x = ConstPtr::slice_from_raw_parts(ConstPtr::new(x.as_mut_ptr()).unwrap(), x.len());
    // ///
    // /// unsafe {
    // ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
    // /// }
    // /// ```
    // TODO: when stable #[unstable(feature = "slice_ptr_get", issue = "74265")]
    // #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
    // #[inline]
    // pub const unsafe fn get_unchecked_mut<I>(self, index: I) -> ConstPtr<I::Output>
    // where
    //     I: ~const SliceIndex<[T]>,
    // {
    //     // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
    //     // As a consequence, the resulting pointer cannot be null.
    //     unsafe { ConstPtr::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
    // }
}

// TODO: when stable #[stable(feature = "nonnull", since = "1.25.0")]
// #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
// impl<T: ?Sized> const Clone for ConstPtr<T> {
//     #[inline(always)]
//     fn clone(&self) -> Self {
//         *self
//     }
// }

// TODO: when stable #[unstable(feature = "coerce_unsized", issue = "27732")]
// impl<T: ?Sized, U: ?Sized> CoerceUnsized<ConstPtr<U>> for ConstPtr<T> where T: Unsize<U> {}

// TODO: when stable  #[unstable(feature = "dispatch_from_dyn", issue = "none")]
// impl<T: ?Sized, U: ?Sized> DispatchFromDyn<ConstPtr<U>> for ConstPtr<T> where T: Unsize<U> {}

impl<T: ?Sized> Copy for ConstPtr<T> {}

impl<T: ?Sized> Clone for ConstPtr<T> {
    #[inline(always)]
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized> core::fmt::Pointer for ConstPtr<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Pointer::fmt(&self.as_ptr(), f)
    }
}

impl<T: ?Sized> core::fmt::Debug for ConstPtr<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Pointer::fmt(&self.as_ptr(), f)
    }
}

impl<T: ?Sized> Eq for ConstPtr<T> {}

impl<T: ?Sized> PartialEq for ConstPtr<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        addr_eq(self.as_ptr(), other.as_ptr())
    }
}

impl<T: ?Sized> Ord for ConstPtr<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.addr().cmp(&other.addr())
    }
}

impl<T: ?Sized> PartialOrd for ConstPtr<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[cfg(feature = "std")]
impl<T: ?Sized> std::hash::Hash for ConstPtr<T> {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_ptr().hash(state);
    }
}

// TODO: when stable #[unstable(feature = "ptr_internals", issue = "none")]
// #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
// impl<T: ?Sized> const From<Unique<T>> for ConstPtr<T> {
//     #[inline]
//     fn from(unique: Unique<T>) -> Self {
//         // SAFETY: A Unique pointer cannot be null, so the conditions for
//         // new_unchecked() are respected.
//         unsafe { ConstPtr::new_unchecked(unique.as_ptr()) }
//     }
// }

// TODO: impl<T: ?Sized> const From<&mut T> for ConstPtr<T> {
impl<T: ?Sized> From<&mut T> for ConstPtr<T> {
    /// Converts a `&mut T` to a `ConstPtr<T>`.
    ///
    /// This conversion is safe and infallible since references cannot be null.
    ///
    /// # Safety
    ///
    /// Creating a `ConstPtr` from a mutable reference is safe. However, you must ensure that
    /// the `ConstPtr` is not used while the mutable reference is still in use. The other
    /// safety requirements for `ConstPtr` still apply. Eg the object must still be valid at
    /// the time of dereferencing, even after the mutable reference is dropped.
    #[inline]
    fn from(reference: &mut T) -> Self {
        ConstPtr::from(reference)
    }
}

// TODO: impl<T: ?Sized> const From<&T> for ConstPtr<T> {
impl<T: ?Sized> From<&T> for ConstPtr<T> {
    /// Converts a `&T` to a `ConstPtr<T>`.
    ///
    /// This conversion is safe and infallible since references cannot be null.
    #[inline]
    fn from(reference: &T) -> Self {
        ConstPtr::from(reference)
    }
}