]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
Various minor/cosmetic improvements to code
[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 clone;
19 use cmp;
20 use fmt;
21 use hash;
22 use intrinsics;
23 use marker::{Copy, PhantomData, Sized};
24 use ptr;
25 use ops::{Deref, DerefMut};
26
27 #[stable(feature = "rust1", since = "1.0.0")]
28 pub use intrinsics::transmute;
29
30 /// Takes ownership and "forgets" about the value **without running its destructor**.
31 ///
32 /// Any resources the value manages, such as heap memory or a file handle, will linger
33 /// forever in an unreachable state. However, it does not guarantee that pointers
34 /// to this memory will remain valid.
35 ///
36 /// * If you want to leak memory, see [`Box::leak`][leak].
37 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`][into_raw].
38 /// * If you want to dispose of a value properly, running its destructor, see
39 /// [`mem::drop`][drop].
40 ///
41 /// # Safety
42 ///
43 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
44 /// do not include a guarantee that destructors will always run. For example,
45 /// a program can create a reference cycle using [`Rc`][rc], or call
46 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
47 /// `mem::forget` from safe code does not fundamentally change Rust's safety
48 /// guarantees.
49 ///
50 /// That said, leaking resources such as memory or I/O objects is usually undesirable,
51 /// so `forget` is only recommended for specialized use cases like those shown below.
52 ///
53 /// Because forgetting a value is allowed, any `unsafe` code you write must
54 /// allow for this possibility. You cannot return a value and expect that the
55 /// caller will necessarily run the value's destructor.
56 ///
57 /// [rc]: ../../std/rc/struct.Rc.html
58 /// [exit]: ../../std/process/fn.exit.html
59 ///
60 /// # Examples
61 ///
62 /// Leak an I/O object, never closing the file:
63 ///
64 /// ```no_run
65 /// use std::mem;
66 /// use std::fs::File;
67 ///
68 /// let file = File::open("foo.txt").unwrap();
69 /// mem::forget(file);
70 /// ```
71 ///
72 /// The practical use cases for `forget` are rather specialized and mainly come
73 /// up in unsafe or FFI code.
74 ///
75 /// ## Use case 1
76 ///
77 /// You have created an uninitialized value using [`mem::uninitialized`][uninit].
78 /// You must either initialize or `forget` it on every computation path before
79 /// Rust drops it automatically, like at the end of a scope or after a panic.
80 /// Running the destructor on an uninitialized value would be [undefined behavior][ub].
81 ///
82 /// ```
83 /// use std::mem;
84 /// use std::ptr;
85 ///
86 /// # let some_condition = false;
87 /// unsafe {
88 ///     let mut uninit_vec: Vec<u32> = mem::uninitialized();
89 ///
90 ///     if some_condition {
91 ///         // Initialize the variable.
92 ///         ptr::write(&mut uninit_vec, Vec::new());
93 ///     } else {
94 ///         // Forget the uninitialized value so its destructor doesn't run.
95 ///         mem::forget(uninit_vec);
96 ///     }
97 /// }
98 /// ```
99 ///
100 /// ## Use case 2
101 ///
102 /// You have duplicated the bytes making up a value, without doing a proper
103 /// [`Clone`][clone]. You need the value's destructor to run only once,
104 /// because a double `free` is undefined behavior.
105 ///
106 /// An example is a possible implementation of [`mem::swap`][swap]:
107 ///
108 /// ```
109 /// use std::mem;
110 /// use std::ptr;
111 ///
112 /// # #[allow(dead_code)]
113 /// fn swap<T>(x: &mut T, y: &mut T) {
114 ///     unsafe {
115 ///         // Give ourselves some scratch space to work with
116 ///         let mut t: T = mem::uninitialized();
117 ///
118 ///         // Perform the swap, `&mut` pointers never alias
119 ///         ptr::copy_nonoverlapping(&*x, &mut t, 1);
120 ///         ptr::copy_nonoverlapping(&*y, x, 1);
121 ///         ptr::copy_nonoverlapping(&t, y, 1);
122 ///
123 ///         // y and t now point to the same thing, but we need to completely
124 ///         // forget `t` because we do not want to run the destructor for `T`
125 ///         // on its value, which is still owned somewhere outside this function.
126 ///         mem::forget(t);
127 ///     }
128 /// }
129 /// ```
130 ///
131 /// [drop]: fn.drop.html
132 /// [uninit]: fn.uninitialized.html
133 /// [clone]: ../clone/trait.Clone.html
134 /// [swap]: fn.swap.html
135 /// [box]: ../../std/boxed/struct.Box.html
136 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
137 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
138 /// [ub]: ../../reference/behavior-considered-undefined.html
139 #[inline]
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn forget<T>(t: T) {
142     ManuallyDrop::new(t);
143 }
144
145 /// Like [`forget`], but also accepts unsized values.
146 ///
147 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
148 /// stabilized.
149 ///
150 /// [`forget`]: fn.forget.html
151 #[inline]
152 #[cfg(not(stage0))]
153 #[unstable(feature = "forget_unsized", issue = "0")]
154 pub fn forget_unsized<T: ?Sized>(t: T) {
155     unsafe { intrinsics::forget(t) }
156 }
157
158 /// Returns the size of a type in bytes.
159 ///
160 /// More specifically, this is the offset in bytes between successive elements
161 /// in an array with that item type including alignment padding. Thus, for any
162 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
163 ///
164 /// In general, the size of a type is not stable across compilations, but
165 /// specific types such as primitives are.
166 ///
167 /// The following table gives the size for primitives.
168 ///
169 /// Type | size_of::\<Type>()
170 /// ---- | ---------------
171 /// () | 0
172 /// bool | 1
173 /// u8 | 1
174 /// u16 | 2
175 /// u32 | 4
176 /// u64 | 8
177 /// u128 | 16
178 /// i8 | 1
179 /// i16 | 2
180 /// i32 | 4
181 /// i64 | 8
182 /// i128 | 16
183 /// f32 | 4
184 /// f64 | 8
185 /// char | 4
186 ///
187 /// Furthermore, `usize` and `isize` have the same size.
188 ///
189 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
190 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
191 ///
192 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
193 /// have the same size. Likewise for `*const T` and `*mut T`.
194 ///
195 /// # Size of `#[repr(C)]` items
196 ///
197 /// The `C` representation for items has a defined layout. With this layout,
198 /// the size of items is also stable as long as all fields have a stable size.
199 ///
200 /// ## Size of Structs
201 ///
202 /// For `structs`, the size is determined by the following algorithm.
203 ///
204 /// For each field in the struct ordered by declaration order:
205 ///
206 /// 1. Add the size of the field.
207 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
208 ///
209 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
210 /// The alignment of the struct is usually the largest alignment of all its
211 /// fields; this can be changed with the use of `repr(align(N))`.
212 ///
213 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
214 ///
215 /// ## Size of Enums
216 ///
217 /// Enums that carry no data other than the discriminant have the same size as C enums
218 /// on the platform they are compiled for.
219 ///
220 /// ## Size of Unions
221 ///
222 /// The size of a union is the size of its largest field.
223 ///
224 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// use std::mem;
230 ///
231 /// // Some primitives
232 /// assert_eq!(4, mem::size_of::<i32>());
233 /// assert_eq!(8, mem::size_of::<f64>());
234 /// assert_eq!(0, mem::size_of::<()>());
235 ///
236 /// // Some arrays
237 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
238 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
239 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
240 ///
241 ///
242 /// // Pointer size equality
243 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
244 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
245 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
246 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
247 /// ```
248 ///
249 /// Using `#[repr(C)]`.
250 ///
251 /// ```
252 /// use std::mem;
253 ///
254 /// #[repr(C)]
255 /// struct FieldStruct {
256 ///     first: u8,
257 ///     second: u16,
258 ///     third: u8
259 /// }
260 ///
261 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
262 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
263 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
264 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
265 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
266 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
267 /// // fields is 2), so add 1 to the size for padding. Size is 6.
268 /// assert_eq!(6, mem::size_of::<FieldStruct>());
269 ///
270 /// #[repr(C)]
271 /// struct TupleStruct(u8, u16, u8);
272 ///
273 /// // Tuple structs follow the same rules.
274 /// assert_eq!(6, mem::size_of::<TupleStruct>());
275 ///
276 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
277 /// // by putting `third` before `second`.
278 /// #[repr(C)]
279 /// struct FieldStructOptimized {
280 ///     first: u8,
281 ///     third: u8,
282 ///     second: u16
283 /// }
284 ///
285 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
286 ///
287 /// // Union size is the size of the largest field.
288 /// #[repr(C)]
289 /// union ExampleUnion {
290 ///     smaller: u8,
291 ///     larger: u16
292 /// }
293 ///
294 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
295 /// ```
296 ///
297 /// [alignment]: ./fn.align_of.html
298 #[inline]
299 #[stable(feature = "rust1", since = "1.0.0")]
300 #[rustc_promotable]
301 pub const fn size_of<T>() -> usize {
302     intrinsics::size_of::<T>()
303 }
304
305 /// Returns the size of the pointed-to value in bytes.
306 ///
307 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
308 /// statically known size, e.g., a slice [`[T]`][slice] or a [trait object],
309 /// then `size_of_val` can be used to get the dynamically-known size.
310 ///
311 /// [slice]: ../../std/primitive.slice.html
312 /// [trait object]: ../../book/first-edition/trait-objects.html
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// use std::mem;
318 ///
319 /// assert_eq!(4, mem::size_of_val(&5i32));
320 ///
321 /// let x: [u8; 13] = [0; 13];
322 /// let y: &[u8] = &x;
323 /// assert_eq!(13, mem::size_of_val(y));
324 /// ```
325 #[inline]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
328     unsafe { intrinsics::size_of_val(val) }
329 }
330
331 /// Returns the [ABI]-required minimum alignment of a type.
332 ///
333 /// Every reference to a value of the type `T` must be a multiple of this number.
334 ///
335 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
336 ///
337 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// # #![allow(deprecated)]
343 /// use std::mem;
344 ///
345 /// assert_eq!(4, mem::min_align_of::<i32>());
346 /// ```
347 #[inline]
348 #[stable(feature = "rust1", since = "1.0.0")]
349 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
350 pub fn min_align_of<T>() -> usize {
351     intrinsics::min_align_of::<T>()
352 }
353
354 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
355 ///
356 /// Every reference to a value of the type `T` must be a multiple of this number.
357 ///
358 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
359 ///
360 /// # Examples
361 ///
362 /// ```
363 /// # #![allow(deprecated)]
364 /// use std::mem;
365 ///
366 /// assert_eq!(4, mem::min_align_of_val(&5i32));
367 /// ```
368 #[inline]
369 #[stable(feature = "rust1", since = "1.0.0")]
370 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
371 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
372     unsafe { intrinsics::min_align_of_val(val) }
373 }
374
375 /// Returns the [ABI]-required minimum alignment of a type.
376 ///
377 /// Every reference to a value of the type `T` must be a multiple of this number.
378 ///
379 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
380 ///
381 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use std::mem;
387 ///
388 /// assert_eq!(4, mem::align_of::<i32>());
389 /// ```
390 #[inline]
391 #[stable(feature = "rust1", since = "1.0.0")]
392 #[rustc_promotable]
393 pub const fn align_of<T>() -> usize {
394     intrinsics::min_align_of::<T>()
395 }
396
397 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
398 ///
399 /// Every reference to a value of the type `T` must be a multiple of this number.
400 ///
401 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
402 ///
403 /// # Examples
404 ///
405 /// ```
406 /// use std::mem;
407 ///
408 /// assert_eq!(4, mem::align_of_val(&5i32));
409 /// ```
410 #[inline]
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
413     unsafe { intrinsics::min_align_of_val(val) }
414 }
415
416 /// Returns whether dropping values of type `T` matters.
417 ///
418 /// This is purely an optimization hint, and may be implemented conservatively:
419 /// it may return `true` for types that don't actually need to be dropped.
420 /// As such always returning `true` would be a valid implementation of
421 /// this function. However if this function actually returns `false`, then you
422 /// can be certain dropping `T` has no side effect.
423 ///
424 /// Low level implementations of things like collections, which need to manually
425 /// drop their data, should use this function to avoid unnecessarily
426 /// trying to drop all their contents when they are destroyed. This might not
427 /// make a difference in release builds (where a loop that has no side-effects
428 /// is easily detected and eliminated), but is often a big win for debug builds.
429 ///
430 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
431 /// can be reduced to some small number of drop_in_place calls, using this is
432 /// unnecessary. In particular note that you can drop_in_place a slice, and that
433 /// will do a single needs_drop check for all the values.
434 ///
435 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
436 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
437 /// values one at a time and should use this API.
438 ///
439 ///
440 /// # Examples
441 ///
442 /// Here's an example of how a collection might make use of needs_drop:
443 ///
444 /// ```
445 /// use std::{mem, ptr};
446 ///
447 /// pub struct MyCollection<T> {
448 /// #   data: [T; 1],
449 ///     /* ... */
450 /// }
451 /// # impl<T> MyCollection<T> {
452 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
453 /// #   fn free_buffer(&mut self) {}
454 /// # }
455 ///
456 /// impl<T> Drop for MyCollection<T> {
457 ///     fn drop(&mut self) {
458 ///         unsafe {
459 ///             // drop the data
460 ///             if mem::needs_drop::<T>() {
461 ///                 for x in self.iter_mut() {
462 ///                     ptr::drop_in_place(x);
463 ///                 }
464 ///             }
465 ///             self.free_buffer();
466 ///         }
467 ///     }
468 /// }
469 /// ```
470 #[inline]
471 #[stable(feature = "needs_drop", since = "1.21.0")]
472 #[rustc_const_unstable(feature = "const_needs_drop")]
473 pub const fn needs_drop<T>() -> bool {
474     intrinsics::needs_drop::<T>()
475 }
476
477 /// Creates a value whose bytes are all zero.
478 ///
479 /// This has the same effect as allocating space with
480 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
481 /// FFI sometimes, but should generally be avoided.
482 ///
483 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
484 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
485 /// a panic or the end of a scope) before being initialized, then the destructor
486 /// will run on zeroed data, likely leading to [undefined behavior][ub].
487 ///
488 /// See also the documentation for [`mem::uninitialized`][uninit], which has
489 /// many of the same caveats.
490 ///
491 /// [uninit]: fn.uninitialized.html
492 /// [ub]: ../../reference/behavior-considered-undefined.html
493 ///
494 /// # Examples
495 ///
496 /// ```
497 /// use std::mem;
498 ///
499 /// let x: i32 = unsafe { mem::zeroed() };
500 /// assert_eq!(0, x);
501 /// ```
502 #[inline]
503 #[rustc_deprecated(since = "2.0.0", reason = "use `mem::MaybeUninit::zeroed` instead")]
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub unsafe fn zeroed<T>() -> T {
506     intrinsics::init()
507 }
508
509 /// Bypasses Rust's normal memory-initialization checks by pretending to
510 /// produce a value of type `T`, while doing nothing at all.
511 ///
512 /// **This is incredibly dangerous and should not be done lightly. Deeply
513 /// consider initializing your memory with a default value instead.**
514 ///
515 /// This is useful for FFI functions and initializing arrays sometimes,
516 /// but should generally be avoided.
517 ///
518 /// # Undefined behavior
519 ///
520 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
521 /// uninitialized boolean. For instance, if you branch on the value of such
522 /// a boolean, your program may take one, both, or neither of the branches.
523 ///
524 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
525 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
526 /// value and its fields if you try to overwrite it in a normal manner. The only way
527 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
528 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
529 ///
530 /// If the value does implement [`Drop`], it must be initialized before
531 /// it goes out of scope (and therefore would be dropped). Note that this
532 /// includes a `panic` occurring and unwinding the stack suddenly.
533 ///
534 /// # Examples
535 ///
536 /// Here's how to safely initialize an array of [`Vec`]s.
537 ///
538 /// ```
539 /// use std::mem;
540 /// use std::ptr;
541 ///
542 /// // Only declare the array. This safely leaves it
543 /// // uninitialized in a way that Rust will track for us.
544 /// // However we can't initialize it element-by-element
545 /// // safely, and we can't use the `[value; 1000]`
546 /// // constructor because it only works with `Copy` data.
547 /// let mut data: [Vec<u32>; 1000];
548 ///
549 /// unsafe {
550 ///     // So we need to do this to initialize it.
551 ///     data = mem::uninitialized();
552 ///
553 ///     // DANGER ZONE: if anything panics or otherwise
554 ///     // incorrectly reads the array here, we will have
555 ///     // Undefined Behavior.
556 ///
557 ///     // It's ok to mutably iterate the data, since this
558 ///     // doesn't involve reading it at all.
559 ///     // (ptr and len are statically known for arrays)
560 ///     for elem in &mut data[..] {
561 ///         // *elem = Vec::new() would try to drop the
562 ///         // uninitialized memory at `elem` -- bad!
563 ///         //
564 ///         // Vec::new doesn't allocate or do really
565 ///         // anything. It's only safe to call here
566 ///         // because we know it won't panic.
567 ///         ptr::write(elem, Vec::new());
568 ///     }
569 ///
570 ///     // SAFE ZONE: everything is initialized.
571 /// }
572 ///
573 /// println!("{:?}", &data[0]);
574 /// ```
575 ///
576 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
577 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
578 /// value that is only [`Clone`], so the following is semantically equivalent and
579 /// vastly less dangerous, as long as you can live with an extra heap
580 /// allocation:
581 ///
582 /// ```
583 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
584 /// println!("{:?}", &data[0]);
585 /// ```
586 ///
587 /// [`Vec`]: ../../std/vec/struct.Vec.html
588 /// [`vec!`]: ../../std/macro.vec.html
589 /// [`Clone`]: ../../std/clone/trait.Clone.html
590 /// [ub]: ../../reference/behavior-considered-undefined.html
591 /// [write]: ../ptr/fn.write.html
592 /// [copy]: ../intrinsics/fn.copy.html
593 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
594 /// [`Drop`]: ../ops/trait.Drop.html
595 #[inline]
596 #[rustc_deprecated(since = "2.0.0", reason = "use `mem::MaybeUninit::uninitialized` instead")]
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub unsafe fn uninitialized<T>() -> T {
599     intrinsics::uninit()
600 }
601
602 /// Swaps the values at two mutable locations, without deinitializing either one.
603 ///
604 /// # Examples
605 ///
606 /// ```
607 /// use std::mem;
608 ///
609 /// let mut x = 5;
610 /// let mut y = 42;
611 ///
612 /// mem::swap(&mut x, &mut y);
613 ///
614 /// assert_eq!(42, x);
615 /// assert_eq!(5, y);
616 /// ```
617 #[inline]
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn swap<T>(x: &mut T, y: &mut T) {
620     unsafe {
621         ptr::swap_nonoverlapping_one(x, y);
622     }
623 }
624
625 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
626 ///
627 /// Neither value is dropped.
628 ///
629 /// # Examples
630 ///
631 /// A simple example:
632 ///
633 /// ```
634 /// use std::mem;
635 ///
636 /// let mut v: Vec<i32> = vec![1, 2];
637 ///
638 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
639 /// assert_eq!(2, old_v.len());
640 /// assert_eq!(3, v.len());
641 /// ```
642 ///
643 /// `replace` allows consumption of a struct field by replacing it with another value.
644 /// Without `replace` you can run into issues like these:
645 ///
646 /// ```compile_fail,E0507
647 /// struct Buffer<T> { buf: Vec<T> }
648 ///
649 /// impl<T> Buffer<T> {
650 ///     fn get_and_reset(&mut self) -> Vec<T> {
651 ///         // error: cannot move out of dereference of `&mut`-pointer
652 ///         let buf = self.buf;
653 ///         self.buf = Vec::new();
654 ///         buf
655 ///     }
656 /// }
657 /// ```
658 ///
659 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
660 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
661 /// `self`, allowing it to be returned:
662 ///
663 /// ```
664 /// # #![allow(dead_code)]
665 /// use std::mem;
666 ///
667 /// # struct Buffer<T> { buf: Vec<T> }
668 /// impl<T> Buffer<T> {
669 ///     fn get_and_reset(&mut self) -> Vec<T> {
670 ///         mem::replace(&mut self.buf, Vec::new())
671 ///     }
672 /// }
673 /// ```
674 ///
675 /// [`Clone`]: ../../std/clone/trait.Clone.html
676 #[inline]
677 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
679     swap(dest, &mut src);
680     src
681 }
682
683 /// Disposes of a value.
684 ///
685 /// While this does call the argument's implementation of [`Drop`][drop],
686 /// it will not release any borrows, as borrows are based on lexical scope.
687 ///
688 /// This effectively does nothing for types which implement `Copy`, e.g.
689 /// integers. Such values are copied and _then_ moved into the function, so the
690 /// value persists after this function call.
691 ///
692 /// This function is not magic; it is literally defined as
693 ///
694 /// ```
695 /// pub fn drop<T>(_x: T) { }
696 /// ```
697 ///
698 /// Because `_x` is moved into the function, it is automatically dropped before
699 /// the function returns.
700 ///
701 /// [drop]: ../ops/trait.Drop.html
702 ///
703 /// # Examples
704 ///
705 /// Basic usage:
706 ///
707 /// ```
708 /// let v = vec![1, 2, 3];
709 ///
710 /// drop(v); // explicitly drop the vector
711 /// ```
712 ///
713 /// Borrows are based on lexical scope, so this produces an error:
714 ///
715 /// ```compile_fail,E0502
716 /// let mut v = vec![1, 2, 3];
717 /// let x = &v[0];
718 ///
719 /// drop(x); // explicitly drop the reference, but the borrow still exists
720 ///
721 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
722 ///            // borrowed as immutable
723 /// ```
724 ///
725 /// An inner scope is needed to fix this:
726 ///
727 /// ```
728 /// let mut v = vec![1, 2, 3];
729 ///
730 /// {
731 ///     let x = &v[0];
732 ///
733 ///     drop(x); // this is now redundant, as `x` is going out of scope anyway
734 /// }
735 ///
736 /// v.push(4); // no problems
737 /// ```
738 ///
739 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
740 /// release a [`RefCell`] borrow:
741 ///
742 /// ```
743 /// use std::cell::RefCell;
744 ///
745 /// let x = RefCell::new(1);
746 ///
747 /// let mut mutable_borrow = x.borrow_mut();
748 /// *mutable_borrow = 1;
749 ///
750 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
751 ///
752 /// let borrow = x.borrow();
753 /// println!("{}", *borrow);
754 /// ```
755 ///
756 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
757 ///
758 /// ```
759 /// #[derive(Copy, Clone)]
760 /// struct Foo(u8);
761 ///
762 /// let x = 1;
763 /// let y = Foo(2);
764 /// drop(x); // a copy of `x` is moved and dropped
765 /// drop(y); // a copy of `y` is moved and dropped
766 ///
767 /// println!("x: {}, y: {}", x, y.0); // still available
768 /// ```
769 ///
770 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
771 /// [`Copy`]: ../../std/marker/trait.Copy.html
772 #[inline]
773 #[stable(feature = "rust1", since = "1.0.0")]
774 pub fn drop<T>(_x: T) { }
775
776 /// Interprets `src` as having type `&U`, and then reads `src` without moving
777 /// the contained value.
778 ///
779 /// This function will unsafely assume the pointer `src` is valid for
780 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
781 /// the `&U`. It will also unsafely create a copy of the contained value instead of
782 /// moving out of `src`.
783 ///
784 /// It is not a compile-time error if `T` and `U` have different sizes, but it
785 /// is highly encouraged to only invoke this function where `T` and `U` have the
786 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
787 /// `T`.
788 ///
789 /// [ub]: ../../reference/behavior-considered-undefined.html
790 /// [size_of]: fn.size_of.html
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// use std::mem;
796 ///
797 /// #[repr(packed)]
798 /// struct Foo {
799 ///     bar: u8,
800 /// }
801 ///
802 /// let foo_slice = [10u8];
803 ///
804 /// unsafe {
805 ///     // Copy the data from 'foo_slice' and treat it as a 'Foo'
806 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
807 ///     assert_eq!(foo_struct.bar, 10);
808 ///
809 ///     // Modify the copied data
810 ///     foo_struct.bar = 20;
811 ///     assert_eq!(foo_struct.bar, 20);
812 /// }
813 ///
814 /// // The contents of 'foo_slice' should not have changed
815 /// assert_eq!(foo_slice, [10]);
816 /// ```
817 #[inline]
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
820     ptr::read_unaligned(src as *const T as *const U)
821 }
822
823 /// Opaque type representing the discriminant of an enum.
824 ///
825 /// See the [`discriminant`] function in this module for more information.
826 ///
827 /// [`discriminant`]: fn.discriminant.html
828 #[stable(feature = "discriminant_value", since = "1.21.0")]
829 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
830
831 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
832
833 #[stable(feature = "discriminant_value", since = "1.21.0")]
834 impl<T> Copy for Discriminant<T> {}
835
836 #[stable(feature = "discriminant_value", since = "1.21.0")]
837 impl<T> clone::Clone for Discriminant<T> {
838     fn clone(&self) -> Self {
839         *self
840     }
841 }
842
843 #[stable(feature = "discriminant_value", since = "1.21.0")]
844 impl<T> cmp::PartialEq for Discriminant<T> {
845     fn eq(&self, rhs: &Self) -> bool {
846         self.0 == rhs.0
847     }
848 }
849
850 #[stable(feature = "discriminant_value", since = "1.21.0")]
851 impl<T> cmp::Eq for Discriminant<T> {}
852
853 #[stable(feature = "discriminant_value", since = "1.21.0")]
854 impl<T> hash::Hash for Discriminant<T> {
855     fn hash<H: hash::Hasher>(&self, state: &mut H) {
856         self.0.hash(state);
857     }
858 }
859
860 #[stable(feature = "discriminant_value", since = "1.21.0")]
861 impl<T> fmt::Debug for Discriminant<T> {
862     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
863         fmt.debug_tuple("Discriminant")
864            .field(&self.0)
865            .finish()
866     }
867 }
868
869 /// Returns a value uniquely identifying the enum variant in `v`.
870 ///
871 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
872 /// return value is unspecified.
873 ///
874 /// # Stability
875 ///
876 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
877 /// of some variant will not change between compilations with the same compiler.
878 ///
879 /// # Examples
880 ///
881 /// This can be used to compare enums that carry data, while disregarding
882 /// the actual data:
883 ///
884 /// ```
885 /// use std::mem;
886 ///
887 /// enum Foo { A(&'static str), B(i32), C(i32) }
888 ///
889 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
890 /// assert!(mem::discriminant(&Foo::B(1))     == mem::discriminant(&Foo::B(2)));
891 /// assert!(mem::discriminant(&Foo::B(3))     != mem::discriminant(&Foo::C(3)));
892 /// ```
893 #[stable(feature = "discriminant_value", since = "1.21.0")]
894 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
895     unsafe {
896         Discriminant(intrinsics::discriminant_value(v), PhantomData)
897     }
898 }
899
900 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
901 ///
902 /// This wrapper is 0-cost.
903 ///
904 /// # Examples
905 ///
906 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
907 /// the type:
908 ///
909 /// ```rust
910 /// use std::mem::ManuallyDrop;
911 /// struct Peach;
912 /// struct Banana;
913 /// struct Melon;
914 /// struct FruitBox {
915 ///     // Immediately clear there’s something non-trivial going on with these fields.
916 ///     peach: ManuallyDrop<Peach>,
917 ///     melon: Melon, // Field that’s independent of the other two.
918 ///     banana: ManuallyDrop<Banana>,
919 /// }
920 ///
921 /// impl Drop for FruitBox {
922 ///     fn drop(&mut self) {
923 ///         unsafe {
924 ///             // Explicit ordering in which field destructors are run specified in the intuitive
925 ///             // location – the destructor of the structure containing the fields.
926 ///             // Moreover, one can now reorder fields within the struct however much they want.
927 ///             ManuallyDrop::drop(&mut self.peach);
928 ///             ManuallyDrop::drop(&mut self.banana);
929 ///         }
930 ///         // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
931 ///         // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
932 ///     }
933 /// }
934 /// ```
935 #[stable(feature = "manually_drop", since = "1.20.0")]
936 #[lang = "manually_drop"]
937 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
938 #[repr(transparent)]
939 pub struct ManuallyDrop<T: ?Sized> {
940     value: T,
941 }
942
943 impl<T> ManuallyDrop<T> {
944     /// Wrap a value to be manually dropped.
945     ///
946     /// # Examples
947     ///
948     /// ```rust
949     /// use std::mem::ManuallyDrop;
950     /// ManuallyDrop::new(Box::new(()));
951     /// ```
952     #[stable(feature = "manually_drop", since = "1.20.0")]
953     #[inline(always)]
954     pub const fn new(value: T) -> ManuallyDrop<T> {
955         ManuallyDrop { value }
956     }
957
958     /// Extract the value from the `ManuallyDrop` container.
959     ///
960     /// This allows the value to be dropped again.
961     ///
962     /// # Examples
963     ///
964     /// ```rust
965     /// use std::mem::ManuallyDrop;
966     /// let x = ManuallyDrop::new(Box::new(()));
967     /// let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`.
968     /// ```
969     #[stable(feature = "manually_drop", since = "1.20.0")]
970     #[inline(always)]
971     pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
972         slot.value
973     }
974
975     /// Takes the contained value out.
976     ///
977     /// This method is primarily intended for moving out values in drop.
978     /// Instead of using [`ManuallyDrop::drop`] to manually drop the value,
979     /// you can use this method to take the value and use it however desired.
980     /// `Drop` will be invoked on the returned value following normal end-of-scope rules.
981     ///
982     /// If you have ownership of the container, you can use [`ManuallyDrop::into_inner`] instead.
983     ///
984     /// # Safety
985     ///
986     /// This function semantically moves out the contained value without preventing further usage.
987     /// It is up to the user of this method to ensure that this container is not used again.
988     #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"]
989     #[unstable(feature = "manually_drop_take", issue = "55422")]
990     #[inline]
991     pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
992         ManuallyDrop::into_inner(ptr::read(slot))
993     }
994 }
995
996 impl<T: ?Sized> ManuallyDrop<T> {
997     /// Manually drops the contained value.
998     ///
999     /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead.
1000     ///
1001     /// # Safety
1002     ///
1003     /// This function runs the destructor of the contained value and thus the wrapped value
1004     /// now represents uninitialized data. It is up to the user of this method to ensure the
1005     /// uninitialized data is not actually used.
1006     ///
1007     /// [`ManuallyDrop::into_inner`]: #method.into_inner
1008     #[stable(feature = "manually_drop", since = "1.20.0")]
1009     #[inline]
1010     pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
1011         ptr::drop_in_place(&mut slot.value)
1012     }
1013 }
1014
1015 #[stable(feature = "manually_drop", since = "1.20.0")]
1016 impl<T: ?Sized> Deref for ManuallyDrop<T> {
1017     type Target = T;
1018     #[inline(always)]
1019     fn deref(&self) -> &T {
1020         &self.value
1021     }
1022 }
1023
1024 #[stable(feature = "manually_drop", since = "1.20.0")]
1025 impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
1026     #[inline(always)]
1027     fn deref_mut(&mut self) -> &mut T {
1028         &mut self.value
1029     }
1030 }
1031
1032 /// A newtype to construct uninitialized instances of `T`
1033 #[allow(missing_debug_implementations)]
1034 #[unstable(feature = "maybe_uninit", issue = "53491")]
1035 // NOTE after stabilizing `MaybeUninit` proceed to deprecate `mem::{uninitialized,zeroed}`
1036 pub union MaybeUninit<T> {
1037     uninit: (),
1038     value: ManuallyDrop<T>,
1039 }
1040
1041 impl<T> MaybeUninit<T> {
1042     /// Create a new `MaybeUninit` initialized with the given value.
1043     ///
1044     /// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
1045     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1046     #[unstable(feature = "maybe_uninit", issue = "53491")]
1047     #[inline(always)]
1048     pub const fn new(val: T) -> MaybeUninit<T> {
1049         MaybeUninit { value: ManuallyDrop::new(val) }
1050     }
1051
1052     /// Create a new `MaybeUninit` in an uninitialized state.
1053     ///
1054     /// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
1055     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1056     #[unstable(feature = "maybe_uninit", issue = "53491")]
1057     #[inline(always)]
1058     pub const fn uninitialized() -> MaybeUninit<T> {
1059         MaybeUninit { uninit: () }
1060     }
1061
1062     /// Create a new `MaybeUninit` in an uninitialized state, with the memory being
1063     /// filled with `0` bytes.  It depends on `T` whether that already makes for
1064     /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
1065     /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
1066     /// be null.
1067     ///
1068     /// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
1069     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1070     #[unstable(feature = "maybe_uninit", issue = "53491")]
1071     #[inline]
1072     pub fn zeroed() -> MaybeUninit<T> {
1073         let mut u = MaybeUninit::<T>::uninitialized();
1074         unsafe {
1075             u.as_mut_ptr().write_bytes(0u8, 1);
1076         }
1077         u
1078     }
1079
1080     /// Set the value of the `MaybeUninit`. This overwrites any previous value without dropping it.
1081     #[unstable(feature = "maybe_uninit", issue = "53491")]
1082     #[inline(always)]
1083     pub fn set(&mut self, val: T) {
1084         unsafe {
1085             self.value = ManuallyDrop::new(val);
1086         }
1087     }
1088
1089     /// Extract the value from the `MaybeUninit` container.  This is a great way
1090     /// to ensure that the data will get dropped, because the resulting `T` is
1091     /// subject to the usual drop handling.
1092     ///
1093     /// # Unsafety
1094     ///
1095     /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
1096     /// state, otherwise this will immediately cause undefined behavior.
1097     #[unstable(feature = "maybe_uninit", issue = "53491")]
1098     #[inline(always)]
1099     pub unsafe fn into_inner(self) -> T {
1100         ManuallyDrop::into_inner(self.value)
1101     }
1102
1103     /// Get a reference to the contained value.
1104     ///
1105     /// # Unsafety
1106     ///
1107     /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
1108     /// state, otherwise this will immediately cause undefined behavior.
1109     #[unstable(feature = "maybe_uninit", issue = "53491")]
1110     #[inline(always)]
1111     pub unsafe fn get_ref(&self) -> &T {
1112         &*self.value
1113     }
1114
1115     /// Get a mutable reference to the contained value.
1116     ///
1117     /// # Unsafety
1118     ///
1119     /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
1120     /// state, otherwise this will immediately cause undefined behavior.
1121     // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
1122     // to uninitialized data (e.g., in `libcore/fmt/float.rs`).  We should make
1123     // a final decision about the rules before stabilization.
1124     #[unstable(feature = "maybe_uninit", issue = "53491")]
1125     #[inline(always)]
1126     pub unsafe fn get_mut(&mut self) -> &mut T {
1127         &mut *self.value
1128     }
1129
1130     /// Get a pointer to the contained value. Reading from this pointer will be undefined
1131     /// behavior unless the `MaybeUninit` is initialized.
1132     #[unstable(feature = "maybe_uninit", issue = "53491")]
1133     #[inline(always)]
1134     pub fn as_ptr(&self) -> *const T {
1135         unsafe { &*self.value as *const T }
1136     }
1137
1138     /// Get a mutable pointer to the contained value. Reading from this pointer will be undefined
1139     /// behavior unless the `MaybeUninit` is initialized.
1140     #[unstable(feature = "maybe_uninit", issue = "53491")]
1141     #[inline(always)]
1142     pub fn as_mut_ptr(&mut self) -> *mut T {
1143         unsafe { &mut *self.value as *mut T }
1144     }
1145 }