]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
af2f876a2f35906010bad6e63e94c1d8c4ceeca6
[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 /// 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
181 /// items of the same type, including alignment padding.
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use std::mem;
187 ///
188 /// assert_eq!(4, mem::size_of::<i32>());
189 /// ```
190 #[inline]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub const fn size_of<T>() -> usize {
193     unsafe { intrinsics::size_of::<T>() }
194 }
195
196 /// Returns the size of the pointed-to value in bytes.
197 ///
198 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
199 /// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
200 /// then `size_of_val` can be used to get the dynamically-known size.
201 ///
202 /// [slice]: ../../std/primitive.slice.html
203 /// [trait object]: ../../book/first-edition/trait-objects.html
204 ///
205 /// # Examples
206 ///
207 /// ```
208 /// use std::mem;
209 ///
210 /// assert_eq!(4, mem::size_of_val(&5i32));
211 ///
212 /// let x: [u8; 13] = [0; 13];
213 /// let y: &[u8] = &x;
214 /// assert_eq!(13, mem::size_of_val(y));
215 /// ```
216 #[inline]
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
219     unsafe { intrinsics::size_of_val(val) }
220 }
221
222 /// Returns the [ABI]-required minimum alignment of a type.
223 ///
224 /// Every reference to a value of the type `T` must be a multiple of this number.
225 ///
226 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
227 ///
228 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// # #![allow(deprecated)]
234 /// use std::mem;
235 ///
236 /// assert_eq!(4, mem::min_align_of::<i32>());
237 /// ```
238 #[inline]
239 #[stable(feature = "rust1", since = "1.0.0")]
240 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
241 pub fn min_align_of<T>() -> usize {
242     unsafe { intrinsics::min_align_of::<T>() }
243 }
244
245 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
246 ///
247 /// Every reference to a value of the type `T` must be a multiple of this number.
248 ///
249 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// # #![allow(deprecated)]
255 /// use std::mem;
256 ///
257 /// assert_eq!(4, mem::min_align_of_val(&5i32));
258 /// ```
259 #[inline]
260 #[stable(feature = "rust1", since = "1.0.0")]
261 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
262 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
263     unsafe { intrinsics::min_align_of_val(val) }
264 }
265
266 /// Returns the [ABI]-required minimum alignment of a type.
267 ///
268 /// Every reference to a value of the type `T` must be a multiple of this number.
269 ///
270 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
271 ///
272 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
273 ///
274 /// # Examples
275 ///
276 /// ```
277 /// use std::mem;
278 ///
279 /// assert_eq!(4, mem::align_of::<i32>());
280 /// ```
281 #[inline]
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub const fn align_of<T>() -> usize {
284     unsafe { intrinsics::min_align_of::<T>() }
285 }
286
287 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
288 ///
289 /// Every reference to a value of the type `T` must be a multiple of this number.
290 ///
291 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
292 ///
293 /// # Examples
294 ///
295 /// ```
296 /// use std::mem;
297 ///
298 /// assert_eq!(4, mem::align_of_val(&5i32));
299 /// ```
300 #[inline]
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
303     unsafe { intrinsics::min_align_of_val(val) }
304 }
305
306 /// Returns whether dropping values of type `T` matters.
307 ///
308 /// This is purely an optimization hint, and may be implemented conservatively.
309 /// For instance, always returning `true` would be a valid implementation of
310 /// this function.
311 ///
312 /// Low level implementations of things like collections, which need to manually
313 /// drop their data, should use this function to avoid unnecessarily
314 /// trying to drop all their contents when they are destroyed. This might not
315 /// make a difference in release builds (where a loop that has no side-effects
316 /// is easily detected and eliminated), but is often a big win for debug builds.
317 ///
318 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
319 /// can be reduced to some small number of drop_in_place calls, using this is
320 /// unnecessary. In particular note that you can drop_in_place a slice, and that
321 /// will do a single needs_drop check for all the values.
322 ///
323 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
324 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
325 /// values one at a time and should use this API.
326 ///
327 ///
328 /// # Examples
329 ///
330 /// Here's an example of how a collection might make use of needs_drop:
331 ///
332 /// ```
333 /// #![feature(needs_drop)]
334 /// use std::{mem, ptr};
335 ///
336 /// pub struct MyCollection<T> {
337 /// #   data: [T; 1],
338 ///     /* ... */
339 /// }
340 /// # impl<T> MyCollection<T> {
341 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
342 /// #   fn free_buffer(&mut self) {}
343 /// # }
344 ///
345 /// impl<T> Drop for MyCollection<T> {
346 ///     fn drop(&mut self) {
347 ///         unsafe {
348 ///             // drop the data
349 ///             if mem::needs_drop::<T>() {
350 ///                 for x in self.iter_mut() {
351 ///                     ptr::drop_in_place(x);
352 ///                 }
353 ///             }
354 ///             self.free_buffer();
355 ///         }
356 ///     }
357 /// }
358 /// ```
359 #[inline]
360 #[unstable(feature = "needs_drop", issue = "41890")]
361 pub fn needs_drop<T>() -> bool {
362     unsafe { intrinsics::needs_drop::<T>() }
363 }
364
365 /// Creates a value whose bytes are all zero.
366 ///
367 /// This has the same effect as allocating space with
368 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
369 /// [FFI] sometimes, but should generally be avoided.
370 ///
371 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
372 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
373 /// a panic or the end of a scope) before being initialized, then the destructor
374 /// will run on zeroed data, likely leading to [undefined behavior][ub].
375 ///
376 /// See also the documentation for [`mem::uninitialized`][uninit], which has
377 /// many of the same caveats.
378 ///
379 /// [uninit]: fn.uninitialized.html
380 /// [FFI]: ../../book/first-edition/ffi.html
381 /// [ub]: ../../reference/behavior-considered-undefined.html
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use std::mem;
387 ///
388 /// let x: i32 = unsafe { mem::zeroed() };
389 /// assert_eq!(0, x);
390 /// ```
391 #[inline]
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub unsafe fn zeroed<T>() -> T {
394     intrinsics::init()
395 }
396
397 /// Bypasses Rust's normal memory-initialization checks by pretending to
398 /// produce a value of type `T`, while doing nothing at all.
399 ///
400 /// **This is incredibly dangerous and should not be done lightly. Deeply
401 /// consider initializing your memory with a default value instead.**
402 ///
403 /// This is useful for [FFI] functions and initializing arrays sometimes,
404 /// but should generally be avoided.
405 ///
406 /// [FFI]: ../../book/first-edition/ffi.html
407 ///
408 /// # Undefined behavior
409 ///
410 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
411 /// uninitialized boolean. For instance, if you branch on the value of such
412 /// a boolean, your program may take one, both, or neither of the branches.
413 ///
414 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
415 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
416 /// value and its fields if you try to overwrite it in a normal manner. The only way
417 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
418 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
419 ///
420 /// If the value does implement [`Drop`], it must be initialized before
421 /// it goes out of scope (and therefore would be dropped). Note that this
422 /// includes a `panic` occurring and unwinding the stack suddenly.
423 ///
424 /// # Examples
425 ///
426 /// Here's how to safely initialize an array of [`Vec`]s.
427 ///
428 /// ```
429 /// use std::mem;
430 /// use std::ptr;
431 ///
432 /// // Only declare the array. This safely leaves it
433 /// // uninitialized in a way that Rust will track for us.
434 /// // However we can't initialize it element-by-element
435 /// // safely, and we can't use the `[value; 1000]`
436 /// // constructor because it only works with `Copy` data.
437 /// let mut data: [Vec<u32>; 1000];
438 ///
439 /// unsafe {
440 ///     // So we need to do this to initialize it.
441 ///     data = mem::uninitialized();
442 ///
443 ///     // DANGER ZONE: if anything panics or otherwise
444 ///     // incorrectly reads the array here, we will have
445 ///     // Undefined Behavior.
446 ///
447 ///     // It's ok to mutably iterate the data, since this
448 ///     // doesn't involve reading it at all.
449 ///     // (ptr and len are statically known for arrays)
450 ///     for elem in &mut data[..] {
451 ///         // *elem = Vec::new() would try to drop the
452 ///         // uninitialized memory at `elem` -- bad!
453 ///         //
454 ///         // Vec::new doesn't allocate or do really
455 ///         // anything. It's only safe to call here
456 ///         // because we know it won't panic.
457 ///         ptr::write(elem, Vec::new());
458 ///     }
459 ///
460 ///     // SAFE ZONE: everything is initialized.
461 /// }
462 ///
463 /// println!("{:?}", &data[0]);
464 /// ```
465 ///
466 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
467 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
468 /// value that is only [`Clone`], so the following is semantically equivalent and
469 /// vastly less dangerous, as long as you can live with an extra heap
470 /// allocation:
471 ///
472 /// ```
473 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
474 /// println!("{:?}", &data[0]);
475 /// ```
476 ///
477 /// [`Vec`]: ../../std/vec/struct.Vec.html
478 /// [`vec!`]: ../../std/macro.vec.html
479 /// [`Clone`]: ../../std/clone/trait.Clone.html
480 /// [ub]: ../../reference/behavior-considered-undefined.html
481 /// [write]: ../ptr/fn.write.html
482 /// [copy]: ../intrinsics/fn.copy.html
483 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
484 /// [`Drop`]: ../ops/trait.Drop.html
485 #[inline]
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub unsafe fn uninitialized<T>() -> T {
488     intrinsics::uninit()
489 }
490
491 /// Swaps the values at two mutable locations, without deinitializing either one.
492 ///
493 /// # Examples
494 ///
495 /// ```
496 /// use std::mem;
497 ///
498 /// let mut x = 5;
499 /// let mut y = 42;
500 ///
501 /// mem::swap(&mut x, &mut y);
502 ///
503 /// assert_eq!(42, x);
504 /// assert_eq!(5, y);
505 /// ```
506 #[inline]
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn swap<T>(x: &mut T, y: &mut T) {
509     unsafe {
510         ptr::swap_nonoverlapping(x, y, 1);
511     }
512 }
513
514 /// Replaces the value at a mutable location with a new one, returning the old value, without
515 /// deinitializing either one.
516 ///
517 /// # Examples
518 ///
519 /// A simple example:
520 ///
521 /// ```
522 /// use std::mem;
523 ///
524 /// let mut v: Vec<i32> = vec![1, 2];
525 ///
526 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
527 /// assert_eq!(2, old_v.len());
528 /// assert_eq!(3, v.len());
529 /// ```
530 ///
531 /// `replace` allows consumption of a struct field by replacing it with another value.
532 /// Without `replace` you can run into issues like these:
533 ///
534 /// ```compile_fail,E0507
535 /// struct Buffer<T> { buf: Vec<T> }
536 ///
537 /// impl<T> Buffer<T> {
538 ///     fn get_and_reset(&mut self) -> Vec<T> {
539 ///         // error: cannot move out of dereference of `&mut`-pointer
540 ///         let buf = self.buf;
541 ///         self.buf = Vec::new();
542 ///         buf
543 ///     }
544 /// }
545 /// ```
546 ///
547 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
548 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
549 /// `self`, allowing it to be returned:
550 ///
551 /// ```
552 /// # #![allow(dead_code)]
553 /// use std::mem;
554 ///
555 /// # struct Buffer<T> { buf: Vec<T> }
556 /// impl<T> Buffer<T> {
557 ///     fn get_and_reset(&mut self) -> Vec<T> {
558 ///         mem::replace(&mut self.buf, Vec::new())
559 ///     }
560 /// }
561 /// ```
562 ///
563 /// [`Clone`]: ../../std/clone/trait.Clone.html
564 #[inline]
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
567     swap(dest, &mut src);
568     src
569 }
570
571 /// Disposes of a value.
572 ///
573 /// While this does call the argument's implementation of [`Drop`][drop],
574 /// it will not release any borrows, as borrows are based on lexical scope.
575 ///
576 /// This effectively does nothing for
577 /// [types which implement `Copy`](../../book/first-edition/ownership.html#copy-types),
578 /// e.g. integers. Such values are copied and _then_ moved into the function,
579 /// so the value persists after this function call.
580 ///
581 /// This function is not magic; it is literally defined as
582 ///
583 /// ```
584 /// pub fn drop<T>(_x: T) { }
585 /// ```
586 ///
587 /// Because `_x` is moved into the function, it is automatically dropped before
588 /// the function returns.
589 ///
590 /// [drop]: ../ops/trait.Drop.html
591 ///
592 /// # Examples
593 ///
594 /// Basic usage:
595 ///
596 /// ```
597 /// let v = vec![1, 2, 3];
598 ///
599 /// drop(v); // explicitly drop the vector
600 /// ```
601 ///
602 /// Borrows are based on lexical scope, so this produces an error:
603 ///
604 /// ```compile_fail,E0502
605 /// let mut v = vec![1, 2, 3];
606 /// let x = &v[0];
607 ///
608 /// drop(x); // explicitly drop the reference, but the borrow still exists
609 ///
610 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
611 ///            // borrowed as immutable
612 /// ```
613 ///
614 /// An inner scope is needed to fix this:
615 ///
616 /// ```
617 /// let mut v = vec![1, 2, 3];
618 ///
619 /// {
620 ///     let x = &v[0];
621 ///
622 ///     drop(x); // this is now redundant, as `x` is going out of scope anyway
623 /// }
624 ///
625 /// v.push(4); // no problems
626 /// ```
627 ///
628 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
629 /// release a [`RefCell`] borrow:
630 ///
631 /// ```
632 /// use std::cell::RefCell;
633 ///
634 /// let x = RefCell::new(1);
635 ///
636 /// let mut mutable_borrow = x.borrow_mut();
637 /// *mutable_borrow = 1;
638 ///
639 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
640 ///
641 /// let borrow = x.borrow();
642 /// println!("{}", *borrow);
643 /// ```
644 ///
645 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
646 ///
647 /// ```
648 /// #[derive(Copy, Clone)]
649 /// struct Foo(u8);
650 ///
651 /// let x = 1;
652 /// let y = Foo(2);
653 /// drop(x); // a copy of `x` is moved and dropped
654 /// drop(y); // a copy of `y` is moved and dropped
655 ///
656 /// println!("x: {}, y: {}", x, y.0); // still available
657 /// ```
658 ///
659 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
660 /// [`Copy`]: ../../std/marker/trait.Copy.html
661 #[inline]
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub fn drop<T>(_x: T) { }
664
665 /// Interprets `src` as having type `&U`, and then reads `src` without moving
666 /// the contained value.
667 ///
668 /// This function will unsafely assume the pointer `src` is valid for
669 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
670 /// the `&U`. It will also unsafely create a copy of the contained value instead of
671 /// moving out of `src`.
672 ///
673 /// It is not a compile-time error if `T` and `U` have different sizes, but it
674 /// is highly encouraged to only invoke this function where `T` and `U` have the
675 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
676 /// `T`.
677 ///
678 /// [ub]: ../../reference/behavior-considered-undefined.html
679 /// [size_of]: fn.size_of.html
680 ///
681 /// # Examples
682 ///
683 /// ```
684 /// use std::mem;
685 ///
686 /// #[repr(packed)]
687 /// struct Foo {
688 ///     bar: u8,
689 /// }
690 ///
691 /// let foo_slice = [10u8];
692 ///
693 /// unsafe {
694 ///     // Copy the data from 'foo_slice' and treat it as a 'Foo'
695 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
696 ///     assert_eq!(foo_struct.bar, 10);
697 ///
698 ///     // Modify the copied data
699 ///     foo_struct.bar = 20;
700 ///     assert_eq!(foo_struct.bar, 20);
701 /// }
702 ///
703 /// // The contents of 'foo_slice' should not have changed
704 /// assert_eq!(foo_slice, [10]);
705 /// ```
706 #[inline]
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
709     ptr::read(src as *const T as *const U)
710 }
711
712 /// Opaque type representing the discriminant of an enum.
713 ///
714 /// See the `discriminant` function in this module for more information.
715 #[stable(feature = "discriminant_value", since = "1.22.0")]
716 pub struct Discriminant<T>(u64, PhantomData<*const T>);
717
718 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
719
720 #[stable(feature = "discriminant_value", since = "1.22.0")]
721 impl<T> Copy for Discriminant<T> {}
722
723 #[stable(feature = "discriminant_value", since = "1.22.0")]
724 impl<T> clone::Clone for Discriminant<T> {
725     fn clone(&self) -> Self {
726         *self
727     }
728 }
729
730 #[stable(feature = "discriminant_value", since = "1.22.0")]
731 impl<T> cmp::PartialEq for Discriminant<T> {
732     fn eq(&self, rhs: &Self) -> bool {
733         self.0 == rhs.0
734     }
735 }
736
737 #[stable(feature = "discriminant_value", since = "1.22.0")]
738 impl<T> cmp::Eq for Discriminant<T> {}
739
740 #[stable(feature = "discriminant_value", since = "1.22.0")]
741 impl<T> hash::Hash for Discriminant<T> {
742     fn hash<H: hash::Hasher>(&self, state: &mut H) {
743         self.0.hash(state);
744     }
745 }
746
747 #[stable(feature = "discriminant_value", since = "1.22.0")]
748 impl<T> fmt::Debug for Discriminant<T> {
749     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
750         fmt.debug_tuple("Discriminant")
751            .field(&self.0)
752            .finish()
753     }
754 }
755
756 /// Returns a value uniquely identifying the enum variant in `v`.
757 ///
758 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
759 /// return value is unspecified.
760 ///
761 /// # Stability
762 ///
763 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
764 /// of some variant will not change between compilations with the same compiler.
765 ///
766 /// # Examples
767 ///
768 /// This can be used to compare enums that carry data, while disregarding
769 /// the actual data:
770 ///
771 /// ```
772 /// use std::mem;
773 ///
774 /// enum Foo { A(&'static str), B(i32), C(i32) }
775 ///
776 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
777 /// assert!(mem::discriminant(&Foo::B(1))     == mem::discriminant(&Foo::B(2)));
778 /// assert!(mem::discriminant(&Foo::B(3))     != mem::discriminant(&Foo::C(3)));
779 /// ```
780 #[stable(feature = "discriminant_value", since = "1.22.0")]
781 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
782     unsafe {
783         Discriminant(intrinsics::discriminant_value(v), PhantomData)
784     }
785 }
786
787
788 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
789 ///
790 /// This wrapper is 0-cost.
791 ///
792 /// # Examples
793 ///
794 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
795 /// the type:
796 ///
797 /// ```rust
798 /// use std::mem::ManuallyDrop;
799 /// struct Peach;
800 /// struct Banana;
801 /// struct Melon;
802 /// struct FruitBox {
803 ///     // Immediately clear there’s something non-trivial going on with these fields.
804 ///     peach: ManuallyDrop<Peach>,
805 ///     melon: Melon, // Field that’s independent of the other two.
806 ///     banana: ManuallyDrop<Banana>,
807 /// }
808 ///
809 /// impl Drop for FruitBox {
810 ///     fn drop(&mut self) {
811 ///         unsafe {
812 ///             // Explicit ordering in which field destructors are run specified in the intuitive
813 ///             // location – the destructor of the structure containing the fields.
814 ///             // Moreover, one can now reorder fields within the struct however much they want.
815 ///             ManuallyDrop::drop(&mut self.peach);
816 ///             ManuallyDrop::drop(&mut self.banana);
817 ///         }
818 ///         // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
819 ///         // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
820 ///     }
821 /// }
822 /// ```
823 #[stable(feature = "manually_drop", since = "1.20.0")]
824 #[allow(unions_with_drop_fields)]
825 #[derive(Copy)]
826 pub union ManuallyDrop<T>{ value: T }
827
828 impl<T> ManuallyDrop<T> {
829     /// Wrap a value to be manually dropped.
830     ///
831     /// # Examples
832     ///
833     /// ```rust
834     /// use std::mem::ManuallyDrop;
835     /// ManuallyDrop::new(Box::new(()));
836     /// ```
837     #[stable(feature = "manually_drop", since = "1.20.0")]
838     #[inline]
839     pub fn new(value: T) -> ManuallyDrop<T> {
840         ManuallyDrop { value: value }
841     }
842
843     /// Extract the value from the ManuallyDrop container.
844     ///
845     /// # Examples
846     ///
847     /// ```rust
848     /// use std::mem::ManuallyDrop;
849     /// let x = ManuallyDrop::new(Box::new(()));
850     /// let _: Box<()> = ManuallyDrop::into_inner(x);
851     /// ```
852     #[stable(feature = "manually_drop", since = "1.20.0")]
853     #[inline]
854     pub fn into_inner(slot: ManuallyDrop<T>) -> T {
855         unsafe {
856             slot.value
857         }
858     }
859
860     /// Manually drops the contained value.
861     ///
862     /// # Safety
863     ///
864     /// This function runs the destructor of the contained value and thus the wrapped value
865     /// now represents uninitialized data. It is up to the user of this method to ensure the
866     /// uninitialized data is not actually used.
867     #[stable(feature = "manually_drop", since = "1.20.0")]
868     #[inline]
869     pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
870         ptr::drop_in_place(&mut slot.value)
871     }
872 }
873
874 #[stable(feature = "manually_drop", since = "1.20.0")]
875 impl<T> Deref for ManuallyDrop<T> {
876     type Target = T;
877     #[inline]
878     fn deref(&self) -> &Self::Target {
879         unsafe {
880             &self.value
881         }
882     }
883 }
884
885 #[stable(feature = "manually_drop", since = "1.20.0")]
886 impl<T> DerefMut for ManuallyDrop<T> {
887     #[inline]
888     fn deref_mut(&mut self) -> &mut Self::Target {
889         unsafe {
890             &mut self.value
891         }
892     }
893 }
894
895 #[stable(feature = "manually_drop", since = "1.20.0")]
896 impl<T: ::fmt::Debug> ::fmt::Debug for ManuallyDrop<T> {
897     fn fmt(&self, fmt: &mut ::fmt::Formatter) -> ::fmt::Result {
898         unsafe {
899             fmt.debug_tuple("ManuallyDrop").field(&self.value).finish()
900         }
901     }
902 }
903
904 #[stable(feature = "manually_drop", since = "1.20.0")]
905 impl<T: Clone> Clone for ManuallyDrop<T> {
906     fn clone(&self) -> Self {
907         ManuallyDrop::new(self.deref().clone())
908     }
909
910     fn clone_from(&mut self, source: &Self) {
911         self.deref_mut().clone_from(source);
912     }
913 }
914
915 #[stable(feature = "manually_drop", since = "1.20.0")]
916 impl<T: Default> Default for ManuallyDrop<T> {
917     fn default() -> Self {
918         ManuallyDrop::new(Default::default())
919     }
920 }
921
922 #[stable(feature = "manually_drop", since = "1.20.0")]
923 impl<T: PartialEq> PartialEq for ManuallyDrop<T> {
924     fn eq(&self, other: &Self) -> bool {
925         self.deref().eq(other)
926     }
927
928     fn ne(&self, other: &Self) -> bool {
929         self.deref().ne(other)
930     }
931 }
932
933 #[stable(feature = "manually_drop", since = "1.20.0")]
934 impl<T: Eq> Eq for ManuallyDrop<T> {}
935
936 #[stable(feature = "manually_drop", since = "1.20.0")]
937 impl<T: PartialOrd> PartialOrd for ManuallyDrop<T> {
938     fn partial_cmp(&self, other: &Self) -> Option<::cmp::Ordering> {
939         self.deref().partial_cmp(other)
940     }
941
942     fn lt(&self, other: &Self) -> bool {
943         self.deref().lt(other)
944     }
945
946     fn le(&self, other: &Self) -> bool {
947         self.deref().le(other)
948     }
949
950     fn gt(&self, other: &Self) -> bool {
951         self.deref().gt(other)
952     }
953
954     fn ge(&self, other: &Self) -> bool {
955         self.deref().ge(other)
956     }
957 }
958
959 #[stable(feature = "manually_drop", since = "1.20.0")]
960 impl<T: Ord> Ord for ManuallyDrop<T> {
961     fn cmp(&self, other: &Self) -> ::cmp::Ordering {
962         self.deref().cmp(other)
963     }
964 }
965
966 #[stable(feature = "manually_drop", since = "1.20.0")]
967 impl<T: ::hash::Hash> ::hash::Hash for ManuallyDrop<T> {
968     fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
969         self.deref().hash(state);
970     }
971 }
972
973 /// Tells LLVM that this point in the code is not reachable, enabling further
974 /// optimizations.
975 ///
976 /// NB: This is very different from the `unreachable!()` macro: Unlike the
977 /// macro, which panics when it is executed, it is *undefined behavior* to
978 /// reach code marked with this function.
979 #[inline]
980 #[unstable(feature = "unreachable", issue = "43751")]
981 pub unsafe fn unreachable() -> ! {
982     intrinsics::unreachable()
983 }