]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem/mod.rs
Clean up E0207 explanation
[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 = "none")]
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 #[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     intrinsics::size_of_val(val)
303 }
304
305 /// Returns the [ABI]-required minimum alignment of a type.
306 ///
307 /// Every reference to a value of the type `T` must be a multiple of this number.
308 ///
309 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
310 ///
311 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// # #![allow(deprecated)]
317 /// use std::mem;
318 ///
319 /// assert_eq!(4, mem::min_align_of::<i32>());
320 /// ```
321 #[inline]
322 #[stable(feature = "rust1", since = "1.0.0")]
323 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
324 pub fn min_align_of<T>() -> usize {
325     intrinsics::min_align_of::<T>()
326 }
327
328 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
329 ///
330 /// Every reference to a value of the type `T` must be a multiple of this number.
331 ///
332 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
333 ///
334 /// # Examples
335 ///
336 /// ```
337 /// # #![allow(deprecated)]
338 /// use std::mem;
339 ///
340 /// assert_eq!(4, mem::min_align_of_val(&5i32));
341 /// ```
342 #[inline]
343 #[stable(feature = "rust1", since = "1.0.0")]
344 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
345 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
346     intrinsics::min_align_of_val(val)
347 }
348
349 /// Returns the [ABI]-required minimum alignment of a type.
350 ///
351 /// Every reference to a value of the type `T` must be a multiple of this number.
352 ///
353 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
354 ///
355 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// use std::mem;
361 ///
362 /// assert_eq!(4, mem::align_of::<i32>());
363 /// ```
364 #[inline(always)]
365 #[stable(feature = "rust1", since = "1.0.0")]
366 #[rustc_promotable]
367 #[rustc_const_stable(feature = "const_align_of", since = "1.32.0")]
368 pub const fn align_of<T>() -> usize {
369     intrinsics::min_align_of::<T>()
370 }
371
372 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
373 ///
374 /// Every reference to a value of the type `T` must be a multiple of this number.
375 ///
376 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
377 ///
378 /// # Examples
379 ///
380 /// ```
381 /// use std::mem;
382 ///
383 /// assert_eq!(4, mem::align_of_val(&5i32));
384 /// ```
385 #[inline]
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[allow(deprecated)]
388 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
389     min_align_of_val(val)
390 }
391
392 /// Returns `true` if dropping values of type `T` matters.
393 ///
394 /// This is purely an optimization hint, and may be implemented conservatively:
395 /// it may return `true` for types that don't actually need to be dropped.
396 /// As such always returning `true` would be a valid implementation of
397 /// this function. However if this function actually returns `false`, then you
398 /// can be certain dropping `T` has no side effect.
399 ///
400 /// Low level implementations of things like collections, which need to manually
401 /// drop their data, should use this function to avoid unnecessarily
402 /// trying to drop all their contents when they are destroyed. This might not
403 /// make a difference in release builds (where a loop that has no side-effects
404 /// is easily detected and eliminated), but is often a big win for debug builds.
405 ///
406 /// Note that [`drop_in_place`] already performs this check, so if your workload
407 /// can be reduced to some small number of [`drop_in_place`] calls, using this is
408 /// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
409 /// will do a single needs_drop check for all the values.
410 ///
411 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
412 /// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
413 /// values one at a time and should use this API.
414 ///
415 /// [`drop_in_place`]: ../ptr/fn.drop_in_place.html
416 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
417 ///
418 /// # Examples
419 ///
420 /// Here's an example of how a collection might make use of `needs_drop`:
421 ///
422 /// ```
423 /// use std::{mem, ptr};
424 ///
425 /// pub struct MyCollection<T> {
426 /// #   data: [T; 1],
427 ///     /* ... */
428 /// }
429 /// # impl<T> MyCollection<T> {
430 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
431 /// #   fn free_buffer(&mut self) {}
432 /// # }
433 ///
434 /// impl<T> Drop for MyCollection<T> {
435 ///     fn drop(&mut self) {
436 ///         unsafe {
437 ///             // drop the data
438 ///             if mem::needs_drop::<T>() {
439 ///                 for x in self.iter_mut() {
440 ///                     ptr::drop_in_place(x);
441 ///                 }
442 ///             }
443 ///             self.free_buffer();
444 ///         }
445 ///     }
446 /// }
447 /// ```
448 #[inline]
449 #[stable(feature = "needs_drop", since = "1.21.0")]
450 #[rustc_const_stable(feature = "const_needs_drop", since = "1.36.0")]
451 pub const fn needs_drop<T>() -> bool {
452     intrinsics::needs_drop::<T>()
453 }
454
455 /// Returns the value of type `T` represented by the all-zero byte-pattern.
456 ///
457 /// This means that, for example, the padding byte in `(u8, u16)` is not
458 /// necessarily zeroed.
459 ///
460 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
461 /// some type `T`. For example, the all-zero byte-pattern is not a valid value
462 /// for reference types (`&T` and `&mut T`). Using `zeroed` on such types
463 /// causes immediate [undefined behavior][ub] because [the Rust compiler assumes][inv]
464 /// that there always is a valid value in a variable it considers initialized.
465 ///
466 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
467 /// It is useful for FFI sometimes, but should generally be avoided.
468 ///
469 /// [zeroed]: union.MaybeUninit.html#method.zeroed
470 /// [ub]: ../../reference/behavior-considered-undefined.html
471 /// [inv]: union.MaybeUninit.html#initialization-invariant
472 ///
473 /// # Examples
474 ///
475 /// Correct usage of this function: initializing an integer with zero.
476 ///
477 /// ```
478 /// use std::mem;
479 ///
480 /// let x: i32 = unsafe { mem::zeroed() };
481 /// assert_eq!(0, x);
482 /// ```
483 ///
484 /// *Incorrect* usage of this function: initializing a reference with zero.
485 ///
486 /// ```rust,no_run
487 /// # #![allow(invalid_value)]
488 /// use std::mem;
489 ///
490 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
491 /// ```
492 #[inline]
493 #[stable(feature = "rust1", since = "1.0.0")]
494 #[allow(deprecated_in_future)]
495 #[allow(deprecated)]
496 #[rustc_diagnostic_item = "mem_zeroed"]
497 pub unsafe fn zeroed<T>() -> T {
498     intrinsics::panic_if_uninhabited::<T>();
499     intrinsics::init()
500 }
501
502 /// Bypasses Rust's normal memory-initialization checks by pretending to
503 /// produce a value of type `T`, while doing nothing at all.
504 ///
505 /// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
506 ///
507 /// The reason for deprecation is that the function basically cannot be used
508 /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
509 /// As the [`assume_init` documentation][assume_init] explains,
510 /// [the Rust compiler assumes][inv] that values are properly initialized.
511 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
512 /// undefined behavior for returning a `bool` that is not definitely either `true`
513 /// or `false`. Worse, truly uninitialized memory like what gets returned here
514 /// is special in that the compiler knows that it does not have a fixed value.
515 /// This makes it undefined behavior to have uninitialized data in a variable even
516 /// if that variable has an integer type.
517 /// (Notice that the rules around uninitialized integers are not finalized yet, but
518 /// until they are, it is advisable to avoid them.)
519 ///
520 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
521 /// [uninit]: union.MaybeUninit.html#method.uninit
522 /// [assume_init]: union.MaybeUninit.html#method.assume_init
523 /// [inv]: union.MaybeUninit.html#initialization-invariant
524 #[inline]
525 #[rustc_deprecated(since = "1.39.0", reason = "use `mem::MaybeUninit` instead")]
526 #[stable(feature = "rust1", since = "1.0.0")]
527 #[allow(deprecated_in_future)]
528 #[allow(deprecated)]
529 #[rustc_diagnostic_item = "mem_uninitialized"]
530 pub unsafe fn uninitialized<T>() -> T {
531     intrinsics::panic_if_uninhabited::<T>();
532     intrinsics::uninit()
533 }
534
535 /// Swaps the values at two mutable locations, without deinitializing either one.
536 ///
537 /// # Examples
538 ///
539 /// ```
540 /// use std::mem;
541 ///
542 /// let mut x = 5;
543 /// let mut y = 42;
544 ///
545 /// mem::swap(&mut x, &mut y);
546 ///
547 /// assert_eq!(42, x);
548 /// assert_eq!(5, y);
549 /// ```
550 #[inline]
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn swap<T>(x: &mut T, y: &mut T) {
553     // SAFETY: the raw pointers have been created from safe mutable references satisfying all the
554     // constraints on `ptr::swap_nonoverlapping_one`
555     unsafe {
556         ptr::swap_nonoverlapping_one(x, y);
557     }
558 }
559
560 /// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
561 ///
562 /// # Examples
563 ///
564 /// A simple example:
565 ///
566 /// ```
567 /// use std::mem;
568 ///
569 /// let mut v: Vec<i32> = vec![1, 2];
570 ///
571 /// let old_v = mem::take(&mut v);
572 /// assert_eq!(vec![1, 2], old_v);
573 /// assert!(v.is_empty());
574 /// ```
575 ///
576 /// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
577 /// Without `take` you can run into issues like these:
578 ///
579 /// ```compile_fail,E0507
580 /// struct Buffer<T> { buf: Vec<T> }
581 ///
582 /// impl<T> Buffer<T> {
583 ///     fn get_and_reset(&mut self) -> Vec<T> {
584 ///         // error: cannot move out of dereference of `&mut`-pointer
585 ///         let buf = self.buf;
586 ///         self.buf = Vec::new();
587 ///         buf
588 ///     }
589 /// }
590 /// ```
591 ///
592 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
593 /// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
594 /// `self`, allowing it to be returned:
595 ///
596 /// ```
597 /// use std::mem;
598 ///
599 /// # struct Buffer<T> { buf: Vec<T> }
600 /// impl<T> Buffer<T> {
601 ///     fn get_and_reset(&mut self) -> Vec<T> {
602 ///         mem::take(&mut self.buf)
603 ///     }
604 /// }
605 ///
606 /// let mut buffer = Buffer { buf: vec![0, 1] };
607 /// assert_eq!(buffer.buf.len(), 2);
608 ///
609 /// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
610 /// assert_eq!(buffer.buf.len(), 0);
611 /// ```
612 ///
613 /// [`Clone`]: ../../std/clone/trait.Clone.html
614 #[inline]
615 #[stable(feature = "mem_take", since = "1.40.0")]
616 pub fn take<T: Default>(dest: &mut T) -> T {
617     replace(dest, T::default())
618 }
619
620 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
621 ///
622 /// Neither value is dropped.
623 ///
624 /// # Examples
625 ///
626 /// A simple example:
627 ///
628 /// ```
629 /// use std::mem;
630 ///
631 /// let mut v: Vec<i32> = vec![1, 2];
632 ///
633 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
634 /// assert_eq!(vec![1, 2], old_v);
635 /// assert_eq!(vec![3, 4, 5], v);
636 /// ```
637 ///
638 /// `replace` allows consumption of a struct field by replacing it with another value.
639 /// Without `replace` you can run into issues like these:
640 ///
641 /// ```compile_fail,E0507
642 /// struct Buffer<T> { buf: Vec<T> }
643 ///
644 /// impl<T> Buffer<T> {
645 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
646 ///         // error: cannot move out of dereference of `&mut`-pointer
647 ///         let t = self.buf[i];
648 ///         self.buf[i] = v;
649 ///         t
650 ///     }
651 /// }
652 /// ```
653 ///
654 /// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
655 /// avoid the move. But `replace` can be used to disassociate the original value at that index from
656 /// `self`, allowing it to be returned:
657 ///
658 /// ```
659 /// # #![allow(dead_code)]
660 /// use std::mem;
661 ///
662 /// # struct Buffer<T> { buf: Vec<T> }
663 /// impl<T> Buffer<T> {
664 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
665 ///         mem::replace(&mut self.buf[i], v)
666 ///     }
667 /// }
668 ///
669 /// let mut buffer = Buffer { buf: vec![0, 1] };
670 /// assert_eq!(buffer.buf[0], 0);
671 ///
672 /// assert_eq!(buffer.replace_index(0, 2), 0);
673 /// assert_eq!(buffer.buf[0], 2);
674 /// ```
675 ///
676 /// [`Clone`]: ../../std/clone/trait.Clone.html
677 #[inline]
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
680     swap(dest, &mut src);
681     src
682 }
683
684 /// Disposes of a value.
685 ///
686 /// This does call the argument's implementation of [`Drop`][drop].
687 ///
688 /// This effectively does nothing for types which implement `Copy`, e.g.
689 /// integers. Such values are copied and _then_ moved into the function, so the
690 /// value persists after this function call.
691 ///
692 /// This function is not magic; it is literally defined as
693 ///
694 /// ```
695 /// pub fn drop<T>(_x: T) { }
696 /// ```
697 ///
698 /// Because `_x` is moved into the function, it is automatically dropped before
699 /// the function returns.
700 ///
701 /// [drop]: ../ops/trait.Drop.html
702 ///
703 /// # Examples
704 ///
705 /// Basic usage:
706 ///
707 /// ```
708 /// let v = vec![1, 2, 3];
709 ///
710 /// drop(v); // explicitly drop the vector
711 /// ```
712 ///
713 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
714 /// release a [`RefCell`] borrow:
715 ///
716 /// ```
717 /// use std::cell::RefCell;
718 ///
719 /// let x = RefCell::new(1);
720 ///
721 /// let mut mutable_borrow = x.borrow_mut();
722 /// *mutable_borrow = 1;
723 ///
724 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
725 ///
726 /// let borrow = x.borrow();
727 /// println!("{}", *borrow);
728 /// ```
729 ///
730 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
731 ///
732 /// ```
733 /// #[derive(Copy, Clone)]
734 /// struct Foo(u8);
735 ///
736 /// let x = 1;
737 /// let y = Foo(2);
738 /// drop(x); // a copy of `x` is moved and dropped
739 /// drop(y); // a copy of `y` is moved and dropped
740 ///
741 /// println!("x: {}, y: {}", x, y.0); // still available
742 /// ```
743 ///
744 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
745 /// [`Copy`]: ../../std/marker/trait.Copy.html
746 #[inline]
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn drop<T>(_x: T) {}
749
750 /// Interprets `src` as having type `&U`, and then reads `src` without moving
751 /// the contained value.
752 ///
753 /// This function will unsafely assume the pointer `src` is valid for
754 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
755 /// the `&U`. It will also unsafely create a copy of the contained value instead of
756 /// moving out of `src`.
757 ///
758 /// It is not a compile-time error if `T` and `U` have different sizes, but it
759 /// is highly encouraged to only invoke this function where `T` and `U` have the
760 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
761 /// `T`.
762 ///
763 /// [ub]: ../../reference/behavior-considered-undefined.html
764 /// [size_of]: fn.size_of.html
765 ///
766 /// # Examples
767 ///
768 /// ```
769 /// use std::mem;
770 ///
771 /// #[repr(packed)]
772 /// struct Foo {
773 ///     bar: u8,
774 /// }
775 ///
776 /// let foo_array = [10u8];
777 ///
778 /// unsafe {
779 ///     // Copy the data from 'foo_array' and treat it as a 'Foo'
780 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
781 ///     assert_eq!(foo_struct.bar, 10);
782 ///
783 ///     // Modify the copied data
784 ///     foo_struct.bar = 20;
785 ///     assert_eq!(foo_struct.bar, 20);
786 /// }
787 ///
788 /// // The contents of 'foo_array' should not have changed
789 /// assert_eq!(foo_array, [10]);
790 /// ```
791 #[inline]
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
794     ptr::read_unaligned(src as *const T as *const U)
795 }
796
797 /// Opaque type representing the discriminant of an enum.
798 ///
799 /// See the [`discriminant`] function in this module for more information.
800 ///
801 /// [`discriminant`]: fn.discriminant.html
802 #[stable(feature = "discriminant_value", since = "1.21.0")]
803 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
804
805 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
806
807 #[stable(feature = "discriminant_value", since = "1.21.0")]
808 impl<T> Copy for Discriminant<T> {}
809
810 #[stable(feature = "discriminant_value", since = "1.21.0")]
811 impl<T> clone::Clone for Discriminant<T> {
812     fn clone(&self) -> Self {
813         *self
814     }
815 }
816
817 #[stable(feature = "discriminant_value", since = "1.21.0")]
818 impl<T> cmp::PartialEq for Discriminant<T> {
819     fn eq(&self, rhs: &Self) -> bool {
820         self.0 == rhs.0
821     }
822 }
823
824 #[stable(feature = "discriminant_value", since = "1.21.0")]
825 impl<T> cmp::Eq for Discriminant<T> {}
826
827 #[stable(feature = "discriminant_value", since = "1.21.0")]
828 impl<T> hash::Hash for Discriminant<T> {
829     fn hash<H: hash::Hasher>(&self, state: &mut H) {
830         self.0.hash(state);
831     }
832 }
833
834 #[stable(feature = "discriminant_value", since = "1.21.0")]
835 impl<T> fmt::Debug for Discriminant<T> {
836     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
837         fmt.debug_tuple("Discriminant").field(&self.0).finish()
838     }
839 }
840
841 /// Returns a value uniquely identifying the enum variant in `v`.
842 ///
843 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
844 /// return value is unspecified.
845 ///
846 /// # Stability
847 ///
848 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
849 /// of some variant will not change between compilations with the same compiler.
850 ///
851 /// # Examples
852 ///
853 /// This can be used to compare enums that carry data, while disregarding
854 /// the actual data:
855 ///
856 /// ```
857 /// use std::mem;
858 ///
859 /// enum Foo { A(&'static str), B(i32), C(i32) }
860 ///
861 /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
862 /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
863 /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
864 /// ```
865 #[stable(feature = "discriminant_value", since = "1.21.0")]
866 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
867     Discriminant(intrinsics::discriminant_value(v), PhantomData)
868 }