]> git.proxmox.com Git - rustc.git/blob - src/libcore/mem.rs
Imported Upstream version 1.3.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 /// # 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 #[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>() }
161 }
162
163 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
164 ///
165 /// # Examples
166 ///
167 /// ```
168 /// use std::mem;
169 ///
170 /// assert_eq!(4, mem::min_align_of_val(&5i32));
171 /// ```
172 #[inline]
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) }
177 }
178
179 /// Returns the alignment in memory for a type.
180 ///
181 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use std::mem;
187 ///
188 /// assert_eq!(4, mem::align_of::<i32>());
189 /// ```
190 #[inline]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn align_of<T>() -> usize {
193 unsafe { intrinsics::min_align_of::<T>() }
194 }
195
196 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// use std::mem;
202 ///
203 /// assert_eq!(4, mem::align_of_val(&5i32));
204 /// ```
205 #[inline]
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) }
209 }
210
211 /// Creates a value initialized to zero.
212 ///
213 /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
214 /// operation).
215 ///
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.
219 ///
220 /// This is useful for FFI functions sometimes, but should generally be avoided.
221 ///
222 /// # Examples
223 ///
224 /// ```
225 /// use std::mem;
226 ///
227 /// let x: i32 = unsafe { mem::zeroed() };
228 /// ```
229 #[inline]
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub unsafe fn zeroed<T>() -> T {
232 intrinsics::init()
233 }
234
235 /// Creates a value initialized to an unspecified series of bytes.
236 ///
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
240 /// of scope.
241 ///
242 /// Some code at one time used the `zeroed` function above to
243 /// accomplish this goal.
244 ///
245 /// This function is expected to be deprecated with the transition
246 /// to non-zeroing drop.
247 #[inline]
248 #[unstable(feature = "filling_drop")]
249 pub unsafe fn dropped<T>() -> T {
250 #[inline(always)]
251 unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
252
253 dropped_impl()
254 }
255
256 /// Bypasses Rust's normal memory-initialization checks by pretending to
257 /// produce a value of type T, while doing nothing at all.
258 ///
259 /// **This is incredibly dangerous, and should not be done lightly. Deeply
260 /// consider initializing your memory with a default value instead.**
261 ///
262 /// This is useful for FFI functions and initializing arrays sometimes,
263 /// but should generally be avoided.
264 ///
265 /// # Undefined Behaviour
266 ///
267 /// It is Undefined Behaviour to read uninitialized memory. Even just an
268 /// uninitialized boolean. For instance, if you branch on the value of such
269 /// a boolean your program may take one, both, or neither of the branches.
270 ///
271 /// Note that this often also includes *writing* to the uninitialized value.
272 /// Rust believes the value is initialized, and will therefore try to Drop
273 /// the uninitialized value and its fields if you try to overwrite the memory
274 /// in a normal manner. The only way to safely initialize an arbitrary
275 /// uninitialized value is with one of the `ptr` functions: `write`, `copy`, or
276 /// `copy_nonoverlapping`. This isn't necessary if `T` is a primitive
277 /// or otherwise only contains types that don't implement Drop.
278 ///
279 /// If this value *does* need some kind of Drop, it must be initialized before
280 /// it goes out of scope (and therefore would be dropped). Note that this
281 /// includes a `panic` occurring and unwinding the stack suddenly.
282 ///
283 /// # Examples
284 ///
285 /// Here's how to safely initialize an array of `Vec`s.
286 ///
287 /// ```
288 /// use std::mem;
289 /// use std::ptr;
290 ///
291 /// // Only declare the array. This safely leaves it
292 /// // uninitialized in a way that Rust will track for us.
293 /// // However we can't initialize it element-by-element
294 /// // safely, and we can't use the `[value; 1000]`
295 /// // constructor because it only works with `Copy` data.
296 /// let mut data: [Vec<u32>; 1000];
297 ///
298 /// unsafe {
299 /// // So we need to do this to initialize it.
300 /// data = mem::uninitialized();
301 ///
302 /// // DANGER ZONE: if anything panics or otherwise
303 /// // incorrectly reads the array here, we will have
304 /// // Undefined Behaviour.
305 ///
306 /// // It's ok to mutably iterate the data, since this
307 /// // doesn't involve reading it at all.
308 /// // (ptr and len are statically known for arrays)
309 /// for elem in &mut data[..] {
310 /// // *elem = Vec::new() would try to drop the
311 /// // uninitialized memory at `elem` -- bad!
312 /// //
313 /// // Vec::new doesn't allocate or do really
314 /// // anything. It's only safe to call here
315 /// // because we know it won't panic.
316 /// ptr::write(elem, Vec::new());
317 /// }
318 ///
319 /// // SAFE ZONE: everything is initialized.
320 /// }
321 ///
322 /// println!("{:?}", &data[0]);
323 /// ```
324 ///
325 /// This example emphasizes exactly how delicate and dangerous doing this is.
326 /// Note that the `vec!` macro *does* let you initialize every element with a
327 /// value that is only `Clone`, so the following is semantically equivalent and
328 /// vastly less dangerous, as long as you can live with an extra heap
329 /// allocation:
330 ///
331 /// ```
332 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
333 /// println!("{:?}", &data[0]);
334 /// ```
335 #[inline]
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub unsafe fn uninitialized<T>() -> T {
338 intrinsics::uninit()
339 }
340
341 /// Swap the values at two mutable locations of the same type, without deinitialising or copying
342 /// either one.
343 ///
344 /// # Examples
345 ///
346 /// ```
347 /// use std::mem;
348 ///
349 /// let x = &mut 5;
350 /// let y = &mut 42;
351 ///
352 /// mem::swap(x, y);
353 ///
354 /// assert_eq!(42, *x);
355 /// assert_eq!(5, *y);
356 /// ```
357 #[inline]
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn swap<T>(x: &mut T, y: &mut T) {
360 unsafe {
361 // Give ourselves some scratch space to work with
362 let mut t: T = uninitialized();
363
364 // Perform the swap, `&mut` pointers never alias
365 ptr::copy_nonoverlapping(&*x, &mut t, 1);
366 ptr::copy_nonoverlapping(&*y, x, 1);
367 ptr::copy_nonoverlapping(&t, y, 1);
368
369 // y and t now point to the same thing, but we need to completely
370 // forget `t` because we do not want to run the destructor for `T`
371 // on its value, which is still owned somewhere outside this function.
372 forget(t);
373 }
374 }
375
376 /// Replaces the value at a mutable location with a new one, returning the old value, without
377 /// deinitialising or copying either one.
378 ///
379 /// This is primarily used for transferring and swapping ownership of a value in a mutable
380 /// location.
381 ///
382 /// # Examples
383 ///
384 /// A simple example:
385 ///
386 /// ```
387 /// use std::mem;
388 ///
389 /// let mut v: Vec<i32> = Vec::new();
390 ///
391 /// mem::replace(&mut v, Vec::new());
392 /// ```
393 ///
394 /// This function allows consumption of one field of a struct by replacing it with another value.
395 /// The normal approach doesn't always work:
396 ///
397 /// ```rust,ignore
398 /// struct Buffer<T> { buf: Vec<T> }
399 ///
400 /// impl<T> Buffer<T> {
401 /// fn get_and_reset(&mut self) -> Vec<T> {
402 /// // error: cannot move out of dereference of `&mut`-pointer
403 /// let buf = self.buf;
404 /// self.buf = Vec::new();
405 /// buf
406 /// }
407 /// }
408 /// ```
409 ///
410 /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
411 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
412 /// `self`, allowing it to be returned:
413 ///
414 /// ```
415 /// use std::mem;
416 /// # struct Buffer<T> { buf: Vec<T> }
417 /// impl<T> Buffer<T> {
418 /// fn get_and_reset(&mut self) -> Vec<T> {
419 /// mem::replace(&mut self.buf, Vec::new())
420 /// }
421 /// }
422 /// ```
423 #[inline]
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
426 swap(dest, &mut src);
427 src
428 }
429
430 /// Disposes of a value.
431 ///
432 /// While this does call the argument's implementation of `Drop`, it will not
433 /// release any borrows, as borrows are based on lexical scope.
434 ///
435 /// # Examples
436 ///
437 /// Basic usage:
438 ///
439 /// ```
440 /// let v = vec![1, 2, 3];
441 ///
442 /// drop(v); // explicitly drop the vector
443 /// ```
444 ///
445 /// Borrows are based on lexical scope, so this produces an error:
446 ///
447 /// ```ignore
448 /// let mut v = vec![1, 2, 3];
449 /// let x = &v[0];
450 ///
451 /// drop(x); // explicitly drop the reference, but the borrow still exists
452 ///
453 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
454 /// // borrowed as immutable
455 /// ```
456 ///
457 /// An inner scope is needed to fix this:
458 ///
459 /// ```
460 /// let mut v = vec![1, 2, 3];
461 ///
462 /// {
463 /// let x = &v[0];
464 ///
465 /// drop(x); // this is now redundant, as `x` is going out of scope anyway
466 /// }
467 ///
468 /// v.push(4); // no problems
469 /// ```
470 ///
471 /// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
472 /// seemingly release a borrow of one:
473 ///
474 /// ```
475 /// use std::cell::RefCell;
476 ///
477 /// let x = RefCell::new(1);
478 ///
479 /// let mut mutable_borrow = x.borrow_mut();
480 /// *mutable_borrow = 1;
481 ///
482 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
483 ///
484 /// let borrow = x.borrow();
485 /// println!("{}", *borrow);
486 /// ```
487 #[inline]
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn drop<T>(_x: T) { }
490
491 macro_rules! repeat_u8_as_u32 {
492 ($name:expr) => { (($name as u32) << 24 |
493 ($name as u32) << 16 |
494 ($name as u32) << 8 |
495 ($name as u32)) }
496 }
497 macro_rules! repeat_u8_as_u64 {
498 ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
499 (repeat_u8_as_u32!($name) as u64)) }
500 }
501
502 // NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
503 //
504 // In particular, the POST_DROP_U8 marker must never equal the
505 // DTOR_NEEDED_U8 marker.
506 //
507 // For a while pnkfelix was using 0xc1 here.
508 // But having the sign bit set is a pain, so 0x1d is probably better.
509 //
510 // And of course, 0x00 brings back the old world of zero'ing on drop.
511 #[unstable(feature = "filling_drop")]
512 #[allow(missing_docs)]
513 pub const POST_DROP_U8: u8 = 0x1d;
514 #[unstable(feature = "filling_drop")]
515 #[allow(missing_docs)]
516 pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
517 #[unstable(feature = "filling_drop")]
518 #[allow(missing_docs)]
519 pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
520
521 #[cfg(target_pointer_width = "32")]
522 #[unstable(feature = "filling_drop")]
523 #[allow(missing_docs)]
524 pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
525 #[cfg(target_pointer_width = "64")]
526 #[unstable(feature = "filling_drop")]
527 #[allow(missing_docs)]
528 pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
529
530 /// Interprets `src` as `&U`, and then reads `src` without moving the contained
531 /// value.
532 ///
533 /// This function will unsafely assume the pointer `src` is valid for
534 /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
535 /// will also unsafely create a copy of the contained value instead of moving
536 /// out of `src`.
537 ///
538 /// It is not a compile-time error if `T` and `U` have different sizes, but it
539 /// is highly encouraged to only invoke this function where `T` and `U` have the
540 /// same size. This function triggers undefined behavior if `U` is larger than
541 /// `T`.
542 ///
543 /// # Examples
544 ///
545 /// ```
546 /// use std::mem;
547 ///
548 /// let one = unsafe { mem::transmute_copy(&1) };
549 ///
550 /// assert_eq!(1, one);
551 /// ```
552 #[inline]
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
555 // FIXME(#23542) Replace with type ascription.
556 #![allow(trivial_casts)]
557 ptr::read(src as *const T as *const U)
558 }
559
560 /// Transforms lifetime of the second pointer to match the first.
561 #[inline]
562 #[unstable(feature = "copy_lifetime",
563 reason = "this function may be removed in the future due to its \
564 questionable utility")]
565 #[deprecated(since = "1.2.0",
566 reason = "unclear that this function buys more safety and \
567 lifetimes are generally not handled as such in unsafe \
568 code today")]
569 pub unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
570 ptr: &T) -> &'a T {
571 transmute(ptr)
572 }
573
574 /// Transforms lifetime of the second mutable pointer to match the first.
575 #[inline]
576 #[unstable(feature = "copy_lifetime",
577 reason = "this function may be removed in the future due to its \
578 questionable utility")]
579 #[deprecated(since = "1.2.0",
580 reason = "unclear that this function buys more safety and \
581 lifetimes are generally not handled as such in unsafe \
582 code today")]
583 pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
584 ptr: &mut T)
585 -> &'a mut T
586 {
587 transmute(ptr)
588 }