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}
;
26 #[stable(feature = "rust1", since = "1.0.0")]
27 pub use intrinsics
::transmute
;
29 /// Leaks a value: takes ownership and "forgets" about the value **without running
32 /// Any resources the value manages, such as heap memory or a file handle, will linger
33 /// forever in an unreachable state.
35 /// If you want to dispose of a value properly, running its destructor, see
36 /// [`mem::drop`][drop].
40 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
41 /// do not include a guarantee that destructors will always run. For example,
42 /// a program can create a reference cycle using [`Rc`][rc], or call
43 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
44 /// `mem::forget` from safe code does not fundamentally change Rust's safety
47 /// That said, leaking resources such as memory or I/O objects is usually undesirable,
48 /// so `forget` is only recommended for specialized use cases like those shown below.
50 /// Because forgetting a value is allowed, any `unsafe` code you write must
51 /// allow for this possibility. You cannot return a value and expect that the
52 /// caller will necessarily run the value's destructor.
54 /// [rc]: ../../std/rc/struct.Rc.html
55 /// [exit]: ../../std/process/fn.exit.html
59 /// Leak some heap memory by never deallocating it:
64 /// let heap_memory = Box::new(3);
65 /// mem::forget(heap_memory);
68 /// Leak an I/O object, never closing the file:
72 /// use std::fs::File;
74 /// let file = File::open("foo.txt").unwrap();
75 /// mem::forget(file);
78 /// The practical use cases for `forget` are rather specialized and mainly come
79 /// up in unsafe or FFI code.
83 /// You have created an uninitialized value using [`mem::uninitialized`][uninit].
84 /// You must either initialize or `forget` it on every computation path before
85 /// Rust drops it automatically, like at the end of a scope or after a panic.
86 /// Running the destructor on an uninitialized value would be [undefined behavior][ub].
92 /// # let some_condition = false;
94 /// let mut uninit_vec: Vec<u32> = mem::uninitialized();
96 /// if some_condition {
97 /// // Initialize the variable.
98 /// ptr::write(&mut uninit_vec, Vec::new());
100 /// // Forget the uninitialized value so its destructor doesn't run.
101 /// mem::forget(uninit_vec);
108 /// You have duplicated the bytes making up a value, without doing a proper
109 /// [`Clone`][clone]. You need the value's destructor to run only once,
110 /// because a double `free` is undefined behavior.
112 /// An example is a possible implementation of [`mem::swap`][swap]:
118 /// # #[allow(dead_code)]
119 /// fn swap<T>(x: &mut T, y: &mut T) {
121 /// // Give ourselves some scratch space to work with
122 /// let mut t: T = mem::uninitialized();
124 /// // Perform the swap, `&mut` pointers never alias
125 /// ptr::copy_nonoverlapping(&*x, &mut t, 1);
126 /// ptr::copy_nonoverlapping(&*y, x, 1);
127 /// ptr::copy_nonoverlapping(&t, y, 1);
129 /// // y and t now point to the same thing, but we need to completely
130 /// // forget `t` because we do not want to run the destructor for `T`
131 /// // on its value, which is still owned somewhere outside this function.
139 /// You are transferring ownership across a [FFI] boundary to code written in
140 /// another language. You need to `forget` the value on the Rust side because Rust
141 /// code is no longer responsible for it.
147 /// fn my_c_function(x: *const u32);
150 /// let x: Box<u32> = Box::new(3);
152 /// // Transfer ownership into C code.
154 /// my_c_function(&*x);
159 /// In this case, C code must call back into Rust to free the object. Calling C's `free`
160 /// function on a [`Box`][box] is *not* safe! Also, `Box` provides an [`into_raw`][into_raw]
161 /// method which is the preferred way to do this in practice.
163 /// [drop]: fn.drop.html
164 /// [uninit]: fn.uninitialized.html
165 /// [clone]: ../clone/trait.Clone.html
166 /// [swap]: fn.swap.html
167 /// [FFI]: ../../book/first-edition/ffi.html
168 /// [box]: ../../std/boxed/struct.Box.html
169 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
170 /// [ub]: ../../reference/behavior-considered-undefined.html
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn forget
<T
>(t
: T
) {
174 ManuallyDrop
::new(t
);
177 /// Returns the size of a type in bytes.
179 /// More specifically, this is the offset in bytes between successive
180 /// items of the same type, including alignment padding.
187 /// assert_eq!(4, mem::size_of::<i32>());
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn size_of
<T
>() -> usize {
192 unsafe { intrinsics::size_of::<T>() }
195 /// Returns the size of the pointed-to value in bytes.
197 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
198 /// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
199 /// then `size_of_val` can be used to get the dynamically-known size.
201 /// [slice]: ../../std/primitive.slice.html
202 /// [trait object]: ../../book/first-edition/trait-objects.html
209 /// assert_eq!(4, mem::size_of_val(&5i32));
211 /// let x: [u8; 13] = [0; 13];
212 /// let y: &[u8] = &x;
213 /// assert_eq!(13, mem::size_of_val(y));
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn size_of_val
<T
: ?Sized
>(val
: &T
) -> usize {
218 unsafe { intrinsics::size_of_val(val) }
221 /// Returns the [ABI]-required minimum alignment of a type.
223 /// Every reference to a value of the type `T` must be a multiple of this number.
225 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
227 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
232 /// # #![allow(deprecated)]
235 /// assert_eq!(4, mem::min_align_of::<i32>());
238 #[stable(feature = "rust1", since = "1.0.0")]
239 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
240 pub fn min_align_of
<T
>() -> usize {
241 unsafe { intrinsics::min_align_of::<T>() }
244 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
246 /// Every reference to a value of the type `T` must be a multiple of this number.
248 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
253 /// # #![allow(deprecated)]
256 /// assert_eq!(4, mem::min_align_of_val(&5i32));
259 #[stable(feature = "rust1", since = "1.0.0")]
260 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
261 pub fn min_align_of_val
<T
: ?Sized
>(val
: &T
) -> usize {
262 unsafe { intrinsics::min_align_of_val(val) }
265 /// Returns the [ABI]-required minimum alignment of a type.
267 /// Every reference to a value of the type `T` must be a multiple of this number.
269 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
271 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
278 /// assert_eq!(4, mem::align_of::<i32>());
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn align_of
<T
>() -> usize {
283 unsafe { intrinsics::min_align_of::<T>() }
286 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
288 /// Every reference to a value of the type `T` must be a multiple of this number.
290 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
297 /// assert_eq!(4, mem::align_of_val(&5i32));
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn align_of_val
<T
: ?Sized
>(val
: &T
) -> usize {
302 unsafe { intrinsics::min_align_of_val(val) }
305 /// Returns whether dropping values of type `T` matters.
307 /// This is purely an optimization hint, and may be implemented conservatively.
308 /// For instance, always returning `true` would be a valid implementation of
311 /// Low level implementations of things like collections, which need to manually
312 /// drop their data, should use this function to avoid unnecessarily
313 /// trying to drop all their contents when they are destroyed. This might not
314 /// make a difference in release builds (where a loop that has no side-effects
315 /// is easily detected and eliminated), but is often a big win for debug builds.
317 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
318 /// can be reduced to some small number of drop_in_place calls, using this is
319 /// unnecessary. In particular note that you can drop_in_place a slice, and that
320 /// will do a single needs_drop check for all the values.
322 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
323 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
324 /// values one at a time and should use this API.
329 /// Here's an example of how a collection might make use of needs_drop:
332 /// #![feature(needs_drop)]
333 /// use std::{mem, ptr};
335 /// pub struct MyCollection<T> {
339 /// # impl<T> MyCollection<T> {
340 /// # fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
341 /// # fn free_buffer(&mut self) {}
344 /// impl<T> Drop for MyCollection<T> {
345 /// fn drop(&mut self) {
348 /// if mem::needs_drop::<T>() {
349 /// for x in self.iter_mut() {
350 /// ptr::drop_in_place(x);
353 /// self.free_buffer();
359 #[unstable(feature = "needs_drop", issue = "41890")]
360 pub fn needs_drop
<T
>() -> bool
{
361 unsafe { intrinsics::needs_drop::<T>() }
364 /// Creates a value whose bytes are all zero.
366 /// This has the same effect as allocating space with
367 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
368 /// [FFI] sometimes, but should generally be avoided.
370 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
371 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
372 /// a panic or the end of a scope) before being initialized, then the destructor
373 /// will run on zeroed data, likely leading to [undefined behavior][ub].
375 /// See also the documentation for [`mem::uninitialized`][uninit], which has
376 /// many of the same caveats.
378 /// [uninit]: fn.uninitialized.html
379 /// [FFI]: ../../book/first-edition/ffi.html
380 /// [ub]: ../../reference/behavior-considered-undefined.html
387 /// let x: i32 = unsafe { mem::zeroed() };
388 /// assert_eq!(0, x);
391 #[stable(feature = "rust1", since = "1.0.0")]
392 pub unsafe fn zeroed
<T
>() -> T
{
396 /// Bypasses Rust's normal memory-initialization checks by pretending to
397 /// produce a value of type `T`, while doing nothing at all.
399 /// **This is incredibly dangerous and should not be done lightly. Deeply
400 /// consider initializing your memory with a default value instead.**
402 /// This is useful for [FFI] functions and initializing arrays sometimes,
403 /// but should generally be avoided.
405 /// [FFI]: ../../book/first-edition/ffi.html
407 /// # Undefined behavior
409 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
410 /// uninitialized boolean. For instance, if you branch on the value of such
411 /// a boolean, your program may take one, both, or neither of the branches.
413 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
414 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
415 /// value and its fields if you try to overwrite it in a normal manner. The only way
416 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
417 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
419 /// If the value does implement [`Drop`], it must be initialized before
420 /// it goes out of scope (and therefore would be dropped). Note that this
421 /// includes a `panic` occurring and unwinding the stack suddenly.
425 /// Here's how to safely initialize an array of [`Vec`]s.
431 /// // Only declare the array. This safely leaves it
432 /// // uninitialized in a way that Rust will track for us.
433 /// // However we can't initialize it element-by-element
434 /// // safely, and we can't use the `[value; 1000]`
435 /// // constructor because it only works with `Copy` data.
436 /// let mut data: [Vec<u32>; 1000];
439 /// // So we need to do this to initialize it.
440 /// data = mem::uninitialized();
442 /// // DANGER ZONE: if anything panics or otherwise
443 /// // incorrectly reads the array here, we will have
444 /// // Undefined Behavior.
446 /// // It's ok to mutably iterate the data, since this
447 /// // doesn't involve reading it at all.
448 /// // (ptr and len are statically known for arrays)
449 /// for elem in &mut data[..] {
450 /// // *elem = Vec::new() would try to drop the
451 /// // uninitialized memory at `elem` -- bad!
453 /// // Vec::new doesn't allocate or do really
454 /// // anything. It's only safe to call here
455 /// // because we know it won't panic.
456 /// ptr::write(elem, Vec::new());
459 /// // SAFE ZONE: everything is initialized.
462 /// println!("{:?}", &data[0]);
465 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
466 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
467 /// value that is only [`Clone`], so the following is semantically equivalent and
468 /// vastly less dangerous, as long as you can live with an extra heap
472 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
473 /// println!("{:?}", &data[0]);
476 /// [`Vec`]: ../../std/vec/struct.Vec.html
477 /// [`vec!`]: ../../std/macro.vec.html
478 /// [`Clone`]: ../../std/clone/trait.Clone.html
479 /// [ub]: ../../reference/behavior-considered-undefined.html
480 /// [write]: ../ptr/fn.write.html
481 /// [copy]: ../intrinsics/fn.copy.html
482 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
483 /// [`Drop`]: ../ops/trait.Drop.html
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub unsafe fn uninitialized
<T
>() -> T
{
490 /// Swaps the values at two mutable locations, without deinitializing either one.
500 /// mem::swap(&mut x, &mut y);
502 /// assert_eq!(42, x);
503 /// assert_eq!(5, y);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn swap
<T
>(x
: &mut T
, y
: &mut T
) {
509 ptr
::swap_nonoverlapping(x
, y
, 1);
513 /// Replaces the value at a mutable location with a new one, returning the old value, without
514 /// deinitializing either one.
518 /// A simple example:
523 /// let mut v: Vec<i32> = vec![1, 2];
525 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
526 /// assert_eq!(2, old_v.len());
527 /// assert_eq!(3, v.len());
530 /// `replace` allows consumption of a struct field by replacing it with another value.
531 /// Without `replace` you can run into issues like these:
533 /// ```compile_fail,E0507
534 /// struct Buffer<T> { buf: Vec<T> }
536 /// impl<T> Buffer<T> {
537 /// fn get_and_reset(&mut self) -> Vec<T> {
538 /// // error: cannot move out of dereference of `&mut`-pointer
539 /// let buf = self.buf;
540 /// self.buf = Vec::new();
546 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
547 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
548 /// `self`, allowing it to be returned:
551 /// # #![allow(dead_code)]
554 /// # struct Buffer<T> { buf: Vec<T> }
555 /// impl<T> Buffer<T> {
556 /// fn get_and_reset(&mut self) -> Vec<T> {
557 /// mem::replace(&mut self.buf, Vec::new())
562 /// [`Clone`]: ../../std/clone/trait.Clone.html
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn replace
<T
>(dest
: &mut T
, mut src
: T
) -> T
{
566 swap(dest
, &mut src
);
570 /// Disposes of a value.
572 /// While this does call the argument's implementation of [`Drop`][drop],
573 /// it will not release any borrows, as borrows are based on lexical scope.
575 /// This effectively does nothing for
576 /// [types which implement `Copy`](../../book/first-edition/ownership.html#copy-types),
577 /// e.g. integers. Such values are copied and _then_ moved into the function,
578 /// so the value persists after this function call.
580 /// This function is not magic; it is literally defined as
583 /// pub fn drop<T>(_x: T) { }
586 /// Because `_x` is moved into the function, it is automatically dropped before
587 /// the function returns.
589 /// [drop]: ../ops/trait.Drop.html
596 /// let v = vec![1, 2, 3];
598 /// drop(v); // explicitly drop the vector
601 /// Borrows are based on lexical scope, so this produces an error:
603 /// ```compile_fail,E0502
604 /// let mut v = vec![1, 2, 3];
607 /// drop(x); // explicitly drop the reference, but the borrow still exists
609 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
610 /// // borrowed as immutable
613 /// An inner scope is needed to fix this:
616 /// let mut v = vec![1, 2, 3];
621 /// drop(x); // this is now redundant, as `x` is going out of scope anyway
624 /// v.push(4); // no problems
627 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
628 /// release a [`RefCell`] borrow:
631 /// use std::cell::RefCell;
633 /// let x = RefCell::new(1);
635 /// let mut mutable_borrow = x.borrow_mut();
636 /// *mutable_borrow = 1;
638 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
640 /// let borrow = x.borrow();
641 /// println!("{}", *borrow);
644 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
647 /// #[derive(Copy, Clone)]
652 /// drop(x); // a copy of `x` is moved and dropped
653 /// drop(y); // a copy of `y` is moved and dropped
655 /// println!("x: {}, y: {}", x, y.0); // still available
658 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
659 /// [`Copy`]: ../../std/marker/trait.Copy.html
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn drop
<T
>(_x
: T
) { }
664 /// Interprets `src` as having type `&U`, and then reads `src` without moving
665 /// the contained value.
667 /// This function will unsafely assume the pointer `src` is valid for
668 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
669 /// the `&U`. It will also unsafely create a copy of the contained value instead of
670 /// moving out of `src`.
672 /// It is not a compile-time error if `T` and `U` have different sizes, but it
673 /// is highly encouraged to only invoke this function where `T` and `U` have the
674 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
677 /// [ub]: ../../reference/behavior-considered-undefined.html
678 /// [size_of]: fn.size_of.html
690 /// let foo_slice = [10u8];
693 /// // Copy the data from 'foo_slice' and treat it as a 'Foo'
694 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
695 /// assert_eq!(foo_struct.bar, 10);
697 /// // Modify the copied data
698 /// foo_struct.bar = 20;
699 /// assert_eq!(foo_struct.bar, 20);
702 /// // The contents of 'foo_slice' should not have changed
703 /// assert_eq!(foo_slice, [10]);
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub unsafe fn transmute_copy
<T
, U
>(src
: &T
) -> U
{
708 ptr
::read(src
as *const T
as *const U
)
711 /// Opaque type representing the discriminant of an enum.
713 /// See the `discriminant` function in this module for more information.
714 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
715 pub struct Discriminant
<T
>(u64, PhantomData
<*const T
>);
717 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
719 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
720 impl<T
> Copy
for Discriminant
<T
> {}
722 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
723 impl<T
> clone
::Clone
for Discriminant
<T
> {
724 fn clone(&self) -> Self {
729 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
730 impl<T
> cmp
::PartialEq
for Discriminant
<T
> {
731 fn eq(&self, rhs
: &Self) -> bool
{
736 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
737 impl<T
> cmp
::Eq
for Discriminant
<T
> {}
739 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
740 impl<T
> hash
::Hash
for Discriminant
<T
> {
741 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
746 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
747 impl<T
> fmt
::Debug
for Discriminant
<T
> {
748 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
749 fmt
.debug_tuple("Discriminant")
755 /// Returns a value uniquely identifying the enum variant in `v`.
757 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
758 /// return value is unspecified.
762 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
763 /// of some variant will not change between compilations with the same compiler.
767 /// This can be used to compare enums that carry data, while disregarding
771 /// #![feature(discriminant_value)]
774 /// enum Foo { A(&'static str), B(i32), C(i32) }
776 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
777 /// assert!(mem::discriminant(&Foo::B(1)) == mem::discriminant(&Foo::B(2)));
778 /// assert!(mem::discriminant(&Foo::B(3)) != mem::discriminant(&Foo::C(3)));
780 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
781 pub fn discriminant
<T
>(v
: &T
) -> Discriminant
<T
> {
783 Discriminant(intrinsics
::discriminant_value(v
), PhantomData
)
788 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
790 /// This wrapper is 0-cost.
794 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
798 /// use std::mem::ManuallyDrop;
802 /// struct FruitBox {
803 /// // Immediately clear there’s something non-trivial going on with these fields.
804 /// peach: ManuallyDrop<Peach>,
805 /// melon: Melon, // Field that’s independent of the other two.
806 /// banana: ManuallyDrop<Banana>,
809 /// impl Drop for FruitBox {
810 /// fn drop(&mut self) {
812 /// // Explicit ordering in which field destructors are run specified in the intuitive
813 /// // location – the destructor of the structure containing the fields.
814 /// // Moreover, one can now reorder fields within the struct however much they want.
815 /// ManuallyDrop::drop(&mut self.peach);
816 /// ManuallyDrop::drop(&mut self.banana);
818 /// // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
819 /// // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
823 #[stable(feature = "manually_drop", since = "1.20.0")]
824 #[allow(unions_with_drop_fields)]
825 pub union ManuallyDrop
<T
>{ value: T }
827 impl<T
> ManuallyDrop
<T
> {
828 /// Wrap a value to be manually dropped.
833 /// use std::mem::ManuallyDrop;
834 /// ManuallyDrop::new(Box::new(()));
836 #[stable(feature = "manually_drop", since = "1.20.0")]
838 pub fn new(value
: T
) -> ManuallyDrop
<T
> {
839 ManuallyDrop { value: value }
842 /// Extract the value from the ManuallyDrop container.
847 /// use std::mem::ManuallyDrop;
848 /// let x = ManuallyDrop::new(Box::new(()));
849 /// let _: Box<()> = ManuallyDrop::into_inner(x);
851 #[stable(feature = "manually_drop", since = "1.20.0")]
853 pub fn into_inner(slot
: ManuallyDrop
<T
>) -> T
{
859 /// Manually drops the contained value.
863 /// This function runs the destructor of the contained value and thus the wrapped value
864 /// now represents uninitialized data. It is up to the user of this method to ensure the
865 /// uninitialized data is not actually used.
866 #[stable(feature = "manually_drop", since = "1.20.0")]
868 pub unsafe fn drop(slot
: &mut ManuallyDrop
<T
>) {
869 ptr
::drop_in_place(&mut slot
.value
)
873 #[stable(feature = "manually_drop", since = "1.20.0")]
874 impl<T
> ::ops
::Deref
for ManuallyDrop
<T
> {
877 fn deref(&self) -> &Self::Target
{
884 #[stable(feature = "manually_drop", since = "1.20.0")]
885 impl<T
> ::ops
::DerefMut
for ManuallyDrop
<T
> {
887 fn deref_mut(&mut self) -> &mut Self::Target
{
894 #[stable(feature = "manually_drop", since = "1.20.0")]
895 impl<T
: ::fmt
::Debug
> ::fmt
::Debug
for ManuallyDrop
<T
> {
896 fn fmt(&self, fmt
: &mut ::fmt
::Formatter
) -> ::fmt
::Result
{
898 fmt
.debug_tuple("ManuallyDrop").field(&self.value
).finish()