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