/// Moves a value out of scope without running drop glue.
pub fn forget<T>(_: T) -> ();
- /// Reinterprets the bits of a value of one type as another type; both types
- /// must have the same size. Neither the original, nor the result, may be an
- /// [invalid value] (../../nomicon/meet-safe-and-unsafe.html).
+ /// Reinterprets the bits of a value of one type as another type.
+ ///
+ /// Both types must have the same size. Neither the original, nor the result,
+ /// may be an [invalid value](../../nomicon/meet-safe-and-unsafe.html).
///
/// `transmute` is semantically equivalent to a bitwise move of one type
- /// into another. It copies the bits from the destination type into the
- /// source type, then forgets the original. It's equivalent to C's `memcpy`
- /// under the hood, just like `transmute_copy`.
+ /// into another. It copies the bits from the source value into the
+ /// destination value, then forgets the original. It's equivalent to C's
+ /// `memcpy` under the hood, just like `transmute_copy`.
///
- /// `transmute` is incredibly unsafe. There are a vast number of ways to
- /// cause undefined behavior with this function. `transmute` should be
+ /// `transmute` is **incredibly** unsafe. There are a vast number of ways to
+ /// cause [undefined behavior][ub] with this function. `transmute` should be
/// the absolute last resort.
///
/// The [nomicon](../../nomicon/transmutes.html) has additional
/// documentation.
///
+ /// [ub]: ../../reference.html#behavior-considered-undefined
+ ///
/// # Examples
///
/// There are a few things that `transmute` is really useful for.
/// assert_eq!(bitpattern, 0x3F800000);
/// ```
///
- /// Turning a pointer into a function pointer:
+ /// Turning a pointer into a function pointer. This is *not* portable to
+ /// machines where function pointers and data pointers have different sizes.
///
/// ```
/// fn foo() -> i32 {
/// assert_eq!(function(), 0);
/// ```
///
- /// Extending a lifetime, or shortening an invariant lifetime; this is
- /// advanced, very unsafe rust:
+ /// Extending a lifetime, or shortening an invariant lifetime. This is
+ /// advanced, very unsafe Rust!
///
/// ```
/// struct R<'a>(&'a i32);
///
/// # Alternatives
///
- /// However, many uses of `transmute` can be achieved through other means.
- /// `transmute` can transform any type into any other, with just the caveat
- /// that they're the same size, and often interesting results occur. Below
- /// are common applications of `transmute` which can be replaced with safe
- /// applications of `as`:
+ /// Don't despair: many uses of `transmute` can be achieved through other means.
+ /// Below are common applications of `transmute` which can be replaced with safer
+ /// constructs.
///
/// Turning a pointer into a `usize`:
///
/// let ptr_num_transmute = unsafe {
/// std::mem::transmute::<&i32, usize>(ptr)
/// };
+ ///
/// // Use an `as` cast instead
/// let ptr_num_cast = ptr as *const i32 as usize;
/// ```
/// let ref_transmuted = unsafe {
/// std::mem::transmute::<*mut i32, &mut i32>(ptr)
/// };
+ ///
/// // Use a reborrow instead
/// let ref_casted = unsafe { &mut *ptr };
/// ```
/// let val_transmuted = unsafe {
/// std::mem::transmute::<&mut i32, &mut u32>(ptr)
/// };
+ ///
/// // Now, put together `as` and reborrowing - note the chaining of `as`
/// // `as` is not transitive
/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
/// // this is not a good way to do this.
/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
/// assert_eq!(slice, &[82, 117, 115, 116]);
+ ///
/// // You could use `str::as_bytes`
/// let slice = "Rust".as_bytes();
/// assert_eq!(slice, &[82, 117, 115, 116]);
+ ///
/// // Or, just use a byte string, if you have control over the string
/// // literal
/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
/// ```
/// let store = [0, 1, 2, 3];
/// let mut v_orig = store.iter().collect::<Vec<&i32>>();
+ ///
/// // Using transmute: this is Undefined Behavior, and a bad idea.
/// // However, it is no-copy.
/// let v_transmuted = unsafe {
/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(
/// v_orig.clone())
/// };
+ ///
/// // This is the suggested, safe way.
- /// // It does copy the entire Vector, though, into a new array.
+ /// // It does copy the entire vector, though, into a new array.
/// let v_collected = v_orig.clone()
/// .into_iter()
/// .map(|r| Some(r))
/// .collect::<Vec<Option<&i32>>>();
+ ///
/// // The no-copy, unsafe way, still using transmute, but not UB.
/// // This is equivalent to the original, but safer, and reuses the
/// // same Vec internals. Therefore the new inner type must have the
///
/// ```
/// use std::{slice, mem};
+ ///
/// // There are multiple ways to do this; and there are multiple problems
/// // with the following, transmute, way.
/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
+ ///
/// // This gets rid of the typesafety problems; `&mut *` will *only* give
/// // you an `&mut T` from an `&mut T` or `*mut T`.
/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
+ ///
/// // This is how the standard library does it. This is the best method, if
/// // you need to do something like this
/// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
#[stable(feature = "rust1", since = "1.0.0")]
pub use intrinsics::transmute;
-/// Leaks a value into the void, consuming ownership and never running its
-/// destructor.
+/// Leaks a value: takes ownership and "forgets" about the value **without running
+/// its destructor**.
///
-/// This function will take ownership of its argument, but is distinct from the
-/// `mem::drop` function in that it **does not run the destructor**, leaking the
-/// value and any resources that it owns.
+/// Any resources the value manages, such as heap memory or a file handle, will linger
+/// forever in an unreachable state.
///
-/// There's only a few reasons to use this function. They mainly come
-/// up in unsafe code or FFI code.
-///
-/// * You have an uninitialized value, perhaps for performance reasons, and
-/// need to prevent the destructor from running on it.
-/// * You have two copies of a value (like when writing something like
-/// [`mem::swap`][swap]), but need the destructor to only run once to
-/// prevent a double `free`.
-/// * Transferring resources across [FFI][ffi] boundaries.
-///
-/// [swap]: fn.swap.html
-/// [ffi]: ../../book/ffi.html
+/// If you want to dispose of a value properly, running its destructor, see
+/// [`mem::drop`][drop].
///
/// # Safety
///
-/// This function is not marked as `unsafe` as Rust does not guarantee that the
-/// `Drop` implementation for a value will always run. Note, however, that
-/// leaking resources such as memory or I/O objects is likely not desired, so
-/// this function is only recommended for specialized use cases.
-///
-/// The safety of this function implies that when writing `unsafe` code
-/// yourself care must be taken when leveraging a destructor that is required to
-/// run to preserve memory safety. There are known situations where the
-/// destructor may not run (such as if ownership of the object with the
-/// destructor is returned) which must be taken into account.
+/// `forget` is not marked as `unsafe`, because Rust's safety guarantees
+/// do not include a guarantee that destructors will always run. For example,
+/// a program can create a reference cycle using [`Rc`][rc], or call
+/// [`process:exit`][exit] to exit without running destructors. Thus, allowing
+/// `mem::forget` from safe code does not fundamentally change Rust's safety
+/// guarantees.
///
-/// # Other forms of Leakage
+/// That said, leaking resources such as memory or I/O objects is usually undesirable,
+/// so `forget` is only recommended for specialized use cases like those shown below.
///
-/// It's important to point out that this function is not the only method by
-/// which a value can be leaked in safe Rust code. Other known sources of
-/// leakage are:
+/// Because forgetting a value is allowed, any `unsafe` code you write must
+/// allow for this possibility. You cannot return a value and expect that the
+/// caller will necessarily run the value's destructor.
///
-/// * `Rc` and `Arc` cycles
-/// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
-/// * Panicking destructors are likely to leak local resources
+/// [rc]: ../../std/rc/struct.Rc.html
+/// [exit]: ../../std/process/fn.exit.html
///
-/// # Example
+/// # Examples
///
/// Leak some heap memory by never deallocating it:
///
-/// ```rust
+/// ```
/// use std::mem;
///
/// let heap_memory = Box::new(3);
///
/// Leak an I/O object, never closing the file:
///
-/// ```rust,no_run
+/// ```no_run
/// use std::mem;
/// use std::fs::File;
///
/// mem::forget(file);
/// ```
///
-/// The `mem::swap` function uses `mem::forget` to good effect:
+/// The practical use cases for `forget` are rather specialized and mainly come
+/// up in unsafe or FFI code.
+///
+/// ## Use case 1
+///
+/// You have created an uninitialized value using [`mem::uninitialized`][uninit].
+/// You must either initialize or `forget` it on every computation path before
+/// Rust drops it automatically, like at the end of a scope or after a panic.
+/// Running the destructor on an uninitialized value would be [undefined behavior][ub].
+///
+/// ```
+/// use std::mem;
+/// use std::ptr;
+///
+/// # let some_condition = false;
+/// unsafe {
+/// let mut uninit_vec: Vec<u32> = mem::uninitialized();
+///
+/// if some_condition {
+/// // Initialize the variable.
+/// ptr::write(&mut uninit_vec, Vec::new());
+/// } else {
+/// // Forget the uninitialized value so its destructor doesn't run.
+/// mem::forget(uninit_vec);
+/// }
+/// }
+/// ```
+///
+/// ## Use case 2
+///
+/// You have duplicated the bytes making up a value, without doing a proper
+/// [`Clone`][clone]. You need the value's destructor to run only once,
+/// because a double `free` is undefined behavior.
///
-/// ```rust
+/// An example is the definition of [`mem::swap`][swap] in this module:
+///
+/// ```
/// use std::mem;
/// use std::ptr;
///
/// }
/// }
/// ```
+///
+/// ## Use case 3
+///
+/// You are transferring ownership across a [FFI] boundary to code written in
+/// another language. You need to `forget` the value on the Rust side because Rust
+/// code is no longer responsible for it.
+///
+/// ```no_run
+/// use std::mem;
+///
+/// extern "C" {
+/// fn my_c_function(x: *const u32);
+/// }
+///
+/// let x: Box<u32> = Box::new(3);
+///
+/// // Transfer ownership into C code.
+/// unsafe {
+/// my_c_function(&*x);
+/// }
+/// mem::forget(x);
+/// ```
+///
+/// In this case, C code must call back into Rust to free the object. Calling C's `free`
+/// function on a [`Box`][box] is *not* safe! Also, `Box` provides an [`into_raw`][into_raw]
+/// method which is the preferred way to do this in practice.
+///
+/// [drop]: fn.drop.html
+/// [uninit]: fn.uninitialized.html
+/// [clone]: ../clone/trait.Clone.html
+/// [swap]: fn.swap.html
+/// [FFI]: ../../book/ffi.html
+/// [box]: ../../std/boxed/struct.Box.html
+/// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
+/// [ub]: ../../reference.html#behavior-considered-undefined
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn forget<T>(t: T) {
unsafe { intrinsics::size_of::<T>() }
}
-/// Returns the size of the given value in bytes.
+/// Returns the size of the pointed-to value in bytes.
+///
+/// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
+/// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
+/// then `size_of_val` can be used to get the dynamically-known size.
+///
+/// [slice]: ../../std/primitive.slice.html
+/// [trait object]: ../../book/trait-objects.html
///
/// # Examples
///
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
+///
+/// let x: [u8; 13] = [0; 13];
+/// let y: &[u8] = &x;
+/// assert_eq!(13, mem::size_of_val(y));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
unsafe { intrinsics::size_of_val(val) }
}
-/// Returns the ABI-required minimum alignment of a type
+/// Returns the [ABI]-required minimum alignment of a type.
+///
+/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
+/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
+///
/// # Examples
///
/// ```
unsafe { intrinsics::min_align_of::<T>() }
}
-/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
+/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
+///
+/// Every valid address of a value of the type `T` must be a multiple of this number.
+///
+/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
unsafe { intrinsics::min_align_of_val(val) }
}
-/// Returns the alignment in memory for a type.
+/// Returns the [ABI]-required minimum alignment of a type.
+///
+/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
+/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
+///
/// # Examples
///
/// ```
unsafe { intrinsics::min_align_of::<T>() }
}
-/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
+/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
+///
+/// Every valid address of a value of the type `T` must be a multiple of this number.
+///
+/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
unsafe { intrinsics::min_align_of_val(val) }
}
-/// Creates a value initialized to zero.
+/// Creates a value whose bytes are all zero.
+///
+/// This has the same effect as allocating space with
+/// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
+/// [FFI] sometimes, but should generally be avoided.
///
-/// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
-/// operation).
+/// There is no guarantee that an all-zero byte-pattern represents a valid value of
+/// some type `T`. If `T` has a destructor and the value is destroyed (due to
+/// a panic or the end of a scope) before being initialized, then the destructor
+/// will run on zeroed data, likely leading to [undefined behavior][ub].
///
-/// Care must be taken when using this function, if the type `T` has a destructor and the value
-/// falls out of scope (due to unwinding or returning) before being initialized, then the
-/// destructor will run on zeroed data, likely leading to crashes.
+/// See also the documentation for [`mem::uninitialized`][uninit], which has
+/// many of the same caveats.
///
-/// This is useful for FFI functions sometimes, but should generally be avoided.
+/// [uninit]: fn.uninitialized.html
+/// [FFI]: ../../book/ffi.html
+/// [ub]: ../../reference.html#behavior-considered-undefined
///
/// # Examples
///
/// use std::mem;
///
/// let x: i32 = unsafe { mem::zeroed() };
+/// assert_eq!(0, x);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
}
/// Bypasses Rust's normal memory-initialization checks by pretending to
-/// produce a value of type T, while doing nothing at all.
+/// produce a value of type `T`, while doing nothing at all.
///
/// **This is incredibly dangerous, and should not be done lightly. Deeply
/// consider initializing your memory with a default value instead.**
///
-/// This is useful for FFI functions and initializing arrays sometimes,
+/// This is useful for [FFI] functions and initializing arrays sometimes,
/// but should generally be avoided.
///
-/// # Undefined Behavior
+/// [FFI]: ../../book/ffi.html
///
-/// It is Undefined Behavior to read uninitialized memory. Even just an
+/// # Undefined behavior
+///
+/// It is [undefined behavior][ub] to read uninitialized memory, even just an
/// uninitialized boolean. For instance, if you branch on the value of such
-/// a boolean your program may take one, both, or neither of the branches.
+/// a boolean, your program may take one, both, or neither of the branches.
///
-/// Note that this often also includes *writing* to the uninitialized value.
-/// Rust believes the value is initialized, and will therefore try to Drop
-/// the uninitialized value and its fields if you try to overwrite the memory
-/// in a normal manner. The only way to safely initialize an arbitrary
-/// uninitialized value is with one of the `ptr` functions: `write`, `copy`, or
-/// `copy_nonoverlapping`. This isn't necessary if `T` is a primitive
-/// or otherwise only contains types that don't implement Drop.
+/// Writing to the uninitialized value is similarly dangerous. Rust believes the
+/// value is initialized, and will therefore try to [`Drop`][drop] the uninitialized
+/// value and its fields if you try to overwrite it in a normal manner. The only way
+/// to safely initialize an uninitialized value is with [`ptr::write`][write],
+/// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
///
-/// If this value *does* need some kind of Drop, it must be initialized before
+/// If the value does implement `Drop`, it must be initialized before
/// it goes out of scope (and therefore would be dropped). Note that this
/// includes a `panic` occurring and unwinding the stack suddenly.
///
+/// [ub]: ../../reference.html#behavior-considered-undefined
+/// [write]: ../ptr/fn.write.html
+/// [copy]: ../intrinsics/fn.copy.html
+/// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
+/// [drop]: ../ops/trait.Drop.html
+///
/// # Examples
///
/// Here's how to safely initialize an array of `Vec`s.
/// println!("{:?}", &data[0]);
/// ```
///
-/// This example emphasizes exactly how delicate and dangerous doing this is.
-/// Note that the `vec!` macro *does* let you initialize every element with a
+/// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
+/// can be. Note that the `vec!` macro *does* let you initialize every element with a
/// value that is only `Clone`, so the following is semantically equivalent and
/// vastly less dangerous, as long as you can live with an extra heap
/// allocation:
intrinsics::uninit()
}
-/// Swap the values at two mutable locations of the same type, without deinitializing or copying
-/// either one.
+/// Swaps the values at two mutable locations, without deinitializing either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
-/// let x = &mut 5;
-/// let y = &mut 42;
+/// let mut x = 5;
+/// let mut y = 42;
///
-/// mem::swap(x, y);
+/// mem::swap(&mut x, &mut y);
///
-/// assert_eq!(42, *x);
-/// assert_eq!(5, *y);
+/// assert_eq!(42, x);
+/// assert_eq!(5, y);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
}
/// Replaces the value at a mutable location with a new one, returning the old value, without
-/// deinitializing or copying either one.
-///
-/// This is primarily used for transferring and swapping ownership of a value in a mutable
-/// location.
+/// deinitializing either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
-/// let mut v: Vec<i32> = Vec::new();
+/// let mut v: Vec<i32> = vec![1, 2];
///
-/// mem::replace(&mut v, Vec::new());
+/// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
+/// assert_eq!(2, old_v.len());
+/// assert_eq!(3, v.len());
/// ```
///
-/// This function allows consumption of one field of a struct by replacing it with another value.
-/// The normal approach doesn't always work:
+/// `replace` allows consumption of a struct field by replacing it with another value.
+/// Without `replace` you can run into issues like these:
///
-/// ```rust,ignore
+/// ```ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// ```
/// # #![allow(dead_code)]
/// use std::mem;
+///
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// Disposes of a value.
///
-/// While this does call the argument's implementation of `Drop`, it will not
-/// release any borrows, as borrows are based on lexical scope.
+/// While this does call the argument's implementation of [`Drop`][drop],
+/// it will not release any borrows, as borrows are based on lexical scope.
///
/// This effectively does nothing for
/// [types which implement `Copy`](../../book/ownership.html#copy-types),
/// e.g. integers. Such values are copied and _then_ moved into the function,
/// so the value persists after this function call.
///
+/// This function is not magic; it is literally defined as
+///
+/// ```
+/// pub fn drop<T>(_x: T) { }
+/// ```
+///
+/// Because `_x` is moved into the function, it is automatically dropped before
+/// the function returns.
+///
+/// [drop]: ../ops/trait.Drop.html
+///
/// # Examples
///
/// Basic usage:
/// v.push(4); // no problems
/// ```
///
-/// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
-/// seemingly release a borrow of one:
+/// Since `RefCell` enforces the borrow rules at runtime, `drop` can
+/// release a `RefCell` borrow:
///
/// ```
/// use std::cell::RefCell;
/// println!("{}", *borrow);
/// ```
///
-/// Integers and other types implementing `Copy` are unaffected by `drop()`
+/// Integers and other types implementing `Copy` are unaffected by `drop`.
///
/// ```
/// #[derive(Copy, Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn drop<T>(_x: T) { }
-/// Interprets `src` as `&U`, and then reads `src` without moving the contained
-/// value.
+/// Interprets `src` as having type `&U`, and then reads `src` without moving
+/// the contained value.
///
/// This function will unsafely assume the pointer `src` is valid for
-/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
-/// will also unsafely create a copy of the contained value instead of moving
-/// out of `src`.
+/// [`size_of::<U>()`][size_of] bytes by transmuting `&T` to `&U` and then reading
+/// the `&U`. It will also unsafely create a copy of the contained value instead of
+/// moving out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
-/// same size. This function triggers undefined behavior if `U` is larger than
+/// same size. This function triggers [undefined behavior][ub] if `U` is larger than
/// `T`.
///
+/// [ub]: ../../reference.html#behavior-considered-undefined
+/// [size_of]: fn.size_of.html
+///
/// # Examples
///
/// ```