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