]> git.proxmox.com Git - rustc.git/blame - library/core/src/ptr/non_null.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / library / core / src / ptr / non_null.rs
CommitLineData
3dfed10e
XL
1use crate::cmp::Ordering;
2use crate::convert::From;
3use crate::fmt;
4use crate::hash;
5use crate::marker::Unsize;
6use crate::mem::{self, MaybeUninit};
7use crate::ops::{CoerceUnsized, DispatchFromDyn};
8use crate::ptr::Unique;
9use crate::slice::{self, SliceIndex};
10
11/// `*mut T` but non-zero and covariant.
12///
13/// This is often the correct thing to use when building data structures using
14/// raw pointers, but is ultimately more dangerous to use because of its additional
15/// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
16///
17/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
18/// is never dereferenced. This is so that enums may use this forbidden value
19/// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
20/// However the pointer may still dangle if it isn't dereferenced.
21///
22/// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
23/// for your use case, you should include some [`PhantomData`] in your type to
24/// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
25/// Usually this won't be necessary; covariance is correct for most safe abstractions,
26/// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
27/// provide a public API that follows the normal shared XOR mutable rules of Rust.
28///
29/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
30/// not change the fact that mutating through a (pointer derived from a) shared
31/// reference is undefined behavior unless the mutation happens inside an
32/// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
33/// reference. When using this `From` instance without an `UnsafeCell<T>`,
34/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
35/// is never used for mutation.
36///
1b1a35ee
XL
37/// [`PhantomData`]: crate::marker::PhantomData
38/// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
3dfed10e
XL
39#[stable(feature = "nonnull", since = "1.25.0")]
40#[repr(transparent)]
41#[rustc_layout_scalar_valid_range_start(1)]
42#[rustc_nonnull_optimization_guaranteed]
43pub struct NonNull<T: ?Sized> {
44 pointer: *const T,
45}
46
47/// `NonNull` pointers are not `Send` because the data they reference may be aliased.
48// N.B., this impl is unnecessary, but should provide better error messages.
49#[stable(feature = "nonnull", since = "1.25.0")]
50impl<T: ?Sized> !Send for NonNull<T> {}
51
52/// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
53// N.B., this impl is unnecessary, but should provide better error messages.
54#[stable(feature = "nonnull", since = "1.25.0")]
55impl<T: ?Sized> !Sync for NonNull<T> {}
56
57impl<T: Sized> NonNull<T> {
58 /// Creates a new `NonNull` that is dangling, but well-aligned.
59 ///
60 /// This is useful for initializing types which lazily allocate, like
61 /// `Vec::new` does.
62 ///
63 /// Note that the pointer value may potentially represent a valid pointer to
64 /// a `T`, which means this must not be used as a "not yet initialized"
65 /// sentinel value. Types that lazily allocate must track initialization by
66 /// some other means.
67 #[stable(feature = "nonnull", since = "1.25.0")]
68 #[rustc_const_stable(feature = "const_nonnull_dangling", since = "1.32.0")]
69 #[inline]
70 pub const fn dangling() -> Self {
71 // SAFETY: mem::align_of() returns a non-zero usize which is then casted
72 // to a *mut T. Therefore, `ptr` is not null and the conditions for
73 // calling new_unchecked() are respected.
74 unsafe {
75 let ptr = mem::align_of::<T>() as *mut T;
76 NonNull::new_unchecked(ptr)
77 }
78 }
79
80 /// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
81 /// that the value has to be initialized.
82 ///
83 /// For the mutable counterpart see [`as_uninit_mut`].
84 ///
1b1a35ee
XL
85 /// [`as_ref`]: NonNull::as_ref
86 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
3dfed10e
XL
87 ///
88 /// # Safety
89 ///
90 /// When calling this method, you have to ensure that all of the following is true:
91 ///
92 /// * The pointer must be properly aligned.
93 ///
94 /// * It must be "dereferencable" in the sense defined in [the module documentation].
95 ///
96 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
97 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
98 /// In particular, for the duration of this lifetime, the memory the pointer points to must
99 /// not get mutated (except inside `UnsafeCell`).
100 ///
101 /// This applies even if the result of this method is unused!
102 ///
103 /// [the module documentation]: crate::ptr#safety
104 #[inline]
105 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
106 pub unsafe fn as_uninit_ref(&self) -> &MaybeUninit<T> {
107 // SAFETY: the caller must guarantee that `self` meets all the
108 // requirements for a reference.
109 unsafe { &*self.cast().as_ptr() }
110 }
111
112 /// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
113 /// that the value has to be initialized.
114 ///
115 /// For the shared counterpart see [`as_uninit_ref`].
116 ///
1b1a35ee
XL
117 /// [`as_mut`]: NonNull::as_mut
118 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
3dfed10e
XL
119 ///
120 /// # Safety
121 ///
122 /// When calling this method, you have to ensure that all of the following is true:
123 ///
124 /// * The pointer must be properly aligned.
125 ///
126 /// * It must be "dereferencable" in the sense defined in [the module documentation].
127 ///
128 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
129 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
130 /// In particular, for the duration of this lifetime, the memory the pointer points to must
131 /// not get accessed (read or written) through any other pointer.
132 ///
133 /// This applies even if the result of this method is unused!
134 ///
135 /// [the module documentation]: crate::ptr#safety
136 #[inline]
137 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
138 pub unsafe fn as_uninit_mut(&mut self) -> &mut MaybeUninit<T> {
139 // SAFETY: the caller must guarantee that `self` meets all the
140 // requirements for a reference.
141 unsafe { &mut *self.cast().as_ptr() }
142 }
143}
144
145impl<T: ?Sized> NonNull<T> {
146 /// Creates a new `NonNull`.
147 ///
148 /// # Safety
149 ///
150 /// `ptr` must be non-null.
151 #[stable(feature = "nonnull", since = "1.25.0")]
152 #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.32.0")]
153 #[inline]
154 pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
155 // SAFETY: the caller must guarantee that `ptr` is non-null.
156 unsafe { NonNull { pointer: ptr as _ } }
157 }
158
159 /// Creates a new `NonNull` if `ptr` is non-null.
160 #[stable(feature = "nonnull", since = "1.25.0")]
161 #[inline]
162 pub fn new(ptr: *mut T) -> Option<Self> {
163 if !ptr.is_null() {
164 // SAFETY: The pointer is already checked and is not null
165 Some(unsafe { Self::new_unchecked(ptr) })
166 } else {
167 None
168 }
169 }
170
171 /// Acquires the underlying `*mut` pointer.
172 #[stable(feature = "nonnull", since = "1.25.0")]
173 #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")]
174 #[inline]
175 pub const fn as_ptr(self) -> *mut T {
176 self.pointer as *mut T
177 }
178
179 /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
180 /// must be used instead.
181 ///
182 /// For the mutable counterpart see [`as_mut`].
183 ///
1b1a35ee
XL
184 /// [`as_uninit_ref`]: NonNull::as_uninit_ref
185 /// [`as_mut`]: NonNull::as_mut
3dfed10e
XL
186 ///
187 /// # Safety
188 ///
189 /// When calling this method, you have to ensure that all of the following is true:
190 ///
191 /// * The pointer must be properly aligned.
192 ///
193 /// * It must be "dereferencable" in the sense defined in [the module documentation].
194 ///
195 /// * The pointer must point to an initialized instance of `T`.
196 ///
197 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
198 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
199 /// In particular, for the duration of this lifetime, the memory the pointer points to must
200 /// not get mutated (except inside `UnsafeCell`).
201 ///
202 /// This applies even if the result of this method is unused!
203 /// (The part about being initialized is not yet fully decided, but until
204 /// it is, the only safe approach is to ensure that they are indeed initialized.)
205 ///
206 /// [the module documentation]: crate::ptr#safety
207 #[stable(feature = "nonnull", since = "1.25.0")]
208 #[inline]
209 pub unsafe fn as_ref(&self) -> &T {
210 // SAFETY: the caller must guarantee that `self` meets all the
211 // requirements for a reference.
212 unsafe { &*self.as_ptr() }
213 }
214
215 /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
216 /// must be used instead.
217 ///
218 /// For the shared counterpart see [`as_ref`].
219 ///
1b1a35ee
XL
220 /// [`as_uninit_mut`]: NonNull::as_uninit_mut
221 /// [`as_ref`]: NonNull::as_ref
3dfed10e
XL
222 ///
223 /// # Safety
224 ///
225 /// When calling this method, you have to ensure that all of the following is true:
226 ///
227 /// * The pointer must be properly aligned.
228 ///
229 /// * It must be "dereferencable" in the sense defined in [the module documentation].
230 ///
231 /// * The pointer must point to an initialized instance of `T`.
232 ///
233 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
234 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
235 /// In particular, for the duration of this lifetime, the memory the pointer points to must
236 /// not get accessed (read or written) through any other pointer.
237 ///
238 /// This applies even if the result of this method is unused!
239 /// (The part about being initialized is not yet fully decided, but until
240 /// it is, the only safe approach is to ensure that they are indeed initialized.)
241 ///
242 /// [the module documentation]: crate::ptr#safety
243 #[stable(feature = "nonnull", since = "1.25.0")]
244 #[inline]
245 pub unsafe fn as_mut(&mut self) -> &mut T {
246 // SAFETY: the caller must guarantee that `self` meets all the
247 // requirements for a mutable reference.
248 unsafe { &mut *self.as_ptr() }
249 }
250
251 /// Casts to a pointer of another type.
252 #[stable(feature = "nonnull_cast", since = "1.27.0")]
253 #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.32.0")]
254 #[inline]
255 pub const fn cast<U>(self) -> NonNull<U> {
256 // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
257 unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) }
258 }
259}
260
261impl<T> NonNull<[T]> {
262 /// Creates a non-null raw slice from a thin pointer and a length.
263 ///
264 /// The `len` argument is the number of **elements**, not the number of bytes.
265 ///
266 /// This function is safe, but dereferencing the return value is unsafe.
267 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
268 ///
3dfed10e
XL
269 /// # Examples
270 ///
271 /// ```rust
272 /// #![feature(nonnull_slice_from_raw_parts)]
273 ///
274 /// use std::ptr::NonNull;
275 ///
276 /// // create a slice pointer when starting out with a pointer to the first element
277 /// let mut x = [5, 6, 7];
278 /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
279 /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
280 /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
281 /// ```
282 ///
283 /// (Note that this example artificially demonstrates a use of this method,
284 /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
285 #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
286 #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
287 #[inline]
288 pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
289 // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
290 unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
291 }
292
293 /// Returns the length of a non-null raw slice.
294 ///
295 /// The returned value is the number of **elements**, not the number of bytes.
296 ///
297 /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
298 /// because the pointer does not have a valid address.
299 ///
300 /// # Examples
301 ///
302 /// ```rust
303 /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
304 /// use std::ptr::NonNull;
305 ///
306 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
307 /// assert_eq!(slice.len(), 3);
308 /// ```
309 #[unstable(feature = "slice_ptr_len", issue = "71146")]
310 #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
311 #[inline]
312 pub const fn len(self) -> usize {
313 self.as_ptr().len()
314 }
315
316 /// Returns a non-null pointer to the slice's buffer.
317 ///
318 /// # Examples
319 ///
320 /// ```rust
321 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
322 /// use std::ptr::NonNull;
323 ///
324 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
325 /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
326 /// ```
327 #[inline]
328 #[unstable(feature = "slice_ptr_get", issue = "74265")]
329 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
330 pub const fn as_non_null_ptr(self) -> NonNull<T> {
331 // SAFETY: We know `self` is non-null.
332 unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
333 }
334
335 /// Returns a raw pointer to the slice's buffer.
336 ///
337 /// # Examples
338 ///
339 /// ```rust
340 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
341 /// use std::ptr::NonNull;
342 ///
343 /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
344 /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
345 /// ```
346 #[inline]
347 #[unstable(feature = "slice_ptr_get", issue = "74265")]
348 #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
349 pub const fn as_mut_ptr(self) -> *mut T {
350 self.as_non_null_ptr().as_ptr()
351 }
352
353 /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
354 /// [`as_ref`], this does not require that the value has to be initialized.
355 ///
356 /// For the mutable counterpart see [`as_uninit_slice_mut`].
357 ///
1b1a35ee
XL
358 /// [`as_ref`]: NonNull::as_ref
359 /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
3dfed10e
XL
360 ///
361 /// # Safety
362 ///
363 /// When calling this method, you have to ensure that all of the following is true:
364 ///
365 /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
366 /// and it must be properly aligned. This means in particular:
367 ///
368 /// * The entire memory range of this slice must be contained within a single allocated object!
369 /// Slices can never span across multiple allocated objects.
370 ///
371 /// * The pointer must be aligned even for zero-length slices. One
372 /// reason for this is that enum layout optimizations may rely on references
373 /// (including slices of any length) being aligned and non-null to distinguish
374 /// them from other data. You can obtain a pointer that is usable as `data`
375 /// for zero-length slices using [`NonNull::dangling()`].
376 ///
377 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
378 /// See the safety documentation of [`pointer::offset`].
379 ///
380 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
381 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
382 /// In particular, for the duration of this lifetime, the memory the pointer points to must
383 /// not get mutated (except inside `UnsafeCell`).
384 ///
385 /// This applies even if the result of this method is unused!
386 ///
1b1a35ee 387 /// See also [`slice::from_raw_parts`].
3dfed10e
XL
388 ///
389 /// [valid]: crate::ptr#safety
3dfed10e
XL
390 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
391 #[inline]
392 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
393 pub unsafe fn as_uninit_slice(&self) -> &[MaybeUninit<T>] {
394 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
395 unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
396 }
397
398 /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
399 /// [`as_mut`], this does not require that the value has to be initialized.
400 ///
401 /// For the shared counterpart see [`as_uninit_slice`].
402 ///
1b1a35ee
XL
403 /// [`as_mut`]: NonNull::as_mut
404 /// [`as_uninit_slice`]: NonNull::as_uninit_slice
3dfed10e
XL
405 ///
406 /// # Safety
407 ///
408 /// When calling this method, you have to ensure that all of the following is true:
409 ///
410 /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
411 /// many bytes, and it must be properly aligned. This means in particular:
412 ///
413 /// * The entire memory range of this slice must be contained within a single allocated object!
414 /// Slices can never span across multiple allocated objects.
415 ///
416 /// * The pointer must be aligned even for zero-length slices. One
417 /// reason for this is that enum layout optimizations may rely on references
418 /// (including slices of any length) being aligned and non-null to distinguish
419 /// them from other data. You can obtain a pointer that is usable as `data`
420 /// for zero-length slices using [`NonNull::dangling()`].
421 ///
422 /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
423 /// See the safety documentation of [`pointer::offset`].
424 ///
425 /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
426 /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
427 /// In particular, for the duration of this lifetime, the memory the pointer points to must
428 /// not get accessed (read or written) through any other pointer.
429 ///
430 /// This applies even if the result of this method is unused!
431 ///
1b1a35ee 432 /// See also [`slice::from_raw_parts_mut`].
3dfed10e
XL
433 ///
434 /// [valid]: crate::ptr#safety
3dfed10e
XL
435 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
436 ///
437 /// # Examples
438 ///
439 /// ```rust
440 /// #![feature(allocator_api, ptr_as_uninit)]
441 ///
442 /// use std::alloc::{AllocRef, Layout, Global};
443 /// use std::mem::MaybeUninit;
444 /// use std::ptr::NonNull;
445 ///
446 /// let memory: NonNull<[u8]> = Global.alloc(Layout::new::<[u8; 32]>())?;
447 /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
448 /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
449 /// # #[allow(unused_variables)]
450 /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
1b1a35ee 451 /// # Ok::<_, std::alloc::AllocError>(())
3dfed10e
XL
452 /// ```
453 #[inline]
454 #[unstable(feature = "ptr_as_uninit", issue = "75402")]
455 pub unsafe fn as_uninit_slice_mut(&self) -> &mut [MaybeUninit<T>] {
456 // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
457 unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
458 }
459
460 /// Returns a raw pointer to an element or subslice, without doing bounds
461 /// checking.
462 ///
463 /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
464 /// is *[undefined behavior]* even if the resulting pointer is not used.
465 ///
466 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
467 ///
468 /// # Examples
469 ///
470 /// ```
471 /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
472 /// use std::ptr::NonNull;
473 ///
474 /// let x = &mut [1, 2, 4];
475 /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
476 ///
477 /// unsafe {
478 /// assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
479 /// }
480 /// ```
481 #[unstable(feature = "slice_ptr_get", issue = "74265")]
482 #[inline]
483 pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
484 where
485 I: SliceIndex<[T]>,
486 {
487 // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
488 // As a consequence, the resulting pointer cannot be NULL.
489 unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
490 }
491}
492
493#[stable(feature = "nonnull", since = "1.25.0")]
494impl<T: ?Sized> Clone for NonNull<T> {
495 #[inline]
496 fn clone(&self) -> Self {
497 *self
498 }
499}
500
501#[stable(feature = "nonnull", since = "1.25.0")]
502impl<T: ?Sized> Copy for NonNull<T> {}
503
504#[unstable(feature = "coerce_unsized", issue = "27732")]
505impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
506
507#[unstable(feature = "dispatch_from_dyn", issue = "none")]
508impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
509
510#[stable(feature = "nonnull", since = "1.25.0")]
511impl<T: ?Sized> fmt::Debug for NonNull<T> {
512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513 fmt::Pointer::fmt(&self.as_ptr(), f)
514 }
515}
516
517#[stable(feature = "nonnull", since = "1.25.0")]
518impl<T: ?Sized> fmt::Pointer for NonNull<T> {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 fmt::Pointer::fmt(&self.as_ptr(), f)
521 }
522}
523
524#[stable(feature = "nonnull", since = "1.25.0")]
525impl<T: ?Sized> Eq for NonNull<T> {}
526
527#[stable(feature = "nonnull", since = "1.25.0")]
528impl<T: ?Sized> PartialEq for NonNull<T> {
529 #[inline]
530 fn eq(&self, other: &Self) -> bool {
531 self.as_ptr() == other.as_ptr()
532 }
533}
534
535#[stable(feature = "nonnull", since = "1.25.0")]
536impl<T: ?Sized> Ord for NonNull<T> {
537 #[inline]
538 fn cmp(&self, other: &Self) -> Ordering {
539 self.as_ptr().cmp(&other.as_ptr())
540 }
541}
542
543#[stable(feature = "nonnull", since = "1.25.0")]
544impl<T: ?Sized> PartialOrd for NonNull<T> {
545 #[inline]
546 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
547 self.as_ptr().partial_cmp(&other.as_ptr())
548 }
549}
550
551#[stable(feature = "nonnull", since = "1.25.0")]
552impl<T: ?Sized> hash::Hash for NonNull<T> {
553 #[inline]
554 fn hash<H: hash::Hasher>(&self, state: &mut H) {
555 self.as_ptr().hash(state)
556 }
557}
558
559#[unstable(feature = "ptr_internals", issue = "none")]
560impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
561 #[inline]
562 fn from(unique: Unique<T>) -> Self {
563 // SAFETY: A Unique pointer cannot be null, so the conditions for
564 // new_unchecked() are respected.
565 unsafe { NonNull::new_unchecked(unique.as_ptr()) }
566 }
567}
568
569#[stable(feature = "nonnull", since = "1.25.0")]
570impl<T: ?Sized> From<&mut T> for NonNull<T> {
571 #[inline]
572 fn from(reference: &mut T) -> Self {
573 // SAFETY: A mutable reference cannot be null.
574 unsafe { NonNull { pointer: reference as *mut T } }
575 }
576}
577
578#[stable(feature = "nonnull", since = "1.25.0")]
579impl<T: ?Sized> From<&T> for NonNull<T> {
580 #[inline]
581 fn from(reference: &T) -> Self {
582 // SAFETY: A reference cannot be null, so the conditions for
583 // new_unchecked() are respected.
584 unsafe { NonNull { pointer: reference as *const T } }
585 }
586}