1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Basic functions for dealing with memory.
13 //! This module contains functions for querying the size and alignment of
14 //! types, initializing and manipulating memory.
16 #![stable(feature = "rust1", since = "1.0.0")]
23 use marker::{Copy, PhantomData, Sized};
25 use ops::{Deref, DerefMut};
27 #[stable(feature = "rust1", since = "1.0.0")]
28 pub use intrinsics::transmute;
30 /// Leaks a value: takes ownership and "forgets" about the value **without running
33 /// Any resources the value manages, such as heap memory or a file handle, will linger
34 /// forever in an unreachable state.
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 /// so `forget` is only recommended for specialized use cases like those shown below.
51 /// Because forgetting a value is allowed, any `unsafe` code you write must
52 /// allow for this possibility. You cannot return a value and expect that the
53 /// caller will necessarily run the value's destructor.
55 /// [rc]: ../../std/rc/struct.Rc.html
56 /// [exit]: ../../std/process/fn.exit.html
60 /// Leak some heap memory by never deallocating it:
65 /// let heap_memory = Box::new(3);
66 /// mem::forget(heap_memory);
69 /// Leak an I/O object, never closing the file:
73 /// use std::fs::File;
75 /// let file = File::open("foo.txt").unwrap();
76 /// mem::forget(file);
79 /// The practical use cases for `forget` are rather specialized and mainly come
80 /// up in unsafe or FFI code.
84 /// You have created an uninitialized value using [`mem::uninitialized`][uninit].
85 /// You must either initialize or `forget` it on every computation path before
86 /// Rust drops it automatically, like at the end of a scope or after a panic.
87 /// Running the destructor on an uninitialized value would be [undefined behavior][ub].
93 /// # let some_condition = false;
95 /// let mut uninit_vec: Vec<u32> = mem::uninitialized();
97 /// if some_condition {
98 /// // Initialize the variable.
99 /// ptr::write(&mut uninit_vec, Vec::new());
101 /// // Forget the uninitialized value so its destructor doesn't run.
102 /// mem::forget(uninit_vec);
109 /// You have duplicated the bytes making up a value, without doing a proper
110 /// [`Clone`][clone]. You need the value's destructor to run only once,
111 /// because a double `free` is undefined behavior.
113 /// An example is a possible implementation of [`mem::swap`][swap]:
119 /// # #[allow(dead_code)]
120 /// fn swap<T>(x: &mut T, y: &mut T) {
122 /// // Give ourselves some scratch space to work with
123 /// let mut t: T = mem::uninitialized();
125 /// // Perform the swap, `&mut` pointers never alias
126 /// ptr::copy_nonoverlapping(&*x, &mut t, 1);
127 /// ptr::copy_nonoverlapping(&*y, x, 1);
128 /// ptr::copy_nonoverlapping(&t, y, 1);
130 /// // y and t now point to the same thing, but we need to completely
131 /// // forget `t` because we do not want to run the destructor for `T`
132 /// // on its value, which is still owned somewhere outside this function.
140 /// You are transferring ownership across a [FFI] boundary to code written in
141 /// another language. You need to `forget` the value on the Rust side because Rust
142 /// code is no longer responsible for it.
148 /// fn my_c_function(x: *const u32);
151 /// let x: Box<u32> = Box::new(3);
153 /// // Transfer ownership into C code.
155 /// my_c_function(&*x);
160 /// In this case, C code must call back into Rust to free the object. Calling C's `free`
161 /// function on a [`Box`][box] is *not* safe! Also, `Box` provides an [`into_raw`][into_raw]
162 /// method which is the preferred way to do this in practice.
164 /// [drop]: fn.drop.html
165 /// [uninit]: fn.uninitialized.html
166 /// [clone]: ../clone/trait.Clone.html
167 /// [swap]: fn.swap.html
168 /// [FFI]: ../../book/first-edition/ffi.html
169 /// [box]: ../../std/boxed/struct.Box.html
170 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
171 /// [ub]: ../../reference/behavior-considered-undefined.html
173 #[stable(feature = "rust1", since = "1.0.0")]
174 pub fn forget<T>(t: T) {
175 ManuallyDrop::new(t);
178 /// Returns the size of a type in bytes.
180 /// More specifically, this is the offset in bytes between successive elements
181 /// in an array with that item type including alignment padding. Thus, for any
182 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
184 /// In general, the size of a type is not stable across compilations, but
185 /// specific types such as primitives are.
187 /// The following table gives the size for primitives.
189 /// Type | size_of::\<Type>()
190 /// ---- | ---------------
204 /// Furthermore, `usize` and `isize` have the same size.
206 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
207 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
209 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
210 /// have the same size. Likewise for `*const T` and `*mut T`.
212 /// # Size of `#[repr(C)]` items
214 /// The `C` representation for items has a defined layout. With this layout,
215 /// the size of items is also stable as long as all fields have a stable size.
217 /// ## Size of Structs
219 /// For `structs`, the size is determined by the following algorithm.
221 /// For each field in the struct ordered by declaration order:
223 /// 1. Add the size of the field.
224 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
226 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
228 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
232 /// Enums that carry no data other than the descriminant have the same size as C enums
233 /// on the platform they are compiled for.
235 /// ## Size of Unions
237 /// The size of a union is the size of its largest field.
239 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
246 /// // Some primitives
247 /// assert_eq!(4, mem::size_of::<i32>());
248 /// assert_eq!(8, mem::size_of::<f64>());
249 /// assert_eq!(0, mem::size_of::<()>());
252 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
253 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
254 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
257 /// // Pointer size equality
258 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
259 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
260 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
261 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
264 /// Using `#[repr(C)]`.
270 /// struct FieldStruct {
276 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
277 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
278 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
279 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
280 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
281 /// // Finally, the alignment of the struct is 2, so add 1 to the size for padding. Size is 6.
282 /// assert_eq!(6, mem::size_of::<FieldStruct>());
285 /// struct TupleStruct(u8, u16, u8);
287 /// // Tuple structs follow the same rules.
288 /// assert_eq!(6, mem::size_of::<TupleStruct>());
290 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
291 /// // by putting `third` before `second`.
293 /// struct FieldStructOptimized {
299 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
301 /// // Union size is the size of the largest field.
303 /// union ExampleUnion {
308 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
311 /// [alignment]: ./fn.align_of.html
313 #[stable(feature = "rust1", since = "1.0.0")]
314 #[rustc_const_unstable(feature = "const_size_of")]
315 pub const fn size_of<T>() -> usize {
316 unsafe { intrinsics::size_of::<T>() }
319 /// Returns the size of the pointed-to value in bytes.
321 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
322 /// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
323 /// then `size_of_val` can be used to get the dynamically-known size.
325 /// [slice]: ../../std/primitive.slice.html
326 /// [trait object]: ../../book/first-edition/trait-objects.html
333 /// assert_eq!(4, mem::size_of_val(&5i32));
335 /// let x: [u8; 13] = [0; 13];
336 /// let y: &[u8] = &x;
337 /// assert_eq!(13, mem::size_of_val(y));
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
342 unsafe { intrinsics::size_of_val(val) }
345 /// Returns the [ABI]-required minimum alignment of a type.
347 /// Every reference to a value of the type `T` must be a multiple of this number.
349 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
351 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
356 /// # #![allow(deprecated)]
359 /// assert_eq!(4, mem::min_align_of::<i32>());
362 #[stable(feature = "rust1", since = "1.0.0")]
363 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
364 pub fn min_align_of<T>() -> usize {
365 unsafe { intrinsics::min_align_of::<T>() }
368 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
370 /// Every reference to a value of the type `T` must be a multiple of this number.
372 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
377 /// # #![allow(deprecated)]
380 /// assert_eq!(4, mem::min_align_of_val(&5i32));
383 #[stable(feature = "rust1", since = "1.0.0")]
384 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
385 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
386 unsafe { intrinsics::min_align_of_val(val) }
389 /// Returns the [ABI]-required minimum alignment of a type.
391 /// Every reference to a value of the type `T` must be a multiple of this number.
393 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
395 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
402 /// assert_eq!(4, mem::align_of::<i32>());
405 #[stable(feature = "rust1", since = "1.0.0")]
406 #[rustc_const_unstable(feature = "const_align_of")]
407 pub const fn align_of<T>() -> usize {
408 unsafe { intrinsics::min_align_of::<T>() }
411 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
413 /// Every reference to a value of the type `T` must be a multiple of this number.
415 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
422 /// assert_eq!(4, mem::align_of_val(&5i32));
425 #[stable(feature = "rust1", since = "1.0.0")]
426 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
427 unsafe { intrinsics::min_align_of_val(val) }
430 /// Returns whether dropping values of type `T` matters.
432 /// This is purely an optimization hint, and may be implemented conservatively:
433 /// it may return `true` for types that don't actually need to be dropped.
434 /// As such always returning `true` would be a valid implementation of
435 /// this function. However if this function actually returns `false`, then you
436 /// can be certain dropping `T` has no side effect.
438 /// Low level implementations of things like collections, which need to manually
439 /// drop their data, should use this function to avoid unnecessarily
440 /// trying to drop all their contents when they are destroyed. This might not
441 /// make a difference in release builds (where a loop that has no side-effects
442 /// is easily detected and eliminated), but is often a big win for debug builds.
444 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
445 /// can be reduced to some small number of drop_in_place calls, using this is
446 /// unnecessary. In particular note that you can drop_in_place a slice, and that
447 /// will do a single needs_drop check for all the values.
449 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
450 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
451 /// values one at a time and should use this API.
456 /// Here's an example of how a collection might make use of needs_drop:
459 /// use std::{mem, ptr};
461 /// pub struct MyCollection<T> {
465 /// # impl<T> MyCollection<T> {
466 /// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
467 /// # fn free_buffer(&mut self) {}
470 /// impl<T> Drop for MyCollection<T> {
471 /// fn drop(&mut self) {
474 /// if mem::needs_drop::<T>() {
475 /// for x in self.iter_mut() {
476 /// ptr::drop_in_place(x);
479 /// self.free_buffer();
485 #[stable(feature = "needs_drop", since = "1.21.0")]
486 pub fn needs_drop<T>() -> bool {
487 unsafe { intrinsics::needs_drop::<T>() }
490 /// Creates a value whose bytes are all zero.
492 /// This has the same effect as allocating space with
493 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
494 /// [FFI] sometimes, but should generally be avoided.
496 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
497 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
498 /// a panic or the end of a scope) before being initialized, then the destructor
499 /// will run on zeroed data, likely leading to [undefined behavior][ub].
501 /// See also the documentation for [`mem::uninitialized`][uninit], which has
502 /// many of the same caveats.
504 /// [uninit]: fn.uninitialized.html
505 /// [FFI]: ../../book/first-edition/ffi.html
506 /// [ub]: ../../reference/behavior-considered-undefined.html
513 /// let x: i32 = unsafe { mem::zeroed() };
514 /// assert_eq!(0, x);
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub unsafe fn zeroed<T>() -> T {
522 /// Bypasses Rust's normal memory-initialization checks by pretending to
523 /// produce a value of type `T`, while doing nothing at all.
525 /// **This is incredibly dangerous and should not be done lightly. Deeply
526 /// consider initializing your memory with a default value instead.**
528 /// This is useful for [FFI] functions and initializing arrays sometimes,
529 /// but should generally be avoided.
531 /// [FFI]: ../../book/first-edition/ffi.html
533 /// # Undefined behavior
535 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
536 /// uninitialized boolean. For instance, if you branch on the value of such
537 /// a boolean, your program may take one, both, or neither of the branches.
539 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
540 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
541 /// value and its fields if you try to overwrite it in a normal manner. The only way
542 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
543 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
545 /// If the value does implement [`Drop`], it must be initialized before
546 /// it goes out of scope (and therefore would be dropped). Note that this
547 /// includes a `panic` occurring and unwinding the stack suddenly.
551 /// Here's how to safely initialize an array of [`Vec`]s.
557 /// // Only declare the array. This safely leaves it
558 /// // uninitialized in a way that Rust will track for us.
559 /// // However we can't initialize it element-by-element
560 /// // safely, and we can't use the `[value; 1000]`
561 /// // constructor because it only works with `Copy` data.
562 /// let mut data: [Vec<u32>; 1000];
565 /// // So we need to do this to initialize it.
566 /// data = mem::uninitialized();
568 /// // DANGER ZONE: if anything panics or otherwise
569 /// // incorrectly reads the array here, we will have
570 /// // Undefined Behavior.
572 /// // It's ok to mutably iterate the data, since this
573 /// // doesn't involve reading it at all.
574 /// // (ptr and len are statically known for arrays)
575 /// for elem in &mut data[..] {
576 /// // *elem = Vec::new() would try to drop the
577 /// // uninitialized memory at `elem` -- bad!
579 /// // Vec::new doesn't allocate or do really
580 /// // anything. It's only safe to call here
581 /// // because we know it won't panic.
582 /// ptr::write(elem, Vec::new());
585 /// // SAFE ZONE: everything is initialized.
588 /// println!("{:?}", &data[0]);
591 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
592 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
593 /// value that is only [`Clone`], so the following is semantically equivalent and
594 /// vastly less dangerous, as long as you can live with an extra heap
598 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
599 /// println!("{:?}", &data[0]);
602 /// [`Vec`]: ../../std/vec/struct.Vec.html
603 /// [`vec!`]: ../../std/macro.vec.html
604 /// [`Clone`]: ../../std/clone/trait.Clone.html
605 /// [ub]: ../../reference/behavior-considered-undefined.html
606 /// [write]: ../ptr/fn.write.html
607 /// [copy]: ../intrinsics/fn.copy.html
608 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
609 /// [`Drop`]: ../ops/trait.Drop.html
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub unsafe fn uninitialized<T>() -> T {
616 /// Swaps the values at two mutable locations, without deinitializing either one.
626 /// mem::swap(&mut x, &mut y);
628 /// assert_eq!(42, x);
629 /// assert_eq!(5, y);
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn swap<T>(x: &mut T, y: &mut T) {
635 ptr::swap_nonoverlapping(x, y, 1);
639 /// Replaces the value at a mutable location with a new one, returning the old value, without
640 /// deinitializing either one.
644 /// A simple example:
649 /// let mut v: Vec<i32> = vec![1, 2];
651 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
652 /// assert_eq!(2, old_v.len());
653 /// assert_eq!(3, v.len());
656 /// `replace` allows consumption of a struct field by replacing it with another value.
657 /// Without `replace` you can run into issues like these:
659 /// ```compile_fail,E0507
660 /// struct Buffer<T> { buf: Vec<T> }
662 /// impl<T> Buffer<T> {
663 /// fn get_and_reset(&mut self) -> Vec<T> {
664 /// // error: cannot move out of dereference of `&mut`-pointer
665 /// let buf = self.buf;
666 /// self.buf = Vec::new();
672 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
673 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
674 /// `self`, allowing it to be returned:
677 /// # #![allow(dead_code)]
680 /// # struct Buffer<T> { buf: Vec<T> }
681 /// impl<T> Buffer<T> {
682 /// fn get_and_reset(&mut self) -> Vec<T> {
683 /// mem::replace(&mut self.buf, Vec::new())
688 /// [`Clone`]: ../../std/clone/trait.Clone.html
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
692 swap(dest, &mut src);
696 /// Disposes of a value.
698 /// While this does call the argument's implementation of [`Drop`][drop],
699 /// it will not release any borrows, as borrows are based on lexical scope.
701 /// This effectively does nothing for
702 /// [types which implement `Copy`](../../book/first-edition/ownership.html#copy-types),
703 /// e.g. integers. Such values are copied and _then_ moved into the function,
704 /// so the value persists after this function call.
706 /// This function is not magic; it is literally defined as
709 /// pub fn drop<T>(_x: T) { }
712 /// Because `_x` is moved into the function, it is automatically dropped before
713 /// the function returns.
715 /// [drop]: ../ops/trait.Drop.html
722 /// let v = vec![1, 2, 3];
724 /// drop(v); // explicitly drop the vector
727 /// Borrows are based on lexical scope, so this produces an error:
729 /// ```compile_fail,E0502
730 /// let mut v = vec![1, 2, 3];
733 /// drop(x); // explicitly drop the reference, but the borrow still exists
735 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
736 /// // borrowed as immutable
739 /// An inner scope is needed to fix this:
742 /// let mut v = vec![1, 2, 3];
747 /// drop(x); // this is now redundant, as `x` is going out of scope anyway
750 /// v.push(4); // no problems
753 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
754 /// release a [`RefCell`] borrow:
757 /// use std::cell::RefCell;
759 /// let x = RefCell::new(1);
761 /// let mut mutable_borrow = x.borrow_mut();
762 /// *mutable_borrow = 1;
764 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
766 /// let borrow = x.borrow();
767 /// println!("{}", *borrow);
770 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
773 /// #[derive(Copy, Clone)]
778 /// drop(x); // a copy of `x` is moved and dropped
779 /// drop(y); // a copy of `y` is moved and dropped
781 /// println!("x: {}, y: {}", x, y.0); // still available
784 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
785 /// [`Copy`]: ../../std/marker/trait.Copy.html
787 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn drop<T>(_x: T) { }
790 /// Interprets `src` as having type `&U`, and then reads `src` without moving
791 /// the contained value.
793 /// This function will unsafely assume the pointer `src` is valid for
794 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
795 /// the `&U`. It will also unsafely create a copy of the contained value instead of
796 /// moving out of `src`.
798 /// It is not a compile-time error if `T` and `U` have different sizes, but it
799 /// is highly encouraged to only invoke this function where `T` and `U` have the
800 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
803 /// [ub]: ../../reference/behavior-considered-undefined.html
804 /// [size_of]: fn.size_of.html
816 /// let foo_slice = [10u8];
819 /// // Copy the data from 'foo_slice' and treat it as a 'Foo'
820 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
821 /// assert_eq!(foo_struct.bar, 10);
823 /// // Modify the copied data
824 /// foo_struct.bar = 20;
825 /// assert_eq!(foo_struct.bar, 20);
828 /// // The contents of 'foo_slice' should not have changed
829 /// assert_eq!(foo_slice, [10]);
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
834 ptr::read(src as *const T as *const U)
837 /// Opaque type representing the discriminant of an enum.
839 /// See the `discriminant` function in this module for more information.
840 #[stable(feature = "discriminant_value", since = "1.21.0")]
841 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
843 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
845 #[stable(feature = "discriminant_value", since = "1.21.0")]
846 impl<T> Copy for Discriminant<T> {}
848 #[stable(feature = "discriminant_value", since = "1.21.0")]
849 impl<T> clone::Clone for Discriminant<T> {
850 fn clone(&self) -> Self {
855 #[stable(feature = "discriminant_value", since = "1.21.0")]
856 impl<T> cmp::PartialEq for Discriminant<T> {
857 fn eq(&self, rhs: &Self) -> bool {
862 #[stable(feature = "discriminant_value", since = "1.21.0")]
863 impl<T> cmp::Eq for Discriminant<T> {}
865 #[stable(feature = "discriminant_value", since = "1.21.0")]
866 impl<T> hash::Hash for Discriminant<T> {
867 fn hash<H: hash::Hasher>(&self, state: &mut H) {
872 #[stable(feature = "discriminant_value", since = "1.21.0")]
873 impl<T> fmt::Debug for Discriminant<T> {
874 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
875 fmt.debug_tuple("Discriminant")
881 /// Returns a value uniquely identifying the enum variant in `v`.
883 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
884 /// return value is unspecified.
888 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
889 /// of some variant will not change between compilations with the same compiler.
893 /// This can be used to compare enums that carry data, while disregarding
899 /// enum Foo { A(&'static str), B(i32), C(i32) }
901 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
902 /// assert!(mem::discriminant(&Foo::B(1)) == mem::discriminant(&Foo::B(2)));
903 /// assert!(mem::discriminant(&Foo::B(3)) != mem::discriminant(&Foo::C(3)));
905 #[stable(feature = "discriminant_value", since = "1.21.0")]
906 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
908 Discriminant(intrinsics::discriminant_value(v), PhantomData)
913 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
915 /// This wrapper is 0-cost.
919 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
923 /// use std::mem::ManuallyDrop;
927 /// struct FruitBox {
928 /// // Immediately clear there’s something non-trivial going on with these fields.
929 /// peach: ManuallyDrop<Peach>,
930 /// melon: Melon, // Field that’s independent of the other two.
931 /// banana: ManuallyDrop<Banana>,
934 /// impl Drop for FruitBox {
935 /// fn drop(&mut self) {
937 /// // Explicit ordering in which field destructors are run specified in the intuitive
938 /// // location – the destructor of the structure containing the fields.
939 /// // Moreover, one can now reorder fields within the struct however much they want.
940 /// ManuallyDrop::drop(&mut self.peach);
941 /// ManuallyDrop::drop(&mut self.banana);
943 /// // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
944 /// // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
948 #[stable(feature = "manually_drop", since = "1.20.0")]
949 #[allow(unions_with_drop_fields)]
951 pub union ManuallyDrop<T>{ value: T }
953 impl<T> ManuallyDrop<T> {
954 /// Wrap a value to be manually dropped.
959 /// use std::mem::ManuallyDrop;
960 /// ManuallyDrop::new(Box::new(()));
962 #[stable(feature = "manually_drop", since = "1.20.0")]
964 pub fn new(value: T) -> ManuallyDrop<T> {
965 ManuallyDrop { value: value }
968 /// Extract the value from the ManuallyDrop container.
973 /// use std::mem::ManuallyDrop;
974 /// let x = ManuallyDrop::new(Box::new(()));
975 /// let _: Box<()> = ManuallyDrop::into_inner(x);
977 #[stable(feature = "manually_drop", since = "1.20.0")]
979 pub fn into_inner(slot: ManuallyDrop<T>) -> T {
985 /// Manually drops the contained value.
989 /// This function runs the destructor of the contained value and thus the wrapped value
990 /// now represents uninitialized data. It is up to the user of this method to ensure the
991 /// uninitialized data is not actually used.
992 #[stable(feature = "manually_drop", since = "1.20.0")]
994 pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
995 ptr::drop_in_place(&mut slot.value)
999 #[stable(feature = "manually_drop", since = "1.20.0")]
1000 impl<T> Deref for ManuallyDrop<T> {
1003 fn deref(&self) -> &Self::Target {
1010 #[stable(feature = "manually_drop", since = "1.20.0")]
1011 impl<T> DerefMut for ManuallyDrop<T> {
1013 fn deref_mut(&mut self) -> &mut Self::Target {
1020 #[stable(feature = "manually_drop", since = "1.20.0")]
1021 impl<T: ::fmt::Debug> ::fmt::Debug for ManuallyDrop<T> {
1022 fn fmt(&self, fmt: &mut ::fmt::Formatter) -> ::fmt::Result {
1024 fmt.debug_tuple("ManuallyDrop").field(&self.value).finish()
1029 #[stable(feature = "manually_drop", since = "1.20.0")]
1030 impl<T: Clone> Clone for ManuallyDrop<T> {
1031 fn clone(&self) -> Self {
1032 ManuallyDrop::new(self.deref().clone())
1035 fn clone_from(&mut self, source: &Self) {
1036 self.deref_mut().clone_from(source);
1040 #[stable(feature = "manually_drop", since = "1.20.0")]
1041 impl<T: Default> Default for ManuallyDrop<T> {
1042 fn default() -> Self {
1043 ManuallyDrop::new(Default::default())
1047 #[stable(feature = "manually_drop", since = "1.20.0")]
1048 impl<T: PartialEq> PartialEq for ManuallyDrop<T> {
1049 fn eq(&self, other: &Self) -> bool {
1050 self.deref().eq(other)
1053 fn ne(&self, other: &Self) -> bool {
1054 self.deref().ne(other)
1058 #[stable(feature = "manually_drop", since = "1.20.0")]
1059 impl<T: Eq> Eq for ManuallyDrop<T> {}
1061 #[stable(feature = "manually_drop", since = "1.20.0")]
1062 impl<T: PartialOrd> PartialOrd for ManuallyDrop<T> {
1063 fn partial_cmp(&self, other: &Self) -> Option<::cmp::Ordering> {
1064 self.deref().partial_cmp(other)
1067 fn lt(&self, other: &Self) -> bool {
1068 self.deref().lt(other)
1071 fn le(&self, other: &Self) -> bool {
1072 self.deref().le(other)
1075 fn gt(&self, other: &Self) -> bool {
1076 self.deref().gt(other)
1079 fn ge(&self, other: &Self) -> bool {
1080 self.deref().ge(other)
1084 #[stable(feature = "manually_drop", since = "1.20.0")]
1085 impl<T: Ord> Ord for ManuallyDrop<T> {
1086 fn cmp(&self, other: &Self) -> ::cmp::Ordering {
1087 self.deref().cmp(other)
1091 #[stable(feature = "manually_drop", since = "1.20.0")]
1092 impl<T: ::hash::Hash> ::hash::Hash for ManuallyDrop<T> {
1093 fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
1094 self.deref().hash(state);
1098 /// Tells LLVM that this point in the code is not reachable, enabling further
1101 /// NB: This is very different from the `unreachable!()` macro: Unlike the
1102 /// macro, which panics when it is executed, it is *undefined behavior* to
1103 /// reach code marked with this function.
1105 #[unstable(feature = "unreachable", issue = "43751")]
1106 pub unsafe fn unreachable() -> ! {
1107 intrinsics::unreachable()