mem.rs 7.3 KB
Newer Older
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12 13 14
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
15

16
use intrinsics;
17
use ptr;
18

19 20
pub use intrinsics::transmute;

21 22 23 24 25 26 27 28 29 30
/// Moves a thing into the void.
///
/// The forget function will take ownership of the provided value but neglect
/// to run any required cleanup or memory management operations on it.
///
/// This function is the unsafe version of the `drop` function because it does
/// not run any destructors.
#[stable]
pub use intrinsics::forget;

31
/// Returns the size of a type in bytes.
32
#[inline]
A
Alex Crichton 已提交
33
#[stable]
34 35 36 37
pub fn size_of<T>() -> uint {
    unsafe { intrinsics::size_of::<T>() }
}

38
/// Returns the size of the type that `_val` points to in bytes.
39
#[inline]
40
#[stable]
41 42 43 44
pub fn size_of_val<T>(_val: &T) -> uint {
    size_of::<T>()
}

45 46 47 48
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller
/// than the preferred alignment.
49
#[inline]
A
Alex Crichton 已提交
50
#[stable]
51 52 53 54 55 56 57
pub fn min_align_of<T>() -> uint {
    unsafe { intrinsics::min_align_of::<T>() }
}

/// Returns the ABI-required minimum alignment of the type of the value that
/// `_val` points to
#[inline]
58
#[stable]
59 60 61 62
pub fn min_align_of_val<T>(_val: &T) -> uint {
    min_align_of::<T>()
}

A
Alex Crichton 已提交
63 64 65 66 67
/// Returns the alignment in memory for a type.
///
/// This function will return the alignment, in bytes, of a type in memory. If
/// the alignment returned is adhered to, then the type is guaranteed to
/// function properly.
68
#[inline]
A
Alex Crichton 已提交
69 70 71 72 73 74
#[stable]
pub fn align_of<T>() -> uint {
    // We use the preferred alignment as the default alignment for a type. This
    // appears to be what clang migrated towards as well:
    //
    // http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
75 76 77
    unsafe { intrinsics::pref_align_of::<T>() }
}

A
Alex Crichton 已提交
78 79 80 81 82
/// Returns the alignment of the type of the value that `_val` points to.
///
/// This is similar to `align_of`, but function will properly handle types such
/// as trait objects (in the future), returning the alignment for an arbitrary
/// value at runtime.
83
#[inline]
84
#[stable]
A
Alex Crichton 已提交
85 86
pub fn align_of_val<T>(_val: &T) -> uint {
    align_of::<T>()
87 88
}

89 90
/// Create a value initialized to zero.
///
A
Alex Gaynor 已提交
91
/// This function is similar to allocating space for a local variable and
A
Alex Crichton 已提交
92 93 94 95 96 97 98 99
/// zeroing it out (an unsafe operation).
///
/// 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.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
100
#[inline]
101
#[stable]
A
Alex Crichton 已提交
102
pub unsafe fn zeroed<T>() -> T {
103 104 105 106
    intrinsics::init()
}

/// Create an uninitialized value.
A
Alex Crichton 已提交
107 108 109 110 111 112 113
///
/// 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 uninitialized
/// data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
114
#[inline]
115 116 117 118 119
#[stable]
pub unsafe fn uninitialized<T>() -> T {
    intrinsics::uninit()
}

B
Brendan Zabarauskas 已提交
120 121
/// Swap the values at two mutable locations of the same type, without
/// deinitialising or copying either one.
122
#[inline]
A
Alex Crichton 已提交
123
#[stable]
124 125 126
pub fn swap<T>(x: &mut T, y: &mut T) {
    unsafe {
        // Give ourselves some scratch space to work with
127
        let mut t: T = uninitialized();
128 129 130 131 132 133

        // Perform the swap, `&mut` pointers never alias
        ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
        ptr::copy_nonoverlapping_memory(x, &*y, 1);
        ptr::copy_nonoverlapping_memory(y, &t, 1);

A
aochagavia 已提交
134
        // y and t now point to the same thing, but we need to completely forget `t`
135
        // because it's no longer relevant.
A
Alex Crichton 已提交
136
        forget(t);
137 138 139
    }
}

B
Brendan Zabarauskas 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
/// Replace the value at a mutable location with a new one, returning the old
/// value, without deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value
/// in a mutable location. For example, this function allows consumption of
/// one field of a struct by replacing it with another value. The normal approach
/// doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
///     fn get_and_reset(&mut self) -> Vec<T> {
///         // error: cannot move out of dereference of `&mut`-pointer
///         let buf = self.buf;
///         self.buf = Vec::new();
///         buf
///     }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even
/// clone and reset `self.buf`. But `replace` can be used to disassociate
/// the original value of `self.buf` from `self`, allowing it to be returned:
///
/// ```rust
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
///     fn get_and_reset(&mut self) -> Vec<T> {
///         use std::mem::replace;
///         replace(&mut self.buf, Vec::new())
///     }
/// }
/// ```
174
#[inline]
A
Alex Crichton 已提交
175
#[stable]
176 177 178 179 180 181
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
    swap(dest, &mut src);
    src
}

/// Disposes of a value.
A
Alex Crichton 已提交
182 183 184 185 186 187 188 189 190
///
/// This function can be used to destroy any value by allowing `drop` to take
/// ownership of its argument.
///
/// # Example
///
/// ```
/// use std::cell::RefCell;
///
191
/// let x = RefCell::new(1i);
A
Alex Crichton 已提交
192 193 194 195 196 197 198 199
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
200
#[inline]
A
Alex Crichton 已提交
201
#[stable]
202 203
pub fn drop<T>(_x: T) { }

A
Alex Crichton 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
/// Interprets `src` as `&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`.
///
/// 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
/// `T`.
#[inline]
#[stable]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
219
    ptr::read(src as *const T as *const U)
A
Alex Crichton 已提交
220 221 222 223 224 225
}

/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
              questionable utility"]
226
pub unsafe fn copy_lifetime<'a, S, T:'a>(_ptr: &'a S, ptr: &T) -> &'a T {
A
Alex Crichton 已提交
227 228 229 230 231 232 233
    transmute(ptr)
}

/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable = "this function may be removed in the future due to its \
              questionable utility"]
234
pub unsafe fn copy_mut_lifetime<'a, S, T:'a>(_ptr: &'a mut S,
A
Alex Crichton 已提交
235 236 237
                                          ptr: &mut T) -> &'a mut T {
    transmute(ptr)
}