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