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")]
22 #[stable(feature = "rust1", since = "1.0.0")]
23 pub use intrinsics::transmute;
25 /// Leaks a value into the void, consuming ownership and never running its
28 /// This function will take ownership of its argument, but is distinct from the
29 /// `mem::drop` function in that it **does not run the destructor**, leaking the
30 /// value and any resources that it owns.
34 /// This function is not marked as `unsafe` as Rust does not guarantee that the
35 /// `Drop` implementation for a value will always run. Note, however, that
36 /// leaking resources such as memory or I/O objects is likely not desired, so
37 /// this function is only recommended for specialized use cases.
39 /// The safety of this function implies that when writing `unsafe` code
40 /// yourself care must be taken when leveraging a destructor that is required to
41 /// run to preserve memory safety. There are known situations where the
42 /// destructor may not run (such as if ownership of the object with the
43 /// destructor is returned) which must be taken into account.
45 /// # Other forms of Leakage
47 /// It's important to point out that this function is not the only method by
48 /// which a value can be leaked in safe Rust code. Other known sources of
51 /// * `Rc` and `Arc` cycles
52 /// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
53 /// * Panicking destructors are likely to leak local resources
57 /// There's only a few reasons to use this function. They mainly come
58 /// up in unsafe code or FFI code.
60 /// * You have an uninitialized value, perhaps for performance reasons, and
61 /// need to prevent the destructor from running on it.
62 /// * You have two copies of a value (like `std::mem::swap`), but need the
63 /// destructor to only run once to prevent a double free.
64 /// * Transferring resources across FFI boundries.
68 /// Leak some heap memory by never deallocating it.
73 /// let heap_memory = Box::new(3);
74 /// mem::forget(heap_memory);
77 /// Leak an I/O object, never closing the file.
81 /// use std::fs::File;
83 /// let file = File::open("foo.txt").unwrap();
84 /// mem::forget(file);
87 /// The swap function uses forget to good effect.
93 /// fn swap<T>(x: &mut T, y: &mut T) {
95 /// // Give ourselves some scratch space to work with
96 /// let mut t: T = mem::uninitialized();
98 /// // Perform the swap, `&mut` pointers never alias
99 /// ptr::copy_nonoverlapping(&*x, &mut t, 1);
100 /// ptr::copy_nonoverlapping(&*y, x, 1);
101 /// ptr::copy_nonoverlapping(&t, y, 1);
103 /// // y and t now point to the same thing, but we need to completely
104 /// // forget `t` because we do not want to run the destructor for `T`
105 /// // on its value, which is still owned somewhere outside this function.
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub fn forget<T>(t: T) {
112 unsafe { intrinsics::forget(t) }
115 /// Returns the size of a type in bytes.
122 /// assert_eq!(4, mem::size_of::<i32>());
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub fn size_of<T>() -> usize {
127 unsafe { intrinsics::size_of::<T>() }
130 /// Returns the size of the type that `val` points to in bytes.
137 /// assert_eq!(4, mem::size_of_val(&5i32));
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
142 unsafe { intrinsics::size_of_val(val) }
145 /// Returns the ABI-required minimum alignment of a type
147 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
154 /// assert_eq!(4, mem::min_align_of::<i32>());
157 #[stable(feature = "rust1", since = "1.0.0")]
158 #[deprecated(reason = "use `align_of` instead", since = "1.2.0")]
159 pub fn min_align_of<T>() -> usize {
160 unsafe { intrinsics::min_align_of::<T>() }
163 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
170 /// assert_eq!(4, mem::min_align_of_val(&5i32));
173 #[stable(feature = "rust1", since = "1.0.0")]
174 #[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
175 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
176 unsafe { intrinsics::min_align_of_val(val) }
179 /// Returns the alignment in memory for a type.
181 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
188 /// assert_eq!(4, mem::align_of::<i32>());
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn align_of<T>() -> usize {
193 unsafe { intrinsics::min_align_of::<T>() }
196 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
203 /// assert_eq!(4, mem::align_of_val(&5i32));
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
208 unsafe { intrinsics::min_align_of_val(val) }
211 /// Creates a value initialized to zero.
213 /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
216 /// Care must be taken when using this function, if the type `T` has a destructor and the value
217 /// falls out of scope (due to unwinding or returning) before being initialized, then the
218 /// destructor will run on zeroed data, likely leading to crashes.
220 /// This is useful for FFI functions sometimes, but should generally be avoided.
227 /// let x: i32 = unsafe { mem::zeroed() };
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub unsafe fn zeroed<T>() -> T {
235 /// Creates a value initialized to an unspecified series of bytes.
237 /// The byte sequence usually indicates that the value at the memory
238 /// in question has been dropped. Thus, *if* T carries a drop flag,
239 /// any associated destructor will not be run when the value falls out
242 /// Some code at one time used the `zeroed` function above to
243 /// accomplish this goal.
245 /// This function is expected to be deprecated with the transition
246 /// to non-zeroing drop.
248 #[unstable(feature = "filling_drop")]
249 pub unsafe fn dropped<T>() -> T {
251 unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
256 /// Creates an uninitialized value.
258 /// Care must be taken when using this function, if the type `T` has a destructor and the value
259 /// falls out of scope (due to unwinding or returning) before being initialized, then the
260 /// destructor will run on uninitialized data, likely leading to crashes.
262 /// This is useful for FFI functions sometimes, but should generally be avoided.
269 /// let x: i32 = unsafe { mem::uninitialized() };
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub unsafe fn uninitialized<T>() -> T {
277 /// Swap the values at two mutable locations of the same type, without deinitialising or copying
290 /// assert_eq!(42, *x);
291 /// assert_eq!(5, *y);
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn swap<T>(x: &mut T, y: &mut T) {
297 // Give ourselves some scratch space to work with
298 let mut t: T = uninitialized();
300 // Perform the swap, `&mut` pointers never alias
301 ptr::copy_nonoverlapping(&*x, &mut t, 1);
302 ptr::copy_nonoverlapping(&*y, x, 1);
303 ptr::copy_nonoverlapping(&t, y, 1);
305 // y and t now point to the same thing, but we need to completely
306 // forget `t` because we do not want to run the destructor for `T`
307 // on its value, which is still owned somewhere outside this function.
312 /// Replaces the value at a mutable location with a new one, returning the old value, without
313 /// deinitialising or copying either one.
315 /// This is primarily used for transferring and swapping ownership of a value in a mutable
320 /// A simple example:
325 /// let mut v: Vec<i32> = Vec::new();
327 /// mem::replace(&mut v, Vec::new());
330 /// This function allows consumption of one field of a struct by replacing it with another value.
331 /// The normal approach doesn't always work:
334 /// struct Buffer<T> { buf: Vec<T> }
336 /// impl<T> Buffer<T> {
337 /// fn get_and_reset(&mut self) -> Vec<T> {
338 /// // error: cannot move out of dereference of `&mut`-pointer
339 /// let buf = self.buf;
340 /// self.buf = Vec::new();
346 /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
347 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
348 /// `self`, allowing it to be returned:
352 /// # struct Buffer<T> { buf: Vec<T> }
353 /// impl<T> Buffer<T> {
354 /// fn get_and_reset(&mut self) -> Vec<T> {
355 /// mem::replace(&mut self.buf, Vec::new())
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
362 swap(dest, &mut src);
366 /// Disposes of a value.
368 /// While this does call the argument's implementation of `Drop`, it will not
369 /// release any borrows, as borrows are based on lexical scope.
376 /// let v = vec![1, 2, 3];
378 /// drop(v); // explicitly drop the vector
381 /// Borrows are based on lexical scope, so this produces an error:
384 /// let mut v = vec![1, 2, 3];
387 /// drop(x); // explicitly drop the reference, but the borrow still exists
389 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
390 /// // borrowed as immutable
393 /// An inner scope is needed to fix this:
396 /// let mut v = vec![1, 2, 3];
401 /// drop(x); // this is now redundant, as `x` is going out of scope anyway
404 /// v.push(4); // no problems
407 /// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
408 /// seemingly release a borrow of one:
411 /// use std::cell::RefCell;
413 /// let x = RefCell::new(1);
415 /// let mut mutable_borrow = x.borrow_mut();
416 /// *mutable_borrow = 1;
418 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
420 /// let borrow = x.borrow();
421 /// println!("{}", *borrow);
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn drop<T>(_x: T) { }
427 macro_rules! repeat_u8_as_u32 {
428 ($name:expr) => { (($name as u32) << 24 |
429 ($name as u32) << 16 |
430 ($name as u32) << 8 |
433 macro_rules! repeat_u8_as_u64 {
434 ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
435 (repeat_u8_as_u32!($name) as u64)) }
438 // NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
440 // In particular, the POST_DROP_U8 marker must never equal the
441 // DTOR_NEEDED_U8 marker.
443 // For a while pnkfelix was using 0xc1 here.
444 // But having the sign bit set is a pain, so 0x1d is probably better.
446 // And of course, 0x00 brings back the old world of zero'ing on drop.
447 #[unstable(feature = "filling_drop")]
448 #[allow(missing_docs)]
449 pub const POST_DROP_U8: u8 = 0x1d;
450 #[unstable(feature = "filling_drop")]
451 #[allow(missing_docs)]
452 pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
453 #[unstable(feature = "filling_drop")]
454 #[allow(missing_docs)]
455 pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
457 #[cfg(target_pointer_width = "32")]
458 #[unstable(feature = "filling_drop")]
459 #[allow(missing_docs)]
460 pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
461 #[cfg(target_pointer_width = "64")]
462 #[unstable(feature = "filling_drop")]
463 #[allow(missing_docs)]
464 pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
466 /// Interprets `src` as `&U`, and then reads `src` without moving the contained
469 /// This function will unsafely assume the pointer `src` is valid for
470 /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
471 /// will also unsafely create a copy of the contained value instead of moving
474 /// It is not a compile-time error if `T` and `U` have different sizes, but it
475 /// is highly encouraged to only invoke this function where `T` and `U` have the
476 /// same size. This function triggers undefined behavior if `U` is larger than
484 /// let one = unsafe { mem::transmute_copy(&1) };
486 /// assert_eq!(1, one);
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
491 // FIXME(#23542) Replace with type ascription.
492 #![allow(trivial_casts)]
493 ptr::read(src as *const T as *const U)
496 /// Transforms lifetime of the second pointer to match the first.
498 #[unstable(feature = "copy_lifetime",
499 reason = "this function may be removed in the future due to its \
500 questionable utility")]
501 #[deprecated(since = "1.2.0",
502 reason = "unclear that this function buys more safety and \
503 lifetimes are generally not handled as such in unsafe \
505 pub unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
510 /// Transforms lifetime of the second mutable pointer to match the first.
512 #[unstable(feature = "copy_lifetime",
513 reason = "this function may be removed in the future due to its \
514 questionable utility")]
515 #[deprecated(since = "1.2.0",
516 reason = "unclear that this function buys more safety and \
517 lifetimes are generally not handled as such in unsafe \
519 pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,