]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
26c6e899df1ce81d5b6817726b2762c3dc75a478
[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(feature = "rust1", since = "1.0.0")]
17
18 use marker::Sized;
19 use intrinsics;
20 use ptr;
21
22 #[stable(feature = "rust1", since = "1.0.0")]
23 pub use intrinsics::transmute;
24
25 /// Leaks a value into the void, consuming ownership and never running its
26 /// destructor.
27 ///
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.
31 ///
32 /// # Safety
33 ///
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.
38 ///
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.
44 ///
45 /// # Other forms of Leakage
46 ///
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
49 /// leakage are:
50 ///
51 /// * `Rc` and `Arc` cycles
52 /// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
53 /// * Panicking destructors are likely to leak local resources
54 ///
55 /// # When To Use
56 ///
57 /// There's only a few reasons to use this function. They mainly come
58 /// up in unsafe code or FFI code.
59 ///
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.
65 ///
66 /// # Example
67 ///
68 /// Leak some heap memory by never deallocating it.
69 ///
70 /// ```rust
71 /// use std::mem;
72 ///
73 /// let heap_memory = Box::new(3);
74 /// mem::forget(heap_memory);
75 /// ```
76 ///
77 /// Leak an I/O object, never closing the file.
78 ///
79 /// ```rust,no_run
80 /// use std::mem;
81 /// use std::fs::File;
82 ///
83 /// let file = File::open("foo.txt").unwrap();
84 /// mem::forget(file);
85 /// ```
86 ///
87 /// The swap function uses forget to good effect.
88 ///
89 /// ```rust
90 /// use std::mem;
91 /// use std::ptr;
92 ///
93 /// fn swap<T>(x: &mut T, y: &mut T) {
94 ///     unsafe {
95 ///         // Give ourselves some scratch space to work with
96 ///         let mut t: T = mem::uninitialized();
97 ///
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);
102 ///
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.
106 ///         mem::forget(t);
107 ///     }
108 /// }
109 /// ```
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub fn forget<T>(t: T) {
112     unsafe { intrinsics::forget(t) }
113 }
114
115 /// Returns the size of a type in bytes.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use std::mem;
121 ///
122 /// assert_eq!(4, mem::size_of::<i32>());
123 /// ```
124 #[inline]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub fn size_of<T>() -> usize {
127     unsafe { intrinsics::size_of::<T>() }
128 }
129
130 /// Returns the size of the type that `val` points to in bytes.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use std::mem;
136 ///
137 /// assert_eq!(4, mem::size_of_val(&5i32));
138 /// ```
139 #[inline]
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) }
143 }
144
145 /// Returns the ABI-required minimum alignment of a type
146 ///
147 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use std::mem;
153 ///
154 /// assert_eq!(4, mem::min_align_of::<i32>());
155 /// ```
156 #[inline]
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub fn min_align_of<T>() -> usize {
159     unsafe { intrinsics::min_align_of::<T>() }
160 }
161
162 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
163 ///
164 /// # Examples
165 ///
166 /// ```
167 /// use std::mem;
168 ///
169 /// assert_eq!(4, mem::min_align_of_val(&5i32));
170 /// ```
171 #[inline]
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
174     unsafe { intrinsics::min_align_of_val(val) }
175 }
176
177 /// Returns the alignment in memory for a type.
178 ///
179 /// This function will return the alignment, in bytes, of a type in memory. If the alignment
180 /// returned is adhered to, then the type is guaranteed to function properly.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use std::mem;
186 ///
187 /// assert_eq!(4, mem::align_of::<i32>());
188 /// ```
189 #[inline]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn align_of<T>() -> usize {
192     // We use the preferred alignment as the default alignment for a type. This
193     // appears to be what clang migrated towards as well:
194     //
195     // http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20110725/044411.html
196     unsafe { intrinsics::pref_align_of::<T>() }
197 }
198
199 /// Returns the alignment of the type of the value that `_val` points to.
200 ///
201 /// This is similar to `align_of`, but function will properly handle types such as trait objects
202 /// (in the future), returning the alignment for an arbitrary value at runtime.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use std::mem;
208 ///
209 /// assert_eq!(4, mem::align_of_val(&5i32));
210 /// ```
211 #[inline]
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn align_of_val<T>(_val: &T) -> usize {
214     align_of::<T>()
215 }
216
217 /// Creates a value initialized to zero.
218 ///
219 /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
220 /// operation).
221 ///
222 /// Care must be taken when using this function, if the type `T` has a destructor and the value
223 /// falls out of scope (due to unwinding or returning) before being initialized, then the
224 /// destructor will run on zeroed data, likely leading to crashes.
225 ///
226 /// This is useful for FFI functions sometimes, but should generally be avoided.
227 ///
228 /// # Examples
229 ///
230 /// ```
231 /// use std::mem;
232 ///
233 /// let x: i32 = unsafe { mem::zeroed() };
234 /// ```
235 #[inline]
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub unsafe fn zeroed<T>() -> T {
238     intrinsics::init()
239 }
240
241 /// Creates a value initialized to an unspecified series of bytes.
242 ///
243 /// The byte sequence usually indicates that the value at the memory
244 /// in question has been dropped. Thus, *if* T carries a drop flag,
245 /// any associated destructor will not be run when the value falls out
246 /// of scope.
247 ///
248 /// Some code at one time used the `zeroed` function above to
249 /// accomplish this goal.
250 ///
251 /// This function is expected to be deprecated with the transition
252 /// to non-zeroing drop.
253 #[inline]
254 #[unstable(feature = "filling_drop")]
255 pub unsafe fn dropped<T>() -> T {
256     #[inline(always)]
257     unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
258
259     dropped_impl()
260 }
261
262 /// Creates an uninitialized value.
263 ///
264 /// Care must be taken when using this function, if the type `T` has a destructor and the value
265 /// falls out of scope (due to unwinding or returning) before being initialized, then the
266 /// destructor will run on uninitialized data, likely leading to crashes.
267 ///
268 /// This is useful for FFI functions sometimes, but should generally be avoided.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// use std::mem;
274 ///
275 /// let x: i32 = unsafe { mem::uninitialized() };
276 /// ```
277 #[inline]
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub unsafe fn uninitialized<T>() -> T {
280     intrinsics::uninit()
281 }
282
283 /// Swap the values at two mutable locations of the same type, without deinitialising or copying
284 /// either one.
285 ///
286 /// # Examples
287 ///
288 /// ```
289 /// use std::mem;
290 ///
291 /// let x = &mut 5;
292 /// let y = &mut 42;
293 ///
294 /// mem::swap(x, y);
295 ///
296 /// assert_eq!(42, *x);
297 /// assert_eq!(5, *y);
298 /// ```
299 #[inline]
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn swap<T>(x: &mut T, y: &mut T) {
302     unsafe {
303         // Give ourselves some scratch space to work with
304         let mut t: T = uninitialized();
305
306         // Perform the swap, `&mut` pointers never alias
307         ptr::copy_nonoverlapping(&*x, &mut t, 1);
308         ptr::copy_nonoverlapping(&*y, x, 1);
309         ptr::copy_nonoverlapping(&t, y, 1);
310
311         // y and t now point to the same thing, but we need to completely
312         // forget `t` because we do not want to run the destructor for `T`
313         // on its value, which is still owned somewhere outside this function.
314         forget(t);
315     }
316 }
317
318 /// Replaces the value at a mutable location with a new one, returning the old value, without
319 /// deinitialising or copying either one.
320 ///
321 /// This is primarily used for transferring and swapping ownership of a value in a mutable
322 /// location.
323 ///
324 /// # Examples
325 ///
326 /// A simple example:
327 ///
328 /// ```
329 /// use std::mem;
330 ///
331 /// let mut v: Vec<i32> = Vec::new();
332 ///
333 /// mem::replace(&mut v, Vec::new());
334 /// ```
335 ///
336 /// This function allows consumption of one field of a struct by replacing it with another value.
337 /// The normal approach doesn't always work:
338 ///
339 /// ```rust,ignore
340 /// struct Buffer<T> { buf: Vec<T> }
341 ///
342 /// impl<T> Buffer<T> {
343 ///     fn get_and_reset(&mut self) -> Vec<T> {
344 ///         // error: cannot move out of dereference of `&mut`-pointer
345 ///         let buf = self.buf;
346 ///         self.buf = Vec::new();
347 ///         buf
348 ///     }
349 /// }
350 /// ```
351 ///
352 /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
353 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
354 /// `self`, allowing it to be returned:
355 ///
356 /// ```
357 /// use std::mem;
358 /// # struct Buffer<T> { buf: Vec<T> }
359 /// impl<T> Buffer<T> {
360 ///     fn get_and_reset(&mut self) -> Vec<T> {
361 ///         mem::replace(&mut self.buf, Vec::new())
362 ///     }
363 /// }
364 /// ```
365 #[inline]
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
368     swap(dest, &mut src);
369     src
370 }
371
372 /// Disposes of a value.
373 ///
374 /// This function can be used to destroy any value by allowing `drop` to take ownership of its
375 /// argument.
376 ///
377 /// # Examples
378 ///
379 /// ```
380 /// use std::cell::RefCell;
381 ///
382 /// let x = RefCell::new(1);
383 ///
384 /// let mut mutable_borrow = x.borrow_mut();
385 /// *mutable_borrow = 1;
386 ///
387 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
388 ///
389 /// let borrow = x.borrow();
390 /// println!("{}", *borrow);
391 /// ```
392 #[inline]
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn drop<T>(_x: T) { }
395
396 macro_rules! repeat_u8_as_u32 {
397     ($name:expr) => { (($name as u32) << 24 |
398                        ($name as u32) << 16 |
399                        ($name as u32) <<  8 |
400                        ($name as u32)) }
401 }
402 macro_rules! repeat_u8_as_u64 {
403     ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
404                        (repeat_u8_as_u32!($name) as u64)) }
405 }
406
407 // NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
408 //
409 // In particular, the POST_DROP_U8 marker must never equal the
410 // DTOR_NEEDED_U8 marker.
411 //
412 // For a while pnkfelix was using 0xc1 here.
413 // But having the sign bit set is a pain, so 0x1d is probably better.
414 //
415 // And of course, 0x00 brings back the old world of zero'ing on drop.
416 #[unstable(feature = "filling_drop")]
417 pub const POST_DROP_U8: u8 = 0x1d;
418 #[unstable(feature = "filling_drop")]
419 pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
420 #[unstable(feature = "filling_drop")]
421 pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
422
423 #[cfg(target_pointer_width = "32")]
424 #[unstable(feature = "filling_drop")]
425 pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
426 #[cfg(target_pointer_width = "64")]
427 #[unstable(feature = "filling_drop")]
428 pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
429
430 /// Interprets `src` as `&U`, and then reads `src` without moving the contained
431 /// value.
432 ///
433 /// This function will unsafely assume the pointer `src` is valid for
434 /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
435 /// will also unsafely create a copy of the contained value instead of moving
436 /// out of `src`.
437 ///
438 /// It is not a compile-time error if `T` and `U` have different sizes, but it
439 /// is highly encouraged to only invoke this function where `T` and `U` have the
440 /// same size. This function triggers undefined behavior if `U` is larger than
441 /// `T`.
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// use std::mem;
447 ///
448 /// let one = unsafe { mem::transmute_copy(&1) };
449 ///
450 /// assert_eq!(1, one);
451 /// ```
452 #[inline]
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
455     // FIXME(#23542) Replace with type ascription.
456     #![allow(trivial_casts)]
457     ptr::read(src as *const T as *const U)
458 }
459
460 /// Transforms lifetime of the second pointer to match the first.
461 #[inline]
462 #[unstable(feature = "core",
463            reason = "this function may be removed in the future due to its \
464                      questionable utility")]
465 pub unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
466                                                         ptr: &T) -> &'a T {
467     transmute(ptr)
468 }
469
470 /// Transforms lifetime of the second mutable pointer to match the first.
471 #[inline]
472 #[unstable(feature = "core",
473            reason = "this function may be removed in the future due to its \
474                      questionable utility")]
475 pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
476                                                                ptr: &mut T)
477                                                               -> &'a mut T
478 {
479     transmute(ptr)
480 }