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