]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
Do not use entropy during gen_weighted_bool(1)
[rust.git] / src / libcore / mem.rs
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.
4 //
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.
10
11 //! Basic functions for dealing with memory
12 //!
13 //! This module contains functions for querying the size and alignment of
14 //! types, initializing and manipulating memory.
15
16 #![stable]
17
18 use kinds::Sized;
19 use intrinsics;
20 use ptr;
21
22 #[stable]
23 pub use intrinsics::transmute;
24
25 /// Moves a thing into the void.
26 ///
27 /// The forget function will take ownership of the provided value but neglect
28 /// to run any required cleanup or memory management operations on it.
29 ///
30 /// This function is the unsafe version of the `drop` function because it does
31 /// not run any destructors.
32 #[stable]
33 pub use intrinsics::forget;
34
35 /// Returns the size of a type in bytes.
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// use std::mem;
41 ///
42 /// assert_eq!(4, mem::size_of::<i32>());
43 /// ```
44 #[inline]
45 #[stable]
46 pub fn size_of<T>() -> uint {
47     unsafe { intrinsics::size_of::<T>() }
48 }
49
50 /// Returns the size of the type that `_val` points to in bytes.
51 ///
52 /// # Examples
53 ///
54 /// ```
55 /// use std::mem;
56 ///
57 /// assert_eq!(4, mem::size_of_val(&5i32));
58 /// ```
59 #[inline]
60 #[stable]
61 pub fn size_of_val<T>(_val: &T) -> uint {
62     size_of::<T>()
63 }
64
65 /// Returns the ABI-required minimum alignment of a type
66 ///
67 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// use std::mem;
73 ///
74 /// assert_eq!(4, mem::min_align_of::<i32>());
75 /// ```
76 #[inline]
77 #[stable]
78 pub fn min_align_of<T>() -> uint {
79     unsafe { intrinsics::min_align_of::<T>() }
80 }
81
82 /// Returns the ABI-required minimum alignment of the type of the value that `_val` points to
83 ///
84 /// # Examples
85 ///
86 /// ```
87 /// use std::mem;
88 ///
89 /// assert_eq!(4, mem::min_align_of_val(&5i32));
90 /// ```
91 #[inline]
92 #[stable]
93 pub fn min_align_of_val<T>(_val: &T) -> uint {
94     min_align_of::<T>()
95 }
96
97 /// Returns the alignment in memory for a type.
98 ///
99 /// This function will return the alignment, in bytes, of a type in memory. If the alignment
100 /// returned is adhered to, then the type is guaranteed to function properly.
101 ///
102 /// # Examples
103 ///
104 /// ```
105 /// use std::mem;
106 ///
107 /// assert_eq!(4, mem::align_of::<i32>());
108 /// ```
109 #[inline]
110 #[stable]
111 pub fn align_of<T>() -> uint {
112     // We use the preferred alignment as the default alignment for a type. This
113     // appears to be what clang migrated towards as well:
114     //
115     // http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
116     unsafe { intrinsics::pref_align_of::<T>() }
117 }
118
119 /// Returns the alignment of the type of the value that `_val` points to.
120 ///
121 /// This is similar to `align_of`, but function will properly handle types such as trait objects
122 /// (in the future), returning the alignment for an arbitrary value at runtime.
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// use std::mem;
128 ///
129 /// assert_eq!(4, mem::align_of_val(&5i32));
130 /// ```
131 #[inline]
132 #[stable]
133 pub fn align_of_val<T>(_val: &T) -> uint {
134     align_of::<T>()
135 }
136
137 /// Create a value initialized to zero.
138 ///
139 /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
140 /// operation).
141 ///
142 /// Care must be taken when using this function, if the type `T` has a destructor and the value
143 /// falls out of scope (due to unwinding or returning) before being initialized, then the
144 /// destructor will run on zeroed data, likely leading to crashes.
145 ///
146 /// This is useful for FFI functions sometimes, but should generally be avoided.
147 ///
148 /// # Examples
149 ///
150 /// ```
151 /// use std::mem;
152 ///
153 /// let x: int = unsafe { mem::zeroed() };
154 /// ```
155 #[inline]
156 #[stable]
157 pub unsafe fn zeroed<T>() -> T {
158     intrinsics::init()
159 }
160
161 /// Create an uninitialized value.
162 ///
163 /// Care must be taken when using this function, if the type `T` has a destructor and the value
164 /// falls out of scope (due to unwinding or returning) before being initialized, then the
165 /// destructor will run on uninitialized data, likely leading to crashes.
166 ///
167 /// This is useful for FFI functions sometimes, but should generally be avoided.
168 ///
169 /// # Examples
170 ///
171 /// ```
172 /// use std::mem;
173 ///
174 /// let x: int = unsafe { mem::uninitialized() };
175 /// ```
176 #[inline]
177 #[stable]
178 pub unsafe fn uninitialized<T>() -> T {
179     intrinsics::uninit()
180 }
181
182 /// Swap the values at two mutable locations of the same type, without deinitialising or copying
183 /// either one.
184 ///
185 /// # Examples
186 ///
187 /// ```
188 /// use std::mem;
189 ///
190 /// let x = &mut 5i;
191 /// let y = &mut 42i;
192 ///
193 /// mem::swap(x, y);
194 ///
195 /// assert_eq!(42i, *x);
196 /// assert_eq!(5i, *y);
197 /// ```
198 #[inline]
199 #[stable]
200 pub fn swap<T>(x: &mut T, y: &mut T) {
201     unsafe {
202         // Give ourselves some scratch space to work with
203         let mut t: T = uninitialized();
204
205         // Perform the swap, `&mut` pointers never alias
206         ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
207         ptr::copy_nonoverlapping_memory(x, &*y, 1);
208         ptr::copy_nonoverlapping_memory(y, &t, 1);
209
210         // y and t now point to the same thing, but we need to completely forget `t`
211         // because it's no longer relevant.
212         forget(t);
213     }
214 }
215
216 /// Replace the value at a mutable location with a new one, returning the old value, without
217 /// deinitialising or copying either one.
218 ///
219 /// This is primarily used for transferring and swapping ownership of a value in a mutable
220 /// location.
221 ///
222 /// # Examples
223 ///
224 /// A simple example:
225 ///
226 /// ```
227 /// use std::mem;
228 ///
229 /// let mut v: Vec<i32> = Vec::new();
230 ///
231 /// mem::replace(&mut v, Vec::new());
232 /// ```
233 ///
234 /// This function allows consumption of one field of a struct by replacing it with another value.
235 /// The normal approach doesn't always work:
236 ///
237 /// ```rust,ignore
238 /// struct Buffer<T> { buf: Vec<T> }
239 ///
240 /// impl<T> Buffer<T> {
241 ///     fn get_and_reset(&mut self) -> Vec<T> {
242 ///         // error: cannot move out of dereference of `&mut`-pointer
243 ///         let buf = self.buf;
244 ///         self.buf = Vec::new();
245 ///         buf
246 ///     }
247 /// }
248 /// ```
249 ///
250 /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
251 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
252 /// `self`, allowing it to be returned:
253 ///
254 /// ```rust
255 /// use std::mem;
256 /// # struct Buffer<T> { buf: Vec<T> }
257 /// impl<T> Buffer<T> {
258 ///     fn get_and_reset(&mut self) -> Vec<T> {
259 ///         mem::replace(&mut self.buf, Vec::new())
260 ///     }
261 /// }
262 /// ```
263 #[inline]
264 #[stable]
265 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
266     swap(dest, &mut src);
267     src
268 }
269
270 /// Disposes of a value.
271 ///
272 /// This function can be used to destroy any value by allowing `drop` to take ownership of its
273 /// argument.
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// use std::cell::RefCell;
279 ///
280 /// let x = RefCell::new(1i);
281 ///
282 /// let mut mutable_borrow = x.borrow_mut();
283 /// *mutable_borrow = 1;
284 ///
285 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
286 ///
287 /// let borrow = x.borrow();
288 /// println!("{}", *borrow);
289 /// ```
290 #[inline]
291 #[stable]
292 pub fn drop<T>(_x: T) { }
293
294 /// Interprets `src` as `&U`, and then reads `src` without moving the contained value.
295 ///
296 /// This function will unsafely assume the pointer `src` is valid for `sizeof(U)` bytes by
297 /// transmuting `&T` to `&U` and then reading the `&U`. It will also unsafely create a copy of the
298 /// contained value instead of moving out of `src`.
299 ///
300 /// It is not a compile-time error if `T` and `U` have different sizes, but it is highly encouraged
301 /// to only invoke this function where `T` and `U` have the same size. This function triggers
302 /// undefined behavior if `U` is larger than `T`.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// use std::mem;
308 ///
309 /// let one = unsafe { mem::transmute_copy(&1i) };
310 ///
311 /// assert_eq!(1u, one);
312 /// ```
313 #[inline]
314 #[stable]
315 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
316     ptr::read(src as *const T as *const U)
317 }
318
319 /// Transforms lifetime of the second pointer to match the first.
320 #[inline]
321 #[unstable = "this function may be removed in the future due to its \
322               questionable utility"]
323 pub unsafe fn copy_lifetime<'a, Sized? S, Sized? T: 'a>(_ptr: &'a S,
324                                                         ptr: &T) -> &'a T {
325     transmute(ptr)
326 }
327
328 /// Transforms lifetime of the second mutable pointer to match the first.
329 #[inline]
330 #[unstable = "this function may be removed in the future due to its \
331               questionable utility"]
332 pub unsafe fn copy_mut_lifetime<'a, Sized? S, Sized? T: 'a>(_ptr: &'a mut S,
333                                                             ptr: &mut T)
334                                                             -> &'a mut T {
335     transmute(ptr)
336 }