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