]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem/mod.rs
Rollup merge of #67289 - estebank:unnamed-closure, r=Centril
[rust.git] / src / libcore / mem / mod.rs
1 //! Basic functions for dealing with memory.
2 //!
3 //! This module contains functions for querying the size and alignment of
4 //! types, initializing and manipulating memory.
5
6 #![stable(feature = "rust1", since = "1.0.0")]
7
8 use crate::clone;
9 use crate::cmp;
10 use crate::fmt;
11 use crate::hash;
12 use crate::intrinsics;
13 use crate::marker::{Copy, PhantomData, Sized};
14 use crate::ptr;
15
16 mod manually_drop;
17 #[stable(feature = "manually_drop", since = "1.20.0")]
18 pub use manually_drop::ManuallyDrop;
19
20 mod maybe_uninit;
21 #[stable(feature = "maybe_uninit", since = "1.36.0")]
22 pub use maybe_uninit::MaybeUninit;
23
24 #[stable(feature = "rust1", since = "1.0.0")]
25 #[doc(inline)]
26 pub use crate::intrinsics::transmute;
27
28 /// Takes ownership and "forgets" about the value **without running its destructor**.
29 ///
30 /// Any resources the value manages, such as heap memory or a file handle, will linger
31 /// forever in an unreachable state. However, it does not guarantee that pointers
32 /// to this memory will remain valid.
33 ///
34 /// * If you want to leak memory, see [`Box::leak`][leak].
35 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`][into_raw].
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 /// The need comes up in some specialized use cases for FFI or unsafe code, but even
50 /// then, [`ManuallyDrop`] is typically preferred.
51 ///
52 /// Because forgetting a value is allowed, any `unsafe` code you write must
53 /// allow for this possibility. You cannot return a value and expect that the
54 /// caller will necessarily run the value's destructor.
55 ///
56 /// [rc]: ../../std/rc/struct.Rc.html
57 /// [exit]: ../../std/process/fn.exit.html
58 ///
59 /// # Examples
60 ///
61 /// Leak an I/O object, never closing the file:
62 ///
63 /// ```no_run
64 /// use std::mem;
65 /// use std::fs::File;
66 ///
67 /// let file = File::open("foo.txt").unwrap();
68 /// mem::forget(file);
69 /// ```
70 ///
71 /// The practical use cases for `forget` are rather specialized and mainly come
72 /// up in unsafe or FFI code. However, [`ManuallyDrop`] is usually preferred
73 /// for such cases, e.g.:
74 ///
75 /// ```
76 /// use std::mem::ManuallyDrop;
77 ///
78 /// let v = vec![65, 122];
79 /// // Before we disassemble `v` into its raw parts, make sure it
80 /// // does not get dropped!
81 /// let mut v = ManuallyDrop::new(v);
82 /// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
83 /// let ptr = v.as_mut_ptr();
84 /// let cap = v.capacity();
85 /// // Finally, build a `String`.
86 /// let s = unsafe { String::from_raw_parts(ptr, 2, cap) };
87 /// assert_eq!(s, "Az");
88 /// // `s` is implicitly dropped and its memory deallocated.
89 /// ```
90 ///
91 /// Using `ManuallyDrop` here has two advantages:
92 ///
93 /// * We do not "touch" `v` after disassembling it. For some types, operations
94 ///   such as passing ownership (to a funcion like `mem::forget`) requires them to actually
95 ///   be fully owned right now; that is a promise we do not want to make here as we are
96 ///   in the process of transferring ownership to the new `String` we are building.
97 /// * In case of an unexpected panic, `ManuallyDrop` is not dropped, but if the panic
98 ///   occurs before `mem::forget` was called we might end up dropping invalid data,
99 ///   or double-dropping. In other words, `ManuallyDrop` errs on the side of leaking
100 ///   instead of erring on the side of dropping.
101 ///
102 /// [drop]: fn.drop.html
103 /// [uninit]: fn.uninitialized.html
104 /// [clone]: ../clone/trait.Clone.html
105 /// [swap]: fn.swap.html
106 /// [box]: ../../std/boxed/struct.Box.html
107 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
108 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
109 /// [ub]: ../../reference/behavior-considered-undefined.html
110 /// [`ManuallyDrop`]: struct.ManuallyDrop.html
111 #[inline]
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub fn forget<T>(t: T) {
114     ManuallyDrop::new(t);
115 }
116
117 /// Like [`forget`], but also accepts unsized values.
118 ///
119 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
120 /// stabilized.
121 ///
122 /// [`forget`]: fn.forget.html
123 #[inline]
124 #[unstable(feature = "forget_unsized", issue = "0")]
125 pub fn forget_unsized<T: ?Sized>(t: T) {
126     // SAFETY: the forget intrinsic could be safe, but there's no point in making it safe since
127     // we'll be implementing this function soon via `ManuallyDrop`
128     unsafe { intrinsics::forget(t) }
129 }
130
131 /// Returns the size of a type in bytes.
132 ///
133 /// More specifically, this is the offset in bytes between successive elements
134 /// in an array with that item type including alignment padding. Thus, for any
135 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
136 ///
137 /// In general, the size of a type is not stable across compilations, but
138 /// specific types such as primitives are.
139 ///
140 /// The following table gives the size for primitives.
141 ///
142 /// Type | size_of::\<Type>()
143 /// ---- | ---------------
144 /// () | 0
145 /// bool | 1
146 /// u8 | 1
147 /// u16 | 2
148 /// u32 | 4
149 /// u64 | 8
150 /// u128 | 16
151 /// i8 | 1
152 /// i16 | 2
153 /// i32 | 4
154 /// i64 | 8
155 /// i128 | 16
156 /// f32 | 4
157 /// f64 | 8
158 /// char | 4
159 ///
160 /// Furthermore, `usize` and `isize` have the same size.
161 ///
162 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
163 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
164 ///
165 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
166 /// have the same size. Likewise for `*const T` and `*mut T`.
167 ///
168 /// # Size of `#[repr(C)]` items
169 ///
170 /// The `C` representation for items has a defined layout. With this layout,
171 /// the size of items is also stable as long as all fields have a stable size.
172 ///
173 /// ## Size of Structs
174 ///
175 /// For `structs`, the size is determined by the following algorithm.
176 ///
177 /// For each field in the struct ordered by declaration order:
178 ///
179 /// 1. Add the size of the field.
180 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
181 ///
182 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
183 /// The alignment of the struct is usually the largest alignment of all its
184 /// fields; this can be changed with the use of `repr(align(N))`.
185 ///
186 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
187 ///
188 /// ## Size of Enums
189 ///
190 /// Enums that carry no data other than the discriminant have the same size as C enums
191 /// on the platform they are compiled for.
192 ///
193 /// ## Size of Unions
194 ///
195 /// The size of a union is the size of its largest field.
196 ///
197 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
198 ///
199 /// # Examples
200 ///
201 /// ```
202 /// use std::mem;
203 ///
204 /// // Some primitives
205 /// assert_eq!(4, mem::size_of::<i32>());
206 /// assert_eq!(8, mem::size_of::<f64>());
207 /// assert_eq!(0, mem::size_of::<()>());
208 ///
209 /// // Some arrays
210 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
211 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
212 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
213 ///
214 ///
215 /// // Pointer size equality
216 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
217 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
218 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
219 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
220 /// ```
221 ///
222 /// Using `#[repr(C)]`.
223 ///
224 /// ```
225 /// use std::mem;
226 ///
227 /// #[repr(C)]
228 /// struct FieldStruct {
229 ///     first: u8,
230 ///     second: u16,
231 ///     third: u8
232 /// }
233 ///
234 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
235 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
236 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
237 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
238 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
239 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
240 /// // fields is 2), so add 1 to the size for padding. Size is 6.
241 /// assert_eq!(6, mem::size_of::<FieldStruct>());
242 ///
243 /// #[repr(C)]
244 /// struct TupleStruct(u8, u16, u8);
245 ///
246 /// // Tuple structs follow the same rules.
247 /// assert_eq!(6, mem::size_of::<TupleStruct>());
248 ///
249 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
250 /// // by putting `third` before `second`.
251 /// #[repr(C)]
252 /// struct FieldStructOptimized {
253 ///     first: u8,
254 ///     third: u8,
255 ///     second: u16
256 /// }
257 ///
258 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
259 ///
260 /// // Union size is the size of the largest field.
261 /// #[repr(C)]
262 /// union ExampleUnion {
263 ///     smaller: u8,
264 ///     larger: u16
265 /// }
266 ///
267 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
268 /// ```
269 ///
270 /// [alignment]: ./fn.align_of.html
271 #[inline(always)]
272 #[stable(feature = "rust1", since = "1.0.0")]
273 #[rustc_promotable]
274 #[cfg_attr(not(bootstrap), rustc_const_stable(feature = "const_size_of", since = "1.32.0"))]
275 pub const fn size_of<T>() -> usize {
276     intrinsics::size_of::<T>()
277 }
278
279 /// Returns the size of the pointed-to value in bytes.
280 ///
281 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
282 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
283 /// then `size_of_val` can be used to get the dynamically-known size.
284 ///
285 /// [slice]: ../../std/primitive.slice.html
286 /// [trait object]: ../../book/ch17-02-trait-objects.html
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// use std::mem;
292 ///
293 /// assert_eq!(4, mem::size_of_val(&5i32));
294 ///
295 /// let x: [u8; 13] = [0; 13];
296 /// let y: &[u8] = &x;
297 /// assert_eq!(13, mem::size_of_val(y));
298 /// ```
299 #[inline]
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
302     #[cfg(bootstrap)]
303     // SAFETY: going away soon
304     unsafe { intrinsics::size_of_val(val) }
305     #[cfg(not(bootstrap))]
306     intrinsics::size_of_val(val)
307 }
308
309 /// Returns the [ABI]-required minimum alignment of a type.
310 ///
311 /// Every reference to a value of the type `T` must be a multiple of this number.
312 ///
313 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
314 ///
315 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// # #![allow(deprecated)]
321 /// use std::mem;
322 ///
323 /// assert_eq!(4, mem::min_align_of::<i32>());
324 /// ```
325 #[inline]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
328 pub fn min_align_of<T>() -> usize {
329     intrinsics::min_align_of::<T>()
330 }
331
332 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
333 ///
334 /// Every reference to a value of the type `T` must be a multiple of this number.
335 ///
336 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
337 ///
338 /// # Examples
339 ///
340 /// ```
341 /// # #![allow(deprecated)]
342 /// use std::mem;
343 ///
344 /// assert_eq!(4, mem::min_align_of_val(&5i32));
345 /// ```
346 #[inline]
347 #[stable(feature = "rust1", since = "1.0.0")]
348 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
349 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
350     #[cfg(bootstrap)]
351     // SAFETY: going away soon
352     unsafe { intrinsics::min_align_of_val(val) }
353     #[cfg(not(bootstrap))]
354     intrinsics::min_align_of_val(val)
355 }
356
357 /// Returns the [ABI]-required minimum alignment of a type.
358 ///
359 /// Every reference to a value of the type `T` must be a multiple of this number.
360 ///
361 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
362 ///
363 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
364 ///
365 /// # Examples
366 ///
367 /// ```
368 /// use std::mem;
369 ///
370 /// assert_eq!(4, mem::align_of::<i32>());
371 /// ```
372 #[inline(always)]
373 #[stable(feature = "rust1", since = "1.0.0")]
374 #[rustc_promotable]
375 #[cfg_attr(not(bootstrap), rustc_const_stable(feature = "const_align_of", since = "1.32.0"))]
376 pub const fn align_of<T>() -> usize {
377     intrinsics::min_align_of::<T>()
378 }
379
380 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
381 ///
382 /// Every reference to a value of the type `T` must be a multiple of this number.
383 ///
384 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// use std::mem;
390 ///
391 /// assert_eq!(4, mem::align_of_val(&5i32));
392 /// ```
393 #[inline]
394 #[stable(feature = "rust1", since = "1.0.0")]
395 #[allow(deprecated)]
396 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
397     min_align_of_val(val)
398 }
399
400 /// Returns `true` if dropping values of type `T` matters.
401 ///
402 /// This is purely an optimization hint, and may be implemented conservatively:
403 /// it may return `true` for types that don't actually need to be dropped.
404 /// As such always returning `true` would be a valid implementation of
405 /// this function. However if this function actually returns `false`, then you
406 /// can be certain dropping `T` has no side effect.
407 ///
408 /// Low level implementations of things like collections, which need to manually
409 /// drop their data, should use this function to avoid unnecessarily
410 /// trying to drop all their contents when they are destroyed. This might not
411 /// make a difference in release builds (where a loop that has no side-effects
412 /// is easily detected and eliminated), but is often a big win for debug builds.
413 ///
414 /// Note that [`drop_in_place`] already performs this check, so if your workload
415 /// can be reduced to some small number of [`drop_in_place`] calls, using this is
416 /// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
417 /// will do a single needs_drop check for all the values.
418 ///
419 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
420 /// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
421 /// values one at a time and should use this API.
422 ///
423 /// [`drop_in_place`]: ../ptr/fn.drop_in_place.html
424 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
425 ///
426 /// # Examples
427 ///
428 /// Here's an example of how a collection might make use of `needs_drop`:
429 ///
430 /// ```
431 /// use std::{mem, ptr};
432 ///
433 /// pub struct MyCollection<T> {
434 /// #   data: [T; 1],
435 ///     /* ... */
436 /// }
437 /// # impl<T> MyCollection<T> {
438 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
439 /// #   fn free_buffer(&mut self) {}
440 /// # }
441 ///
442 /// impl<T> Drop for MyCollection<T> {
443 ///     fn drop(&mut self) {
444 ///         unsafe {
445 ///             // drop the data
446 ///             if mem::needs_drop::<T>() {
447 ///                 for x in self.iter_mut() {
448 ///                     ptr::drop_in_place(x);
449 ///                 }
450 ///             }
451 ///             self.free_buffer();
452 ///         }
453 ///     }
454 /// }
455 /// ```
456 #[inline]
457 #[stable(feature = "needs_drop", since = "1.21.0")]
458 #[cfg_attr(not(bootstrap), rustc_const_stable(feature = "const_needs_drop", since = "1.36.0"))]
459 pub const fn needs_drop<T>() -> bool {
460     intrinsics::needs_drop::<T>()
461 }
462
463 /// Returns the value of type `T` represented by the all-zero byte-pattern.
464 ///
465 /// This means that, for example, the padding byte in `(u8, u16)` is not
466 /// necessarily zeroed.
467 ///
468 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
469 /// some type `T`. For example, the all-zero byte-pattern is not a valid value
470 /// for reference types (`&T` and `&mut T`). Using `zeroed` on such types
471 /// causes immediate [undefined behavior][ub] because [the Rust compiler assumes][inv]
472 /// that there always is a valid value in a variable it considers initialized.
473 ///
474 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
475 /// It is useful for FFI sometimes, but should generally be avoided.
476 ///
477 /// [zeroed]: union.MaybeUninit.html#method.zeroed
478 /// [ub]: ../../reference/behavior-considered-undefined.html
479 /// [inv]: union.MaybeUninit.html#initialization-invariant
480 ///
481 /// # Examples
482 ///
483 /// Correct usage of this function: initializing an integer with zero.
484 ///
485 /// ```
486 /// use std::mem;
487 ///
488 /// let x: i32 = unsafe { mem::zeroed() };
489 /// assert_eq!(0, x);
490 /// ```
491 ///
492 /// *Incorrect* usage of this function: initializing a reference with zero.
493 ///
494 /// ```rust,no_run
495 /// # #![allow(invalid_value)]
496 /// use std::mem;
497 ///
498 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
499 /// ```
500 #[inline]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 #[allow(deprecated_in_future)]
503 #[allow(deprecated)]
504 #[cfg_attr(all(not(bootstrap)), rustc_diagnostic_item = "mem_zeroed")]
505 pub unsafe fn zeroed<T>() -> T {
506     intrinsics::panic_if_uninhabited::<T>();
507     intrinsics::init()
508 }
509
510 /// Bypasses Rust's normal memory-initialization checks by pretending to
511 /// produce a value of type `T`, while doing nothing at all.
512 ///
513 /// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
514 ///
515 /// The reason for deprecation is that the function basically cannot be used
516 /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
517 /// As the [`assume_init` documentation][assume_init] explains,
518 /// [the Rust compiler assumes][inv] that values are properly initialized.
519 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
520 /// undefined behavior for returning a `bool` that is not definitely either `true`
521 /// or `false`. Worse, truly uninitialized memory like what gets returned here
522 /// is special in that the compiler knows that it does not have a fixed value.
523 /// This makes it undefined behavior to have uninitialized data in a variable even
524 /// if that variable has an integer type.
525 /// (Notice that the rules around uninitialized integers are not finalized yet, but
526 /// until they are, it is advisable to avoid them.)
527 ///
528 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
529 /// [uninit]: union.MaybeUninit.html#method.uninit
530 /// [assume_init]: union.MaybeUninit.html#method.assume_init
531 /// [inv]: union.MaybeUninit.html#initialization-invariant
532 #[inline]
533 #[rustc_deprecated(since = "1.39.0", reason = "use `mem::MaybeUninit` instead")]
534 #[stable(feature = "rust1", since = "1.0.0")]
535 #[allow(deprecated_in_future)]
536 #[allow(deprecated)]
537 #[cfg_attr(all(not(bootstrap)), rustc_diagnostic_item = "mem_uninitialized")]
538 pub unsafe fn uninitialized<T>() -> T {
539     intrinsics::panic_if_uninhabited::<T>();
540     intrinsics::uninit()
541 }
542
543 /// Swaps the values at two mutable locations, without deinitializing either one.
544 ///
545 /// # Examples
546 ///
547 /// ```
548 /// use std::mem;
549 ///
550 /// let mut x = 5;
551 /// let mut y = 42;
552 ///
553 /// mem::swap(&mut x, &mut y);
554 ///
555 /// assert_eq!(42, x);
556 /// assert_eq!(5, y);
557 /// ```
558 #[inline]
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn swap<T>(x: &mut T, y: &mut T) {
561     // SAFETY: the raw pointers have been created from safe mutable references satisfying all the
562     // constraints on `ptr::swap_nonoverlapping_one`
563     unsafe {
564         ptr::swap_nonoverlapping_one(x, y);
565     }
566 }
567
568 /// Replace `dest` with the default value of `T`, and return the previous `dest` value.
569 ///
570 /// # Examples
571 ///
572 /// A simple example:
573 ///
574 /// ```
575 /// use std::mem;
576 ///
577 /// let mut v: Vec<i32> = vec![1, 2];
578 ///
579 /// let old_v = mem::take(&mut v);
580 /// assert_eq!(vec![1, 2], old_v);
581 /// assert!(v.is_empty());
582 /// ```
583 ///
584 /// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
585 /// Without `take` you can run into issues like these:
586 ///
587 /// ```compile_fail,E0507
588 /// struct Buffer<T> { buf: Vec<T> }
589 ///
590 /// impl<T> Buffer<T> {
591 ///     fn get_and_reset(&mut self) -> Vec<T> {
592 ///         // error: cannot move out of dereference of `&mut`-pointer
593 ///         let buf = self.buf;
594 ///         self.buf = Vec::new();
595 ///         buf
596 ///     }
597 /// }
598 /// ```
599 ///
600 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
601 /// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
602 /// `self`, allowing it to be returned:
603 ///
604 /// ```
605 /// use std::mem;
606 ///
607 /// # struct Buffer<T> { buf: Vec<T> }
608 /// impl<T> Buffer<T> {
609 ///     fn get_and_reset(&mut self) -> Vec<T> {
610 ///         mem::take(&mut self.buf)
611 ///     }
612 /// }
613 ///
614 /// let mut buffer = Buffer { buf: vec![0, 1] };
615 /// assert_eq!(buffer.buf.len(), 2);
616 ///
617 /// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
618 /// assert_eq!(buffer.buf.len(), 0);
619 /// ```
620 ///
621 /// [`Clone`]: ../../std/clone/trait.Clone.html
622 #[inline]
623 #[stable(feature = "mem_take", since = "1.40.0")]
624 pub fn take<T: Default>(dest: &mut T) -> T {
625     replace(dest, T::default())
626 }
627
628 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
629 ///
630 /// Neither value is dropped.
631 ///
632 /// # Examples
633 ///
634 /// A simple example:
635 ///
636 /// ```
637 /// use std::mem;
638 ///
639 /// let mut v: Vec<i32> = vec![1, 2];
640 ///
641 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
642 /// assert_eq!(vec![1, 2], old_v);
643 /// assert_eq!(vec![3, 4, 5], v);
644 /// ```
645 ///
646 /// `replace` allows consumption of a struct field by replacing it with another value.
647 /// Without `replace` you can run into issues like these:
648 ///
649 /// ```compile_fail,E0507
650 /// struct Buffer<T> { buf: Vec<T> }
651 ///
652 /// impl<T> Buffer<T> {
653 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
654 ///         // error: cannot move out of dereference of `&mut`-pointer
655 ///         let t = self.buf[i];
656 ///         self.buf[i] = v;
657 ///         t
658 ///     }
659 /// }
660 /// ```
661 ///
662 /// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
663 /// avoid the move. But `replace` can be used to disassociate the original value at that index from
664 /// `self`, allowing it to be returned:
665 ///
666 /// ```
667 /// # #![allow(dead_code)]
668 /// use std::mem;
669 ///
670 /// # struct Buffer<T> { buf: Vec<T> }
671 /// impl<T> Buffer<T> {
672 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
673 ///         mem::replace(&mut self.buf[i], v)
674 ///     }
675 /// }
676 ///
677 /// let mut buffer = Buffer { buf: vec![0, 1] };
678 /// assert_eq!(buffer.buf[0], 0);
679 ///
680 /// assert_eq!(buffer.replace_index(0, 2), 0);
681 /// assert_eq!(buffer.buf[0], 2);
682 /// ```
683 ///
684 /// [`Clone`]: ../../std/clone/trait.Clone.html
685 #[inline]
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
688     swap(dest, &mut src);
689     src
690 }
691
692 /// Disposes of a value.
693 ///
694 /// This does call the argument's implementation of [`Drop`][drop].
695 ///
696 /// This effectively does nothing for types which implement `Copy`, e.g.
697 /// integers. Such values are copied and _then_ moved into the function, so the
698 /// value persists after this function call.
699 ///
700 /// This function is not magic; it is literally defined as
701 ///
702 /// ```
703 /// pub fn drop<T>(_x: T) { }
704 /// ```
705 ///
706 /// Because `_x` is moved into the function, it is automatically dropped before
707 /// the function returns.
708 ///
709 /// [drop]: ../ops/trait.Drop.html
710 ///
711 /// # Examples
712 ///
713 /// Basic usage:
714 ///
715 /// ```
716 /// let v = vec![1, 2, 3];
717 ///
718 /// drop(v); // explicitly drop the vector
719 /// ```
720 ///
721 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
722 /// release a [`RefCell`] borrow:
723 ///
724 /// ```
725 /// use std::cell::RefCell;
726 ///
727 /// let x = RefCell::new(1);
728 ///
729 /// let mut mutable_borrow = x.borrow_mut();
730 /// *mutable_borrow = 1;
731 ///
732 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
733 ///
734 /// let borrow = x.borrow();
735 /// println!("{}", *borrow);
736 /// ```
737 ///
738 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
739 ///
740 /// ```
741 /// #[derive(Copy, Clone)]
742 /// struct Foo(u8);
743 ///
744 /// let x = 1;
745 /// let y = Foo(2);
746 /// drop(x); // a copy of `x` is moved and dropped
747 /// drop(y); // a copy of `y` is moved and dropped
748 ///
749 /// println!("x: {}, y: {}", x, y.0); // still available
750 /// ```
751 ///
752 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
753 /// [`Copy`]: ../../std/marker/trait.Copy.html
754 #[inline]
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn drop<T>(_x: T) { }
757
758 /// Interprets `src` as having type `&U`, and then reads `src` without moving
759 /// the contained value.
760 ///
761 /// This function will unsafely assume the pointer `src` is valid for
762 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
763 /// the `&U`. It will also unsafely create a copy of the contained value instead of
764 /// moving out of `src`.
765 ///
766 /// It is not a compile-time error if `T` and `U` have different sizes, but it
767 /// is highly encouraged to only invoke this function where `T` and `U` have the
768 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
769 /// `T`.
770 ///
771 /// [ub]: ../../reference/behavior-considered-undefined.html
772 /// [size_of]: fn.size_of.html
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// use std::mem;
778 ///
779 /// #[repr(packed)]
780 /// struct Foo {
781 ///     bar: u8,
782 /// }
783 ///
784 /// let foo_array = [10u8];
785 ///
786 /// unsafe {
787 ///     // Copy the data from 'foo_array' and treat it as a 'Foo'
788 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
789 ///     assert_eq!(foo_struct.bar, 10);
790 ///
791 ///     // Modify the copied data
792 ///     foo_struct.bar = 20;
793 ///     assert_eq!(foo_struct.bar, 20);
794 /// }
795 ///
796 /// // The contents of 'foo_array' should not have changed
797 /// assert_eq!(foo_array, [10]);
798 /// ```
799 #[inline]
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
802     ptr::read_unaligned(src as *const T as *const U)
803 }
804
805 /// Opaque type representing the discriminant of an enum.
806 ///
807 /// See the [`discriminant`] function in this module for more information.
808 ///
809 /// [`discriminant`]: fn.discriminant.html
810 #[stable(feature = "discriminant_value", since = "1.21.0")]
811 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
812
813 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
814
815 #[stable(feature = "discriminant_value", since = "1.21.0")]
816 impl<T> Copy for Discriminant<T> {}
817
818 #[stable(feature = "discriminant_value", since = "1.21.0")]
819 impl<T> clone::Clone for Discriminant<T> {
820     fn clone(&self) -> Self {
821         *self
822     }
823 }
824
825 #[stable(feature = "discriminant_value", since = "1.21.0")]
826 impl<T> cmp::PartialEq for Discriminant<T> {
827     fn eq(&self, rhs: &Self) -> bool {
828         self.0 == rhs.0
829     }
830 }
831
832 #[stable(feature = "discriminant_value", since = "1.21.0")]
833 impl<T> cmp::Eq for Discriminant<T> {}
834
835 #[stable(feature = "discriminant_value", since = "1.21.0")]
836 impl<T> hash::Hash for Discriminant<T> {
837     fn hash<H: hash::Hasher>(&self, state: &mut H) {
838         self.0.hash(state);
839     }
840 }
841
842 #[stable(feature = "discriminant_value", since = "1.21.0")]
843 impl<T> fmt::Debug for Discriminant<T> {
844     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
845         fmt.debug_tuple("Discriminant")
846            .field(&self.0)
847            .finish()
848     }
849 }
850
851 /// Returns a value uniquely identifying the enum variant in `v`.
852 ///
853 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
854 /// return value is unspecified.
855 ///
856 /// # Stability
857 ///
858 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
859 /// of some variant will not change between compilations with the same compiler.
860 ///
861 /// # Examples
862 ///
863 /// This can be used to compare enums that carry data, while disregarding
864 /// the actual data:
865 ///
866 /// ```
867 /// use std::mem;
868 ///
869 /// enum Foo { A(&'static str), B(i32), C(i32) }
870 ///
871 /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
872 /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
873 /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
874 /// ```
875 #[stable(feature = "discriminant_value", since = "1.21.0")]
876 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
877     #[cfg(bootstrap)]
878     // SAFETY: going away soon
879     unsafe {
880         Discriminant(intrinsics::discriminant_value(v), PhantomData)
881     }
882     #[cfg(not(bootstrap))]
883     Discriminant(intrinsics::discriminant_value(v), PhantomData)
884 }