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