1 //! Basic functions for dealing with memory.
3 //! This module contains functions for querying the size and alignment of
4 //! types, initializing and manipulating memory.
6 #![stable(feature = "rust1", since = "1.0.0")]
12 use crate::intrinsics;
13 use crate::marker::{Copy, PhantomData, Sized};
17 #[stable(feature = "manually_drop", since = "1.20.0")]
18 pub use manually_drop::ManuallyDrop;
21 #[stable(feature = "maybe_uninit", since = "1.36.0")]
22 pub use maybe_uninit::MaybeUninit;
24 #[stable(feature = "rust1", since = "1.0.0")]
26 pub use crate::intrinsics::transmute;
28 /// Takes ownership and "forgets" about the value **without running its destructor**.
30 /// Any resources the value manages, such as heap memory or a file handle, will linger
31 /// forever in an unreachable state. However, it does not guarantee that pointers
32 /// to this memory will remain valid.
34 /// * If you want to leak memory, see [`Box::leak`][leak].
35 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`][into_raw].
36 /// * If you want to dispose of a value properly, running its destructor, see
37 /// [`mem::drop`][drop].
41 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
42 /// do not include a guarantee that destructors will always run. For example,
43 /// a program can create a reference cycle using [`Rc`][rc], or call
44 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
45 /// `mem::forget` from safe code does not fundamentally change Rust's safety
48 /// That said, leaking resources such as memory or I/O objects is usually undesirable.
49 /// The need comes up in some specialized use cases for FFI or unsafe code, but even
50 /// then, [`ManuallyDrop`] is typically preferred.
52 /// Because forgetting a value is allowed, any `unsafe` code you write must
53 /// allow for this possibility. You cannot return a value and expect that the
54 /// caller will necessarily run the value's destructor.
56 /// [rc]: ../../std/rc/struct.Rc.html
57 /// [exit]: ../../std/process/fn.exit.html
61 /// Leak an I/O object, never closing the file:
65 /// use std::fs::File;
67 /// let file = File::open("foo.txt").unwrap();
68 /// mem::forget(file);
71 /// The practical use cases for `forget` are rather specialized and mainly come
72 /// up in unsafe or FFI code. However, [`ManuallyDrop`] is usually preferred
73 /// for such cases, e.g.:
76 /// use std::mem::ManuallyDrop;
78 /// let v = vec![65, 122];
79 /// // Before we disassemble `v` into its raw parts, make sure it
80 /// // does not get dropped!
81 /// let mut v = ManuallyDrop::new(v);
82 /// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
83 /// let ptr = v.as_mut_ptr();
84 /// let cap = v.capacity();
85 /// // Finally, build a `String`.
86 /// let s = unsafe { String::from_raw_parts(ptr, 2, cap) };
87 /// assert_eq!(s, "Az");
88 /// // `s` is implicitly dropped and its memory deallocated.
91 /// Using `ManuallyDrop` here has two advantages:
93 /// * We do not "touch" `v` after disassembling it. For some types, operations
94 /// such as passing ownership (to a funcion like `mem::forget`) requires them to actually
95 /// be fully owned right now; that is a promise we do not want to make here as we are
96 /// in the process of transferring ownership to the new `String` we are building.
97 /// * In case of an unexpected panic, `ManuallyDrop` is not dropped, but if the panic
98 /// occurs before `mem::forget` was called we might end up dropping invalid data,
99 /// or double-dropping. In other words, `ManuallyDrop` errs on the side of leaking
100 /// instead of erring on the side of dropping.
102 /// [drop]: fn.drop.html
103 /// [uninit]: fn.uninitialized.html
104 /// [clone]: ../clone/trait.Clone.html
105 /// [swap]: fn.swap.html
106 /// [box]: ../../std/boxed/struct.Box.html
107 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
108 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
109 /// [ub]: ../../reference/behavior-considered-undefined.html
110 /// [`ManuallyDrop`]: struct.ManuallyDrop.html
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub fn forget<T>(t: T) {
114 ManuallyDrop::new(t);
117 /// Like [`forget`], but also accepts unsized values.
119 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
122 /// [`forget`]: fn.forget.html
124 #[unstable(feature = "forget_unsized", issue = "none")]
125 pub fn forget_unsized<T: ?Sized>(t: T) {
126 // SAFETY: the forget intrinsic could be safe, but there's no point in making it safe since
127 // we'll be implementing this function soon via `ManuallyDrop`
128 unsafe { intrinsics::forget(t) }
131 /// Returns the size of a type in bytes.
133 /// More specifically, this is the offset in bytes between successive elements
134 /// in an array with that item type including alignment padding. Thus, for any
135 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
137 /// In general, the size of a type is not stable across compilations, but
138 /// specific types such as primitives are.
140 /// The following table gives the size for primitives.
142 /// Type | size_of::\<Type>()
143 /// ---- | ---------------
160 /// Furthermore, `usize` and `isize` have the same size.
162 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
163 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
165 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
166 /// have the same size. Likewise for `*const T` and `*mut T`.
168 /// # Size of `#[repr(C)]` items
170 /// The `C` representation for items has a defined layout. With this layout,
171 /// the size of items is also stable as long as all fields have a stable size.
173 /// ## Size of Structs
175 /// For `structs`, the size is determined by the following algorithm.
177 /// For each field in the struct ordered by declaration order:
179 /// 1. Add the size of the field.
180 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
182 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
183 /// The alignment of the struct is usually the largest alignment of all its
184 /// fields; this can be changed with the use of `repr(align(N))`.
186 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
190 /// Enums that carry no data other than the discriminant have the same size as C enums
191 /// on the platform they are compiled for.
193 /// ## Size of Unions
195 /// The size of a union is the size of its largest field.
197 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
204 /// // Some primitives
205 /// assert_eq!(4, mem::size_of::<i32>());
206 /// assert_eq!(8, mem::size_of::<f64>());
207 /// assert_eq!(0, mem::size_of::<()>());
210 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
211 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
212 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
215 /// // Pointer size equality
216 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
217 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
218 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
219 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
222 /// Using `#[repr(C)]`.
228 /// struct FieldStruct {
234 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
235 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
236 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
237 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
238 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
239 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
240 /// // fields is 2), so add 1 to the size for padding. Size is 6.
241 /// assert_eq!(6, mem::size_of::<FieldStruct>());
244 /// struct TupleStruct(u8, u16, u8);
246 /// // Tuple structs follow the same rules.
247 /// assert_eq!(6, mem::size_of::<TupleStruct>());
249 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
250 /// // by putting `third` before `second`.
252 /// struct FieldStructOptimized {
258 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
260 /// // Union size is the size of the largest field.
262 /// union ExampleUnion {
267 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
270 /// [alignment]: ./fn.align_of.html
272 #[stable(feature = "rust1", since = "1.0.0")]
274 #[rustc_const_stable(feature = "const_size_of", since = "1.32.0")]
275 pub const fn size_of<T>() -> usize {
276 intrinsics::size_of::<T>()
279 /// Returns the size of the pointed-to value in bytes.
281 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
282 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
283 /// then `size_of_val` can be used to get the dynamically-known size.
285 /// [slice]: ../../std/primitive.slice.html
286 /// [trait object]: ../../book/ch17-02-trait-objects.html
293 /// assert_eq!(4, mem::size_of_val(&5i32));
295 /// let x: [u8; 13] = [0; 13];
296 /// let y: &[u8] = &x;
297 /// assert_eq!(13, mem::size_of_val(y));
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
302 intrinsics::size_of_val(val)
305 /// Returns the [ABI]-required minimum alignment of a type.
307 /// Every reference to a value of the type `T` must be a multiple of this number.
309 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
311 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
316 /// # #![allow(deprecated)]
319 /// assert_eq!(4, mem::min_align_of::<i32>());
322 #[stable(feature = "rust1", since = "1.0.0")]
323 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
324 pub fn min_align_of<T>() -> usize {
325 intrinsics::min_align_of::<T>()
328 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
330 /// Every reference to a value of the type `T` must be a multiple of this number.
332 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
337 /// # #![allow(deprecated)]
340 /// assert_eq!(4, mem::min_align_of_val(&5i32));
343 #[stable(feature = "rust1", since = "1.0.0")]
344 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
345 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
346 intrinsics::min_align_of_val(val)
349 /// Returns the [ABI]-required minimum alignment of a type.
351 /// Every reference to a value of the type `T` must be a multiple of this number.
353 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
355 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
362 /// assert_eq!(4, mem::align_of::<i32>());
365 #[stable(feature = "rust1", since = "1.0.0")]
367 #[rustc_const_stable(feature = "const_align_of", since = "1.32.0")]
368 pub const fn align_of<T>() -> usize {
369 intrinsics::min_align_of::<T>()
372 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
374 /// Every reference to a value of the type `T` must be a multiple of this number.
376 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
383 /// assert_eq!(4, mem::align_of_val(&5i32));
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
389 min_align_of_val(val)
392 /// Returns `true` if dropping values of type `T` matters.
394 /// This is purely an optimization hint, and may be implemented conservatively:
395 /// it may return `true` for types that don't actually need to be dropped.
396 /// As such always returning `true` would be a valid implementation of
397 /// this function. However if this function actually returns `false`, then you
398 /// can be certain dropping `T` has no side effect.
400 /// Low level implementations of things like collections, which need to manually
401 /// drop their data, should use this function to avoid unnecessarily
402 /// trying to drop all their contents when they are destroyed. This might not
403 /// make a difference in release builds (where a loop that has no side-effects
404 /// is easily detected and eliminated), but is often a big win for debug builds.
406 /// Note that [`drop_in_place`] already performs this check, so if your workload
407 /// can be reduced to some small number of [`drop_in_place`] calls, using this is
408 /// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
409 /// will do a single needs_drop check for all the values.
411 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
412 /// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
413 /// values one at a time and should use this API.
415 /// [`drop_in_place`]: ../ptr/fn.drop_in_place.html
416 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
420 /// Here's an example of how a collection might make use of `needs_drop`:
423 /// use std::{mem, ptr};
425 /// pub struct MyCollection<T> {
429 /// # impl<T> MyCollection<T> {
430 /// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
431 /// # fn free_buffer(&mut self) {}
434 /// impl<T> Drop for MyCollection<T> {
435 /// fn drop(&mut self) {
438 /// if mem::needs_drop::<T>() {
439 /// for x in self.iter_mut() {
440 /// ptr::drop_in_place(x);
443 /// self.free_buffer();
449 #[stable(feature = "needs_drop", since = "1.21.0")]
450 #[rustc_const_stable(feature = "const_needs_drop", since = "1.36.0")]
451 pub const fn needs_drop<T>() -> bool {
452 intrinsics::needs_drop::<T>()
455 /// Returns the value of type `T` represented by the all-zero byte-pattern.
457 /// This means that, for example, the padding byte in `(u8, u16)` is not
458 /// necessarily zeroed.
460 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
461 /// some type `T`. For example, the all-zero byte-pattern is not a valid value
462 /// for reference types (`&T` and `&mut T`). Using `zeroed` on such types
463 /// causes immediate [undefined behavior][ub] because [the Rust compiler assumes][inv]
464 /// that there always is a valid value in a variable it considers initialized.
466 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
467 /// It is useful for FFI sometimes, but should generally be avoided.
469 /// [zeroed]: union.MaybeUninit.html#method.zeroed
470 /// [ub]: ../../reference/behavior-considered-undefined.html
471 /// [inv]: union.MaybeUninit.html#initialization-invariant
475 /// Correct usage of this function: initializing an integer with zero.
480 /// let x: i32 = unsafe { mem::zeroed() };
481 /// assert_eq!(0, x);
484 /// *Incorrect* usage of this function: initializing a reference with zero.
487 /// # #![allow(invalid_value)]
490 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
493 #[stable(feature = "rust1", since = "1.0.0")]
494 #[allow(deprecated_in_future)]
496 #[rustc_diagnostic_item = "mem_zeroed"]
497 pub unsafe fn zeroed<T>() -> T {
498 intrinsics::panic_if_uninhabited::<T>();
502 /// Bypasses Rust's normal memory-initialization checks by pretending to
503 /// produce a value of type `T`, while doing nothing at all.
505 /// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
507 /// The reason for deprecation is that the function basically cannot be used
508 /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
509 /// As the [`assume_init` documentation][assume_init] explains,
510 /// [the Rust compiler assumes][inv] that values are properly initialized.
511 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
512 /// undefined behavior for returning a `bool` that is not definitely either `true`
513 /// or `false`. Worse, truly uninitialized memory like what gets returned here
514 /// is special in that the compiler knows that it does not have a fixed value.
515 /// This makes it undefined behavior to have uninitialized data in a variable even
516 /// if that variable has an integer type.
517 /// (Notice that the rules around uninitialized integers are not finalized yet, but
518 /// until they are, it is advisable to avoid them.)
520 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
521 /// [uninit]: union.MaybeUninit.html#method.uninit
522 /// [assume_init]: union.MaybeUninit.html#method.assume_init
523 /// [inv]: union.MaybeUninit.html#initialization-invariant
525 #[rustc_deprecated(since = "1.39.0", reason = "use `mem::MaybeUninit` instead")]
526 #[stable(feature = "rust1", since = "1.0.0")]
527 #[allow(deprecated_in_future)]
529 #[rustc_diagnostic_item = "mem_uninitialized"]
530 pub unsafe fn uninitialized<T>() -> T {
531 intrinsics::panic_if_uninhabited::<T>();
535 /// Swaps the values at two mutable locations, without deinitializing either one.
545 /// mem::swap(&mut x, &mut y);
547 /// assert_eq!(42, x);
548 /// assert_eq!(5, y);
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn swap<T>(x: &mut T, y: &mut T) {
553 // SAFETY: the raw pointers have been created from safe mutable references satisfying all the
554 // constraints on `ptr::swap_nonoverlapping_one`
556 ptr::swap_nonoverlapping_one(x, y);
560 /// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
564 /// A simple example:
569 /// let mut v: Vec<i32> = vec![1, 2];
571 /// let old_v = mem::take(&mut v);
572 /// assert_eq!(vec![1, 2], old_v);
573 /// assert!(v.is_empty());
576 /// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
577 /// Without `take` you can run into issues like these:
579 /// ```compile_fail,E0507
580 /// struct Buffer<T> { buf: Vec<T> }
582 /// impl<T> Buffer<T> {
583 /// fn get_and_reset(&mut self) -> Vec<T> {
584 /// // error: cannot move out of dereference of `&mut`-pointer
585 /// let buf = self.buf;
586 /// self.buf = Vec::new();
592 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
593 /// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
594 /// `self`, allowing it to be returned:
599 /// # struct Buffer<T> { buf: Vec<T> }
600 /// impl<T> Buffer<T> {
601 /// fn get_and_reset(&mut self) -> Vec<T> {
602 /// mem::take(&mut self.buf)
606 /// let mut buffer = Buffer { buf: vec![0, 1] };
607 /// assert_eq!(buffer.buf.len(), 2);
609 /// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
610 /// assert_eq!(buffer.buf.len(), 0);
613 /// [`Clone`]: ../../std/clone/trait.Clone.html
615 #[stable(feature = "mem_take", since = "1.40.0")]
616 pub fn take<T: Default>(dest: &mut T) -> T {
617 replace(dest, T::default())
620 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
622 /// Neither value is dropped.
626 /// A simple example:
631 /// let mut v: Vec<i32> = vec![1, 2];
633 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
634 /// assert_eq!(vec![1, 2], old_v);
635 /// assert_eq!(vec![3, 4, 5], v);
638 /// `replace` allows consumption of a struct field by replacing it with another value.
639 /// Without `replace` you can run into issues like these:
641 /// ```compile_fail,E0507
642 /// struct Buffer<T> { buf: Vec<T> }
644 /// impl<T> Buffer<T> {
645 /// fn replace_index(&mut self, i: usize, v: T) -> T {
646 /// // error: cannot move out of dereference of `&mut`-pointer
647 /// let t = self.buf[i];
654 /// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
655 /// avoid the move. But `replace` can be used to disassociate the original value at that index from
656 /// `self`, allowing it to be returned:
659 /// # #![allow(dead_code)]
662 /// # struct Buffer<T> { buf: Vec<T> }
663 /// impl<T> Buffer<T> {
664 /// fn replace_index(&mut self, i: usize, v: T) -> T {
665 /// mem::replace(&mut self.buf[i], v)
669 /// let mut buffer = Buffer { buf: vec![0, 1] };
670 /// assert_eq!(buffer.buf[0], 0);
672 /// assert_eq!(buffer.replace_index(0, 2), 0);
673 /// assert_eq!(buffer.buf[0], 2);
676 /// [`Clone`]: ../../std/clone/trait.Clone.html
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
680 swap(dest, &mut src);
684 /// Disposes of a value.
686 /// This does call the argument's implementation of [`Drop`][drop].
688 /// This effectively does nothing for types which implement `Copy`, e.g.
689 /// integers. Such values are copied and _then_ moved into the function, so the
690 /// value persists after this function call.
692 /// This function is not magic; it is literally defined as
695 /// pub fn drop<T>(_x: T) { }
698 /// Because `_x` is moved into the function, it is automatically dropped before
699 /// the function returns.
701 /// [drop]: ../ops/trait.Drop.html
708 /// let v = vec![1, 2, 3];
710 /// drop(v); // explicitly drop the vector
713 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
714 /// release a [`RefCell`] borrow:
717 /// use std::cell::RefCell;
719 /// let x = RefCell::new(1);
721 /// let mut mutable_borrow = x.borrow_mut();
722 /// *mutable_borrow = 1;
724 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
726 /// let borrow = x.borrow();
727 /// println!("{}", *borrow);
730 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
733 /// #[derive(Copy, Clone)]
738 /// drop(x); // a copy of `x` is moved and dropped
739 /// drop(y); // a copy of `y` is moved and dropped
741 /// println!("x: {}, y: {}", x, y.0); // still available
744 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
745 /// [`Copy`]: ../../std/marker/trait.Copy.html
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn drop<T>(_x: T) {}
750 /// Interprets `src` as having type `&U`, and then reads `src` without moving
751 /// the contained value.
753 /// This function will unsafely assume the pointer `src` is valid for
754 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
755 /// the `&U`. It will also unsafely create a copy of the contained value instead of
756 /// moving out of `src`.
758 /// It is not a compile-time error if `T` and `U` have different sizes, but it
759 /// is highly encouraged to only invoke this function where `T` and `U` have the
760 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
763 /// [ub]: ../../reference/behavior-considered-undefined.html
764 /// [size_of]: fn.size_of.html
776 /// let foo_array = [10u8];
779 /// // Copy the data from 'foo_array' and treat it as a 'Foo'
780 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
781 /// assert_eq!(foo_struct.bar, 10);
783 /// // Modify the copied data
784 /// foo_struct.bar = 20;
785 /// assert_eq!(foo_struct.bar, 20);
788 /// // The contents of 'foo_array' should not have changed
789 /// assert_eq!(foo_array, [10]);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
794 ptr::read_unaligned(src as *const T as *const U)
797 /// Opaque type representing the discriminant of an enum.
799 /// See the [`discriminant`] function in this module for more information.
801 /// [`discriminant`]: fn.discriminant.html
802 #[stable(feature = "discriminant_value", since = "1.21.0")]
803 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
805 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
807 #[stable(feature = "discriminant_value", since = "1.21.0")]
808 impl<T> Copy for Discriminant<T> {}
810 #[stable(feature = "discriminant_value", since = "1.21.0")]
811 impl<T> clone::Clone for Discriminant<T> {
812 fn clone(&self) -> Self {
817 #[stable(feature = "discriminant_value", since = "1.21.0")]
818 impl<T> cmp::PartialEq for Discriminant<T> {
819 fn eq(&self, rhs: &Self) -> bool {
824 #[stable(feature = "discriminant_value", since = "1.21.0")]
825 impl<T> cmp::Eq for Discriminant<T> {}
827 #[stable(feature = "discriminant_value", since = "1.21.0")]
828 impl<T> hash::Hash for Discriminant<T> {
829 fn hash<H: hash::Hasher>(&self, state: &mut H) {
834 #[stable(feature = "discriminant_value", since = "1.21.0")]
835 impl<T> fmt::Debug for Discriminant<T> {
836 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
837 fmt.debug_tuple("Discriminant").field(&self.0).finish()
841 /// Returns a value uniquely identifying the enum variant in `v`.
843 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
844 /// return value is unspecified.
848 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
849 /// of some variant will not change between compilations with the same compiler.
853 /// This can be used to compare enums that carry data, while disregarding
859 /// enum Foo { A(&'static str), B(i32), C(i32) }
861 /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
862 /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
863 /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
865 #[stable(feature = "discriminant_value", since = "1.21.0")]
866 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
867 Discriminant(intrinsics::discriminant_value(v), PhantomData)