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