]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
Change error message in rustbook
[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 /// There's only a few reasons to use this function. They mainly come
33 /// up in unsafe code or FFI code.
34 ///
35 /// * You have an uninitialized value, perhaps for performance reasons, and
36 ///   need to prevent the destructor from running on it.
37 /// * You have two copies of a value (like when writing something like
38 ///   [`mem::swap`][swap]), but need the destructor to only run once to
39 ///   prevent a double `free`.
40 /// * Transferring resources across [FFI][ffi] boundries.
41 ///
42 /// [swap]: fn.swap.html
43 /// [ffi]: ../../book/ffi.html
44 ///
45 /// # Safety
46 ///
47 /// This function is not marked as `unsafe` as Rust does not guarantee that the
48 /// `Drop` implementation for a value will always run. Note, however, that
49 /// leaking resources such as memory or I/O objects is likely not desired, so
50 /// this function is only recommended for specialized use cases.
51 ///
52 /// The safety of this function implies that when writing `unsafe` code
53 /// yourself care must be taken when leveraging a destructor that is required to
54 /// run to preserve memory safety. There are known situations where the
55 /// destructor may not run (such as if ownership of the object with the
56 /// destructor is returned) which must be taken into account.
57 ///
58 /// # Other forms of Leakage
59 ///
60 /// It's important to point out that this function is not the only method by
61 /// which a value can be leaked in safe Rust code. Other known sources of
62 /// leakage are:
63 ///
64 /// * `Rc` and `Arc` cycles
65 /// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
66 /// * Panicking destructors are likely to leak local resources
67 ///
68 /// # Example
69 ///
70 /// Leak some heap memory by never deallocating it:
71 ///
72 /// ```rust
73 /// use std::mem;
74 ///
75 /// let heap_memory = Box::new(3);
76 /// mem::forget(heap_memory);
77 /// ```
78 ///
79 /// Leak an I/O object, never closing the file:
80 ///
81 /// ```rust,no_run
82 /// use std::mem;
83 /// use std::fs::File;
84 ///
85 /// let file = File::open("foo.txt").unwrap();
86 /// mem::forget(file);
87 /// ```
88 ///
89 /// The `mem::swap` function uses `mem::forget` to good effect:
90 ///
91 /// ```rust
92 /// use std::mem;
93 /// use std::ptr;
94 ///
95 /// fn swap<T>(x: &mut T, y: &mut T) {
96 ///     unsafe {
97 ///         // Give ourselves some scratch space to work with
98 ///         let mut t: T = mem::uninitialized();
99 ///
100 ///         // Perform the swap, `&mut` pointers never alias
101 ///         ptr::copy_nonoverlapping(&*x, &mut t, 1);
102 ///         ptr::copy_nonoverlapping(&*y, x, 1);
103 ///         ptr::copy_nonoverlapping(&t, y, 1);
104 ///
105 ///         // y and t now point to the same thing, but we need to completely
106 ///         // forget `t` because we do not want to run the destructor for `T`
107 ///         // on its value, which is still owned somewhere outside this function.
108 ///         mem::forget(t);
109 ///     }
110 /// }
111 /// ```
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub fn forget<T>(t: T) {
114     unsafe { intrinsics::forget(t) }
115 }
116
117 /// Returns the size of a type in bytes.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// use std::mem;
123 ///
124 /// assert_eq!(4, mem::size_of::<i32>());
125 /// ```
126 #[inline]
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub fn size_of<T>() -> usize {
129     unsafe { intrinsics::size_of::<T>() }
130 }
131
132 /// Returns the size of the type that `val` points to in bytes.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use std::mem;
138 ///
139 /// assert_eq!(4, mem::size_of_val(&5i32));
140 /// ```
141 #[inline]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
144     unsafe { intrinsics::size_of_val(val) }
145 }
146
147 /// Returns the ABI-required minimum alignment of a type
148 ///
149 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use std::mem;
155 ///
156 /// assert_eq!(4, mem::min_align_of::<i32>());
157 /// ```
158 #[inline]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[deprecated(reason = "use `align_of` instead", since = "1.2.0")]
161 pub fn min_align_of<T>() -> usize {
162     unsafe { intrinsics::min_align_of::<T>() }
163 }
164
165 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
166 ///
167 /// # Examples
168 ///
169 /// ```
170 /// use std::mem;
171 ///
172 /// assert_eq!(4, mem::min_align_of_val(&5i32));
173 /// ```
174 #[inline]
175 #[stable(feature = "rust1", since = "1.0.0")]
176 #[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
177 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
178     unsafe { intrinsics::min_align_of_val(val) }
179 }
180
181 /// Returns the alignment in memory for a type.
182 ///
183 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
184 ///
185 /// # Examples
186 ///
187 /// ```
188 /// use std::mem;
189 ///
190 /// assert_eq!(4, mem::align_of::<i32>());
191 /// ```
192 #[inline]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn align_of<T>() -> usize {
195     unsafe { intrinsics::min_align_of::<T>() }
196 }
197
198 /// Returns the ABI-required minimum alignment of the type of the value that `val` points to
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// use std::mem;
204 ///
205 /// assert_eq!(4, mem::align_of_val(&5i32));
206 /// ```
207 #[inline]
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
210     unsafe { intrinsics::min_align_of_val(val) }
211 }
212
213 /// Creates a value initialized to zero.
214 ///
215 /// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
216 /// operation).
217 ///
218 /// Care must be taken when using this function, if the type `T` has a destructor and the value
219 /// falls out of scope (due to unwinding or returning) before being initialized, then the
220 /// destructor will run on zeroed data, likely leading to crashes.
221 ///
222 /// This is useful for FFI functions sometimes, but should generally be avoided.
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// use std::mem;
228 ///
229 /// let x: i32 = unsafe { mem::zeroed() };
230 /// ```
231 #[inline]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub unsafe fn zeroed<T>() -> T {
234     intrinsics::init()
235 }
236
237 /// Creates a value initialized to an unspecified series of bytes.
238 ///
239 /// The byte sequence usually indicates that the value at the memory
240 /// in question has been dropped. Thus, *if* T carries a drop flag,
241 /// any associated destructor will not be run when the value falls out
242 /// of scope.
243 ///
244 /// Some code at one time used the `zeroed` function above to
245 /// accomplish this goal.
246 ///
247 /// This function is expected to be deprecated with the transition
248 /// to non-zeroing drop.
249 #[inline]
250 #[unstable(feature = "filling_drop", issue = "5016")]
251 pub unsafe fn dropped<T>() -> T {
252     #[inline(always)]
253     unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
254
255     dropped_impl()
256 }
257
258 /// Bypasses Rust's normal memory-initialization checks by pretending to
259 /// produce a value of type T, while doing nothing at all.
260 ///
261 /// **This is incredibly dangerous, and should not be done lightly. Deeply
262 /// consider initializing your memory with a default value instead.**
263 ///
264 /// This is useful for FFI functions and initializing arrays sometimes,
265 /// but should generally be avoided.
266 ///
267 /// # Undefined Behaviour
268 ///
269 /// It is Undefined Behaviour to read uninitialized memory. Even just an
270 /// uninitialized boolean. For instance, if you branch on the value of such
271 /// a boolean your program may take one, both, or neither of the branches.
272 ///
273 /// Note that this often also includes *writing* to the uninitialized value.
274 /// Rust believes the value is initialized, and will therefore try to Drop
275 /// the uninitialized value and its fields if you try to overwrite the memory
276 /// in a normal manner. The only way to safely initialize an arbitrary
277 /// uninitialized value is with one of the `ptr` functions: `write`, `copy`, or
278 /// `copy_nonoverlapping`. This isn't necessary if `T` is a primitive
279 /// or otherwise only contains types that don't implement Drop.
280 ///
281 /// If this value *does* need some kind of Drop, it must be initialized before
282 /// it goes out of scope (and therefore would be dropped). Note that this
283 /// includes a `panic` occurring and unwinding the stack suddenly.
284 ///
285 /// # Examples
286 ///
287 /// Here's how to safely initialize an array of `Vec`s.
288 ///
289 /// ```
290 /// use std::mem;
291 /// use std::ptr;
292 ///
293 /// // Only declare the array. This safely leaves it
294 /// // uninitialized in a way that Rust will track for us.
295 /// // However we can't initialize it element-by-element
296 /// // safely, and we can't use the `[value; 1000]`
297 /// // constructor because it only works with `Copy` data.
298 /// let mut data: [Vec<u32>; 1000];
299 ///
300 /// unsafe {
301 ///     // So we need to do this to initialize it.
302 ///     data = mem::uninitialized();
303 ///
304 ///     // DANGER ZONE: if anything panics or otherwise
305 ///     // incorrectly reads the array here, we will have
306 ///     // Undefined Behaviour.
307 ///
308 ///     // It's ok to mutably iterate the data, since this
309 ///     // doesn't involve reading it at all.
310 ///     // (ptr and len are statically known for arrays)
311 ///     for elem in &mut data[..] {
312 ///         // *elem = Vec::new() would try to drop the
313 ///         // uninitialized memory at `elem` -- bad!
314 ///         //
315 ///         // Vec::new doesn't allocate or do really
316 ///         // anything. It's only safe to call here
317 ///         // because we know it won't panic.
318 ///         ptr::write(elem, Vec::new());
319 ///     }
320 ///
321 ///     // SAFE ZONE: everything is initialized.
322 /// }
323 ///
324 /// println!("{:?}", &data[0]);
325 /// ```
326 ///
327 /// This example emphasizes exactly how delicate and dangerous doing this is.
328 /// Note that the `vec!` macro *does* let you initialize every element with a
329 /// value that is only `Clone`, so the following is semantically equivalent and
330 /// vastly less dangerous, as long as you can live with an extra heap
331 /// allocation:
332 ///
333 /// ```
334 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
335 /// println!("{:?}", &data[0]);
336 /// ```
337 #[inline]
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub unsafe fn uninitialized<T>() -> T {
340     intrinsics::uninit()
341 }
342
343 /// Swap the values at two mutable locations of the same type, without deinitialising or copying
344 /// either one.
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// use std::mem;
350 ///
351 /// let x = &mut 5;
352 /// let y = &mut 42;
353 ///
354 /// mem::swap(x, y);
355 ///
356 /// assert_eq!(42, *x);
357 /// assert_eq!(5, *y);
358 /// ```
359 #[inline]
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn swap<T>(x: &mut T, y: &mut T) {
362     unsafe {
363         // Give ourselves some scratch space to work with
364         let mut t: T = uninitialized();
365
366         // Perform the swap, `&mut` pointers never alias
367         ptr::copy_nonoverlapping(&*x, &mut t, 1);
368         ptr::copy_nonoverlapping(&*y, x, 1);
369         ptr::copy_nonoverlapping(&t, y, 1);
370
371         // y and t now point to the same thing, but we need to completely
372         // forget `t` because we do not want to run the destructor for `T`
373         // on its value, which is still owned somewhere outside this function.
374         forget(t);
375     }
376 }
377
378 /// Replaces the value at a mutable location with a new one, returning the old value, without
379 /// deinitialising or copying either one.
380 ///
381 /// This is primarily used for transferring and swapping ownership of a value in a mutable
382 /// location.
383 ///
384 /// # Examples
385 ///
386 /// A simple example:
387 ///
388 /// ```
389 /// use std::mem;
390 ///
391 /// let mut v: Vec<i32> = Vec::new();
392 ///
393 /// mem::replace(&mut v, Vec::new());
394 /// ```
395 ///
396 /// This function allows consumption of one field of a struct by replacing it with another value.
397 /// The normal approach doesn't always work:
398 ///
399 /// ```rust,ignore
400 /// struct Buffer<T> { buf: Vec<T> }
401 ///
402 /// impl<T> Buffer<T> {
403 ///     fn get_and_reset(&mut self) -> Vec<T> {
404 ///         // error: cannot move out of dereference of `&mut`-pointer
405 ///         let buf = self.buf;
406 ///         self.buf = Vec::new();
407 ///         buf
408 ///     }
409 /// }
410 /// ```
411 ///
412 /// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
413 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
414 /// `self`, allowing it to be returned:
415 ///
416 /// ```
417 /// use std::mem;
418 /// # struct Buffer<T> { buf: Vec<T> }
419 /// impl<T> Buffer<T> {
420 ///     fn get_and_reset(&mut self) -> Vec<T> {
421 ///         mem::replace(&mut self.buf, Vec::new())
422 ///     }
423 /// }
424 /// ```
425 #[inline]
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
428     swap(dest, &mut src);
429     src
430 }
431
432 /// Disposes of a value.
433 ///
434 /// While this does call the argument's implementation of `Drop`, it will not
435 /// release any borrows, as borrows are based on lexical scope.
436 ///
437 /// This effectively does nothing for
438 /// [types which implement `Copy`](../../book/ownership.html#copy-types),
439 /// e.g. integers. Such values are copied and _then_ moved into the function,
440 /// so the value persists after this function call.
441 ///
442 /// # Examples
443 ///
444 /// Basic usage:
445 ///
446 /// ```
447 /// let v = vec![1, 2, 3];
448 ///
449 /// drop(v); // explicitly drop the vector
450 /// ```
451 ///
452 /// Borrows are based on lexical scope, so this produces an error:
453 ///
454 /// ```ignore
455 /// let mut v = vec![1, 2, 3];
456 /// let x = &v[0];
457 ///
458 /// drop(x); // explicitly drop the reference, but the borrow still exists
459 ///
460 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
461 ///            // borrowed as immutable
462 /// ```
463 ///
464 /// An inner scope is needed to fix this:
465 ///
466 /// ```
467 /// let mut v = vec![1, 2, 3];
468 ///
469 /// {
470 ///     let x = &v[0];
471 ///
472 ///     drop(x); // this is now redundant, as `x` is going out of scope anyway
473 /// }
474 ///
475 /// v.push(4); // no problems
476 /// ```
477 ///
478 /// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
479 /// seemingly release a borrow of one:
480 ///
481 /// ```
482 /// use std::cell::RefCell;
483 ///
484 /// let x = RefCell::new(1);
485 ///
486 /// let mut mutable_borrow = x.borrow_mut();
487 /// *mutable_borrow = 1;
488 ///
489 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
490 ///
491 /// let borrow = x.borrow();
492 /// println!("{}", *borrow);
493 /// ```
494 ///
495 /// Integers and other types implementing `Copy` are unaffected by `drop()`
496 ///
497 /// ```
498 /// #[derive(Copy, Clone)]
499 /// struct Foo(u8);
500 ///
501 /// let x = 1;
502 /// let y = Foo(2);
503 /// drop(x); // a copy of `x` is moved and dropped
504 /// drop(y); // a copy of `y` is moved and dropped
505 ///
506 /// println!("x: {}, y: {}", x, y.0); // still available
507 /// ```
508 ///
509 #[inline]
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn drop<T>(_x: T) { }
512
513 macro_rules! repeat_u8_as_u32 {
514     ($name:expr) => { (($name as u32) << 24 |
515                        ($name as u32) << 16 |
516                        ($name as u32) <<  8 |
517                        ($name as u32)) }
518 }
519 macro_rules! repeat_u8_as_u64 {
520     ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
521                        (repeat_u8_as_u32!($name) as u64)) }
522 }
523
524 // NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
525 //
526 // In particular, the POST_DROP_U8 marker must never equal the
527 // DTOR_NEEDED_U8 marker.
528 //
529 // For a while pnkfelix was using 0xc1 here.
530 // But having the sign bit set is a pain, so 0x1d is probably better.
531 //
532 // And of course, 0x00 brings back the old world of zero'ing on drop.
533 #[unstable(feature = "filling_drop", issue = "5016")]
534 #[allow(missing_docs)]
535 pub const POST_DROP_U8: u8 = 0x1d;
536 #[unstable(feature = "filling_drop", issue = "5016")]
537 #[allow(missing_docs)]
538 pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
539 #[unstable(feature = "filling_drop", issue = "5016")]
540 #[allow(missing_docs)]
541 pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
542
543 #[cfg(target_pointer_width = "32")]
544 #[unstable(feature = "filling_drop", issue = "5016")]
545 #[allow(missing_docs)]
546 pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
547 #[cfg(target_pointer_width = "64")]
548 #[unstable(feature = "filling_drop", issue = "5016")]
549 #[allow(missing_docs)]
550 pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
551
552 /// Interprets `src` as `&U`, and then reads `src` without moving the contained
553 /// value.
554 ///
555 /// This function will unsafely assume the pointer `src` is valid for
556 /// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
557 /// will also unsafely create a copy of the contained value instead of moving
558 /// out of `src`.
559 ///
560 /// It is not a compile-time error if `T` and `U` have different sizes, but it
561 /// is highly encouraged to only invoke this function where `T` and `U` have the
562 /// same size. This function triggers undefined behavior if `U` is larger than
563 /// `T`.
564 ///
565 /// # Examples
566 ///
567 /// ```
568 /// use std::mem;
569 ///
570 /// let one = unsafe { mem::transmute_copy(&1) };
571 ///
572 /// assert_eq!(1, one);
573 /// ```
574 #[inline]
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
577     // FIXME(#23542) Replace with type ascription.
578     #![allow(trivial_casts)]
579     ptr::read(src as *const T as *const U)
580 }