]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/non_null.rs
Add `as_uninit`-like methods to pointer types and unify documentation of `as_ref...
[rust.git] / library / core / src / ptr / non_null.rs
1 use crate::cmp::Ordering;
2 use crate::convert::From;
3 use crate::fmt;
4 use crate::hash;
5 use crate::marker::Unsize;
6 use crate::mem::{self, MaybeUninit};
7 use crate::ops::{CoerceUnsized, DispatchFromDyn};
8 use crate::ptr::Unique;
9 use 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 ///
37 /// [`PhantomData`]: ../marker/struct.PhantomData.html
38 /// [`UnsafeCell<T>`]: ../cell/struct.UnsafeCell.html
39 #[stable(feature = "nonnull", since = "1.25.0")]
40 #[repr(transparent)]
41 #[rustc_layout_scalar_valid_range_start(1)]
42 #[rustc_nonnull_optimization_guaranteed]
43 pub 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")]
50 impl<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")]
55 impl<T: ?Sized> !Sync for NonNull<T> {}
56
57 impl<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     ///
85     /// [`as_ref`]: #method.as_ref
86     /// [`as_uninit_mut`]: #method.as_uninit_mut
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     ///
117     /// [`as_mut`]: #method.as_mut
118     /// [`as_uninit_ref`]: #method.as_uninit_ref
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
145 impl<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     ///
184     /// [`as_uninit_ref`]: #method.as_uninit_ref
185     /// [`as_mut`]: #method.as_mut
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     ///
220     /// [`as_uninit_mut`]: #method.as_uninit_mut
221     /// [`as_ref`]: #method.as_ref
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
261 impl<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     ///
269     /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
270     ///
271     /// # Examples
272     ///
273     /// ```rust
274     /// #![feature(nonnull_slice_from_raw_parts)]
275     ///
276     /// use std::ptr::NonNull;
277     ///
278     /// // create a slice pointer when starting out with a pointer to the first element
279     /// let mut x = [5, 6, 7];
280     /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
281     /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
282     /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
283     /// ```
284     ///
285     /// (Note that this example artificially demonstrates a use of this method,
286     /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
287     #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
288     #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
289     #[inline]
290     pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
291         // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
292         unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
293     }
294
295     /// Returns the length of a non-null raw slice.
296     ///
297     /// The returned value is the number of **elements**, not the number of bytes.
298     ///
299     /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
300     /// because the pointer does not have a valid address.
301     ///
302     /// # Examples
303     ///
304     /// ```rust
305     /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
306     /// use std::ptr::NonNull;
307     ///
308     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
309     /// assert_eq!(slice.len(), 3);
310     /// ```
311     #[unstable(feature = "slice_ptr_len", issue = "71146")]
312     #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
313     #[inline]
314     pub const fn len(self) -> usize {
315         self.as_ptr().len()
316     }
317
318     /// Returns a non-null pointer to the slice's buffer.
319     ///
320     /// # Examples
321     ///
322     /// ```rust
323     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
324     /// use std::ptr::NonNull;
325     ///
326     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
327     /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap());
328     /// ```
329     #[inline]
330     #[unstable(feature = "slice_ptr_get", issue = "74265")]
331     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
332     pub const fn as_non_null_ptr(self) -> NonNull<T> {
333         // SAFETY: We know `self` is non-null.
334         unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) }
335     }
336
337     /// Returns a raw pointer to the slice's buffer.
338     ///
339     /// # Examples
340     ///
341     /// ```rust
342     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
343     /// use std::ptr::NonNull;
344     ///
345     /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
346     /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8);
347     /// ```
348     #[inline]
349     #[unstable(feature = "slice_ptr_get", issue = "74265")]
350     #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
351     pub const fn as_mut_ptr(self) -> *mut T {
352         self.as_non_null_ptr().as_ptr()
353     }
354
355     /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
356     /// [`as_ref`], this does not require that the value has to be initialized.
357     ///
358     /// For the mutable counterpart see [`as_uninit_slice_mut`].
359     ///
360     /// [`as_ref`]: #method.as_ref
361     /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
362     ///
363     /// # Safety
364     ///
365     /// When calling this method, you have to ensure that all of the following is true:
366     ///
367     /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
368     ///   and it must be properly aligned. This means in particular:
369     ///
370     ///     * The entire memory range of this slice must be contained within a single allocated object!
371     ///       Slices can never span across multiple allocated objects.
372     ///
373     ///     * The pointer must be aligned even for zero-length slices. One
374     ///       reason for this is that enum layout optimizations may rely on references
375     ///       (including slices of any length) being aligned and non-null to distinguish
376     ///       them from other data. You can obtain a pointer that is usable as `data`
377     ///       for zero-length slices using [`NonNull::dangling()`].
378     ///
379     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
380     ///   See the safety documentation of [`pointer::offset`].
381     ///
382     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
383     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
384     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
385     ///   not get mutated (except inside `UnsafeCell`).
386     ///
387     /// This applies even if the result of this method is unused!
388     ///
389     /// See also [`slice::from_raw_parts`][].
390     ///
391     /// [valid]: crate::ptr#safety
392     /// [`NonNull::dangling()`]: NonNull::dangling
393     /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
394     #[inline]
395     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
396     pub unsafe fn as_uninit_slice(&self) -> &[MaybeUninit<T>] {
397         // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
398         unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
399     }
400
401     /// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
402     /// [`as_mut`], this does not require that the value has to be initialized.
403     ///
404     /// For the shared counterpart see [`as_uninit_slice`].
405     ///
406     /// [`as_mut`]: #method.as_mut
407     /// [`as_uninit_slice`]: #method.as_uninit_slice
408     ///
409     /// # Safety
410     ///
411     /// When calling this method, you have to ensure that all of the following is true:
412     ///
413     /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
414     ///   many bytes, and it must be properly aligned. This means in particular:
415     ///
416     ///     * The entire memory range of this slice must be contained within a single allocated object!
417     ///       Slices can never span across multiple allocated objects.
418     ///
419     ///     * The pointer must be aligned even for zero-length slices. One
420     ///       reason for this is that enum layout optimizations may rely on references
421     ///       (including slices of any length) being aligned and non-null to distinguish
422     ///       them from other data. You can obtain a pointer that is usable as `data`
423     ///       for zero-length slices using [`NonNull::dangling()`].
424     ///
425     /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
426     ///   See the safety documentation of [`pointer::offset`].
427     ///
428     /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
429     ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
430     ///   In particular, for the duration of this lifetime, the memory the pointer points to must
431     ///   not get accessed (read or written) through any other pointer.
432     ///
433     /// This applies even if the result of this method is unused!
434     ///
435     /// See also [`slice::from_raw_parts_mut`][].
436     ///
437     /// [valid]: crate::ptr#safety
438     /// [`NonNull::dangling()`]: NonNull::dangling
439     /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
440     ///
441     /// # Examples
442     ///
443     /// ```rust
444     /// #![feature(allocator_api, ptr_as_uninit)]
445     ///
446     /// use std::alloc::{AllocRef, Layout, Global};
447     /// use std::mem::MaybeUninit;
448     /// use std::ptr::NonNull;
449     ///
450     /// let memory: NonNull<[u8]> = Global.alloc(Layout::new::<[u8; 32]>())?;
451     /// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
452     /// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
453     /// # #[allow(unused_variables)]
454     /// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
455     /// # Ok::<_, std::alloc::AllocErr>(())
456     /// ```
457     #[inline]
458     #[unstable(feature = "ptr_as_uninit", issue = "75402")]
459     pub unsafe fn as_uninit_slice_mut(&self) -> &mut [MaybeUninit<T>] {
460         // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
461         unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
462     }
463
464     /// Returns a raw pointer to an element or subslice, without doing bounds
465     /// checking.
466     ///
467     /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
468     /// is *[undefined behavior]* even if the resulting pointer is not used.
469     ///
470     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)]
476     /// use std::ptr::NonNull;
477     ///
478     /// let x = &mut [1, 2, 4];
479     /// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
480     ///
481     /// unsafe {
482     ///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
483     /// }
484     /// ```
485     #[unstable(feature = "slice_ptr_get", issue = "74265")]
486     #[inline]
487     pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
488     where
489         I: SliceIndex<[T]>,
490     {
491         // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
492         // As a consequence, the resulting pointer cannot be NULL.
493         unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
494     }
495 }
496
497 #[stable(feature = "nonnull", since = "1.25.0")]
498 impl<T: ?Sized> Clone for NonNull<T> {
499     #[inline]
500     fn clone(&self) -> Self {
501         *self
502     }
503 }
504
505 #[stable(feature = "nonnull", since = "1.25.0")]
506 impl<T: ?Sized> Copy for NonNull<T> {}
507
508 #[unstable(feature = "coerce_unsized", issue = "27732")]
509 impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
510
511 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
512 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> {}
513
514 #[stable(feature = "nonnull", since = "1.25.0")]
515 impl<T: ?Sized> fmt::Debug for NonNull<T> {
516     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517         fmt::Pointer::fmt(&self.as_ptr(), f)
518     }
519 }
520
521 #[stable(feature = "nonnull", since = "1.25.0")]
522 impl<T: ?Sized> fmt::Pointer for NonNull<T> {
523     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524         fmt::Pointer::fmt(&self.as_ptr(), f)
525     }
526 }
527
528 #[stable(feature = "nonnull", since = "1.25.0")]
529 impl<T: ?Sized> Eq for NonNull<T> {}
530
531 #[stable(feature = "nonnull", since = "1.25.0")]
532 impl<T: ?Sized> PartialEq for NonNull<T> {
533     #[inline]
534     fn eq(&self, other: &Self) -> bool {
535         self.as_ptr() == other.as_ptr()
536     }
537 }
538
539 #[stable(feature = "nonnull", since = "1.25.0")]
540 impl<T: ?Sized> Ord for NonNull<T> {
541     #[inline]
542     fn cmp(&self, other: &Self) -> Ordering {
543         self.as_ptr().cmp(&other.as_ptr())
544     }
545 }
546
547 #[stable(feature = "nonnull", since = "1.25.0")]
548 impl<T: ?Sized> PartialOrd for NonNull<T> {
549     #[inline]
550     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
551         self.as_ptr().partial_cmp(&other.as_ptr())
552     }
553 }
554
555 #[stable(feature = "nonnull", since = "1.25.0")]
556 impl<T: ?Sized> hash::Hash for NonNull<T> {
557     #[inline]
558     fn hash<H: hash::Hasher>(&self, state: &mut H) {
559         self.as_ptr().hash(state)
560     }
561 }
562
563 #[unstable(feature = "ptr_internals", issue = "none")]
564 impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
565     #[inline]
566     fn from(unique: Unique<T>) -> Self {
567         // SAFETY: A Unique pointer cannot be null, so the conditions for
568         // new_unchecked() are respected.
569         unsafe { NonNull::new_unchecked(unique.as_ptr()) }
570     }
571 }
572
573 #[stable(feature = "nonnull", since = "1.25.0")]
574 impl<T: ?Sized> From<&mut T> for NonNull<T> {
575     #[inline]
576     fn from(reference: &mut T) -> Self {
577         // SAFETY: A mutable reference cannot be null.
578         unsafe { NonNull { pointer: reference as *mut T } }
579     }
580 }
581
582 #[stable(feature = "nonnull", since = "1.25.0")]
583 impl<T: ?Sized> From<&T> for NonNull<T> {
584     #[inline]
585     fn from(reference: &T) -> Self {
586         // SAFETY: A reference cannot be null, so the conditions for
587         // new_unchecked() are respected.
588         unsafe { NonNull { pointer: reference as *const T } }
589     }
590 }