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, DiscriminantKind, 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`].
35 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`].
36 /// * If you want to dispose of a value properly, running its destructor, see
37 /// [`mem::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 resource 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 /// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone.
80 /// [`ManuallyDrop`] should be used instead. 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(), v.len(), 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. Even when a value is just moved to `mem::forget` (which won't
101 ///   inspect it), 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, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity());
117 /// // Finally, build a `String`.
118 /// let s = unsafe { String::from_raw_parts(ptr, len, cap) };
119 /// assert_eq!(s, "Az");
120 /// // `s` is implicitly dropped and its memory deallocated.
121 /// ```
122 ///
123 /// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor
124 /// before doing anything else. `mem::forget()` doesn't allow this because it consumes its
125 /// argument, forcing us to call it only after extracting anything we need from `v`. Even
126 /// if a panic were introduced between construction of `ManuallyDrop` and building the
127 /// string (which cannot happen in the code as shown), it would result in a leak and not a
128 /// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of
129 /// erring on the side of (double-)dropping.
130 ///
131 /// Also, `ManuallyDrop` prevents us from having to "touch" `v` after transferring the
132 /// ownership to `s` — the final step of interacting with `v` to dispose of it without
133 /// running its destructor is entirely avoided.
134 ///
135 /// [`Box`]: ../../std/boxed/struct.Box.html
136 /// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak
137 /// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw
138 /// [`mem::drop`]: drop
139 /// [ub]: ../../reference/behavior-considered-undefined.html
140 #[inline]
141 #[rustc_const_stable(feature = "const_forget", since = "1.46.0")]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_forget")]
forget<T>(t: T)144 pub const fn forget<T>(t: T) {
145     let _ = ManuallyDrop::new(t);
146 }
147 
148 /// Like [`forget`], but also accepts unsized values.
149 ///
150 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
151 /// stabilized.
152 #[inline]
153 #[unstable(feature = "forget_unsized", issue = "none")]
forget_unsized<T: ?Sized>(t: T)154 pub fn forget_unsized<T: ?Sized>(t: T) {
155     intrinsics::forget(t)
156 }
157 
158 /// Returns the size of a type in bytes.
159 ///
160 /// More specifically, this is the offset in bytes between successive elements
161 /// in an array with that item type including alignment padding. Thus, for any
162 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
163 ///
164 /// In general, the size of a type is not stable across compilations, but
165 /// specific types such as primitives are.
166 ///
167 /// The following table gives the size for primitives.
168 ///
169 /// Type | size_of::\<Type>()
170 /// ---- | ---------------
171 /// () | 0
172 /// bool | 1
173 /// u8 | 1
174 /// u16 | 2
175 /// u32 | 4
176 /// u64 | 8
177 /// u128 | 16
178 /// i8 | 1
179 /// i16 | 2
180 /// i32 | 4
181 /// i64 | 8
182 /// i128 | 16
183 /// f32 | 4
184 /// f64 | 8
185 /// char | 4
186 ///
187 /// Furthermore, `usize` and `isize` have the same size.
188 ///
189 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
190 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
191 ///
192 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
193 /// have the same size. Likewise for `*const T` and `*mut T`.
194 ///
195 /// # Size of `#[repr(C)]` items
196 ///
197 /// The `C` representation for items has a defined layout. With this layout,
198 /// the size of items is also stable as long as all fields have a stable size.
199 ///
200 /// ## Size of Structs
201 ///
202 /// For `structs`, the size is determined by the following algorithm.
203 ///
204 /// For each field in the struct ordered by declaration order:
205 ///
206 /// 1. Add the size of the field.
207 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
208 ///
209 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
210 /// The alignment of the struct is usually the largest alignment of all its
211 /// fields; this can be changed with the use of `repr(align(N))`.
212 ///
213 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
214 ///
215 /// ## Size of Enums
216 ///
217 /// Enums that carry no data other than the discriminant have the same size as C enums
218 /// on the platform they are compiled for.
219 ///
220 /// ## Size of Unions
221 ///
222 /// The size of a union is the size of its largest field.
223 ///
224 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// use std::mem;
230 ///
231 /// // Some primitives
232 /// assert_eq!(4, mem::size_of::<i32>());
233 /// assert_eq!(8, mem::size_of::<f64>());
234 /// assert_eq!(0, mem::size_of::<()>());
235 ///
236 /// // Some arrays
237 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
238 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
239 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
240 ///
241 ///
242 /// // Pointer size equality
243 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
244 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
245 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
246 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
247 /// ```
248 ///
249 /// Using `#[repr(C)]`.
250 ///
251 /// ```
252 /// use std::mem;
253 ///
254 /// #[repr(C)]
255 /// struct FieldStruct {
256 ///     first: u8,
257 ///     second: u16,
258 ///     third: u8
259 /// }
260 ///
261 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
262 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
263 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
264 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
265 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
266 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
267 /// // fields is 2), so add 1 to the size for padding. Size is 6.
268 /// assert_eq!(6, mem::size_of::<FieldStruct>());
269 ///
270 /// #[repr(C)]
271 /// struct TupleStruct(u8, u16, u8);
272 ///
273 /// // Tuple structs follow the same rules.
274 /// assert_eq!(6, mem::size_of::<TupleStruct>());
275 ///
276 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
277 /// // by putting `third` before `second`.
278 /// #[repr(C)]
279 /// struct FieldStructOptimized {
280 ///     first: u8,
281 ///     third: u8,
282 ///     second: u16
283 /// }
284 ///
285 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
286 ///
287 /// // Union size is the size of the largest field.
288 /// #[repr(C)]
289 /// union ExampleUnion {
290 ///     smaller: u8,
291 ///     larger: u16
292 /// }
293 ///
294 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
295 /// ```
296 ///
297 /// [alignment]: align_of
298 #[inline(always)]
299 #[must_use]
300 #[stable(feature = "rust1", since = "1.0.0")]
301 #[rustc_promotable]
302 #[rustc_const_stable(feature = "const_size_of", since = "1.24.0")]
303 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of")]
size_of<T>() -> usize304 pub const fn size_of<T>() -> usize {
305     intrinsics::size_of::<T>()
306 }
307 
308 /// Returns the size of the pointed-to value in bytes.
309 ///
310 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
311 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
312 /// then `size_of_val` can be used to get the dynamically-known size.
313 ///
314 /// [trait object]: ../../book/ch17-02-trait-objects.html
315 ///
316 /// # Examples
317 ///
318 /// ```
319 /// use std::mem;
320 ///
321 /// assert_eq!(4, mem::size_of_val(&5i32));
322 ///
323 /// let x: [u8; 13] = [0; 13];
324 /// let y: &[u8] = &x;
325 /// assert_eq!(13, mem::size_of_val(y));
326 /// ```
327 #[inline]
328 #[must_use]
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")]
331 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")]
size_of_val<T: ?Sized>(val: &T) -> usize332 pub const fn size_of_val<T: ?Sized>(val: &T) -> usize {
333     // SAFETY: `val` is a reference, so it's a valid raw pointer
334     unsafe { intrinsics::size_of_val(val) }
335 }
336 
337 /// Returns the size of the pointed-to value in bytes.
338 ///
339 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
340 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
341 /// then `size_of_val_raw` can be used to get the dynamically-known size.
342 ///
343 /// # Safety
344 ///
345 /// This function is only safe to call if the following conditions hold:
346 ///
347 /// - If `T` is `Sized`, this function is always safe to call.
348 /// - If the unsized tail of `T` is:
349 ///     - a [slice], then the length of the slice tail must be an initialized
350 ///       integer, and the size of the *entire value*
351 ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
352 ///     - a [trait object], then the vtable part of the pointer must point
353 ///       to a valid vtable acquired by an unsizing coercion, and the size
354 ///       of the *entire value* (dynamic tail length + statically sized prefix)
355 ///       must fit in `isize`.
356 ///     - an (unstable) [extern type], then this function is always safe to
357 ///       call, but may panic or otherwise return the wrong value, as the
358 ///       extern type's layout is not known. This is the same behavior as
359 ///       [`size_of_val`] on a reference to a type with an extern type tail.
360 ///     - otherwise, it is conservatively not allowed to call this function.
361 ///
362 /// [trait object]: ../../book/ch17-02-trait-objects.html
363 /// [extern type]: ../../unstable-book/language-features/extern-types.html
364 ///
365 /// # Examples
366 ///
367 /// ```
368 /// #![feature(layout_for_ptr)]
369 /// use std::mem;
370 ///
371 /// assert_eq!(4, mem::size_of_val(&5i32));
372 ///
373 /// let x: [u8; 13] = [0; 13];
374 /// let y: &[u8] = &x;
375 /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) });
376 /// ```
377 #[inline]
378 #[must_use]
379 #[unstable(feature = "layout_for_ptr", issue = "69835")]
380 #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")]
size_of_val_raw<T: ?Sized>(val: *const T) -> usize381 pub const unsafe fn size_of_val_raw<T: ?Sized>(val: *const T) -> usize {
382     // SAFETY: the caller must provide a valid raw pointer
383     unsafe { intrinsics::size_of_val(val) }
384 }
385 
386 /// Returns the [ABI]-required minimum alignment of a type.
387 ///
388 /// Every reference to a value of the type `T` must be a multiple of this number.
389 ///
390 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
391 ///
392 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
393 ///
394 /// # Examples
395 ///
396 /// ```
397 /// # #![allow(deprecated)]
398 /// use std::mem;
399 ///
400 /// assert_eq!(4, mem::min_align_of::<i32>());
401 /// ```
402 #[inline]
403 #[must_use]
404 #[stable(feature = "rust1", since = "1.0.0")]
405 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
min_align_of<T>() -> usize406 pub fn min_align_of<T>() -> usize {
407     intrinsics::min_align_of::<T>()
408 }
409 
410 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
411 ///
412 /// Every reference to a value of the type `T` must be a multiple of this number.
413 ///
414 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// # #![allow(deprecated)]
420 /// use std::mem;
421 ///
422 /// assert_eq!(4, mem::min_align_of_val(&5i32));
423 /// ```
424 #[inline]
425 #[must_use]
426 #[stable(feature = "rust1", since = "1.0.0")]
427 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
min_align_of_val<T: ?Sized>(val: &T) -> usize428 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
429     // SAFETY: val is a reference, so it's a valid raw pointer
430     unsafe { intrinsics::min_align_of_val(val) }
431 }
432 
433 /// Returns the [ABI]-required minimum alignment of a type.
434 ///
435 /// Every reference to a value of the type `T` must be a multiple of this number.
436 ///
437 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
438 ///
439 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use std::mem;
445 ///
446 /// assert_eq!(4, mem::align_of::<i32>());
447 /// ```
448 #[inline(always)]
449 #[must_use]
450 #[stable(feature = "rust1", since = "1.0.0")]
451 #[rustc_promotable]
452 #[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
align_of<T>() -> usize453 pub const fn align_of<T>() -> usize {
454     intrinsics::min_align_of::<T>()
455 }
456 
457 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
458 ///
459 /// Every reference to a value of the type `T` must be a multiple of this number.
460 ///
461 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
462 ///
463 /// # Examples
464 ///
465 /// ```
466 /// use std::mem;
467 ///
468 /// assert_eq!(4, mem::align_of_val(&5i32));
469 /// ```
470 #[inline]
471 #[must_use]
472 #[stable(feature = "rust1", since = "1.0.0")]
473 #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")]
474 #[allow(deprecated)]
align_of_val<T: ?Sized>(val: &T) -> usize475 pub const fn align_of_val<T: ?Sized>(val: &T) -> usize {
476     // SAFETY: val is a reference, so it's a valid raw pointer
477     unsafe { intrinsics::min_align_of_val(val) }
478 }
479 
480 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
481 ///
482 /// Every reference to a value of the type `T` must be a multiple of this number.
483 ///
484 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
485 ///
486 /// # Safety
487 ///
488 /// This function is only safe to call if the following conditions hold:
489 ///
490 /// - If `T` is `Sized`, this function is always safe to call.
491 /// - If the unsized tail of `T` is:
492 ///     - a [slice], then the length of the slice tail must be an initialized
493 ///       integer, and the size of the *entire value*
494 ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
495 ///     - a [trait object], then the vtable part of the pointer must point
496 ///       to a valid vtable acquired by an unsizing coercion, and the size
497 ///       of the *entire value* (dynamic tail length + statically sized prefix)
498 ///       must fit in `isize`.
499 ///     - an (unstable) [extern type], then this function is always safe to
500 ///       call, but may panic or otherwise return the wrong value, as the
501 ///       extern type's layout is not known. This is the same behavior as
502 ///       [`align_of_val`] on a reference to a type with an extern type tail.
503 ///     - otherwise, it is conservatively not allowed to call this function.
504 ///
505 /// [trait object]: ../../book/ch17-02-trait-objects.html
506 /// [extern type]: ../../unstable-book/language-features/extern-types.html
507 ///
508 /// # Examples
509 ///
510 /// ```
511 /// #![feature(layout_for_ptr)]
512 /// use std::mem;
513 ///
514 /// assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) });
515 /// ```
516 #[inline]
517 #[must_use]
518 #[unstable(feature = "layout_for_ptr", issue = "69835")]
519 #[rustc_const_unstable(feature = "const_align_of_val_raw", issue = "46571")]
align_of_val_raw<T: ?Sized>(val: *const T) -> usize520 pub const unsafe fn align_of_val_raw<T: ?Sized>(val: *const T) -> usize {
521     // SAFETY: the caller must provide a valid raw pointer
522     unsafe { intrinsics::min_align_of_val(val) }
523 }
524 
525 /// Returns `true` if dropping values of type `T` matters.
526 ///
527 /// This is purely an optimization hint, and may be implemented conservatively:
528 /// it may return `true` for types that don't actually need to be dropped.
529 /// As such always returning `true` would be a valid implementation of
530 /// this function. However if this function actually returns `false`, then you
531 /// can be certain dropping `T` has no side effect.
532 ///
533 /// Low level implementations of things like collections, which need to manually
534 /// drop their data, should use this function to avoid unnecessarily
535 /// trying to drop all their contents when they are destroyed. This might not
536 /// make a difference in release builds (where a loop that has no side-effects
537 /// is easily detected and eliminated), but is often a big win for debug builds.
538 ///
539 /// Note that [`drop_in_place`] already performs this check, so if your workload
540 /// can be reduced to some small number of [`drop_in_place`] calls, using this is
541 /// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
542 /// will do a single needs_drop check for all the values.
543 ///
544 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
545 /// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
546 /// values one at a time and should use this API.
547 ///
548 /// [`drop_in_place`]: crate::ptr::drop_in_place
549 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
550 ///
551 /// # Examples
552 ///
553 /// Here's an example of how a collection might make use of `needs_drop`:
554 ///
555 /// ```
556 /// use std::{mem, ptr};
557 ///
558 /// pub struct MyCollection<T> {
559 /// #   data: [T; 1],
560 ///     /* ... */
561 /// }
562 /// # impl<T> MyCollection<T> {
563 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
564 /// #   fn free_buffer(&mut self) {}
565 /// # }
566 ///
567 /// impl<T> Drop for MyCollection<T> {
568 ///     fn drop(&mut self) {
569 ///         unsafe {
570 ///             // drop the data
571 ///             if mem::needs_drop::<T>() {
572 ///                 for x in self.iter_mut() {
573 ///                     ptr::drop_in_place(x);
574 ///                 }
575 ///             }
576 ///             self.free_buffer();
577 ///         }
578 ///     }
579 /// }
580 /// ```
581 #[inline]
582 #[must_use]
583 #[stable(feature = "needs_drop", since = "1.21.0")]
584 #[rustc_const_stable(feature = "const_needs_drop", since = "1.36.0")]
585 #[rustc_diagnostic_item = "needs_drop"]
needs_drop<T>() -> bool586 pub const fn needs_drop<T>() -> bool {
587     intrinsics::needs_drop::<T>()
588 }
589 
590 /// Returns the value of type `T` represented by the all-zero byte-pattern.
591 ///
592 /// This means that, for example, the padding byte in `(u8, u16)` is not
593 /// necessarily zeroed.
594 ///
595 /// There is no guarantee that an all-zero byte-pattern represents a valid value
596 /// of some type `T`. For example, the all-zero byte-pattern is not a valid value
597 /// for reference types (`&T`, `&mut T`) and functions pointers. Using `zeroed`
598 /// on such types causes immediate [undefined behavior][ub] because [the Rust
599 /// compiler assumes][inv] that there always is a valid value in a variable it
600 /// considers initialized.
601 ///
602 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
603 /// It is useful for FFI sometimes, but should generally be avoided.
604 ///
605 /// [zeroed]: MaybeUninit::zeroed
606 /// [ub]: ../../reference/behavior-considered-undefined.html
607 /// [inv]: MaybeUninit#initialization-invariant
608 ///
609 /// # Examples
610 ///
611 /// Correct usage of this function: initializing an integer with zero.
612 ///
613 /// ```
614 /// use std::mem;
615 ///
616 /// let x: i32 = unsafe { mem::zeroed() };
617 /// assert_eq!(0, x);
618 /// ```
619 ///
620 /// *Incorrect* usage of this function: initializing a reference with zero.
621 ///
622 /// ```rust,no_run
623 /// # #![allow(invalid_value)]
624 /// use std::mem;
625 ///
626 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
627 /// let _y: fn() = unsafe { mem::zeroed() }; // And again!
628 /// ```
629 #[inline(always)]
630 #[must_use]
631 #[stable(feature = "rust1", since = "1.0.0")]
632 #[allow(deprecated_in_future)]
633 #[allow(deprecated)]
634 #[rustc_diagnostic_item = "mem_zeroed"]
635 #[track_caller]
zeroed<T>() -> T636 pub unsafe fn zeroed<T>() -> T {
637     // SAFETY: the caller must guarantee that an all-zero value is valid for `T`.
638     unsafe {
639         intrinsics::assert_zero_valid::<T>();
640         MaybeUninit::zeroed().assume_init()
641     }
642 }
643 
644 /// Bypasses Rust's normal memory-initialization checks by pretending to
645 /// produce a value of type `T`, while doing nothing at all.
646 ///
647 /// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
648 ///
649 /// The reason for deprecation is that the function basically cannot be used
650 /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
651 /// As the [`assume_init` documentation][assume_init] explains,
652 /// [the Rust compiler assumes][inv] that values are properly initialized.
653 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
654 /// undefined behavior for returning a `bool` that is not definitely either `true`
655 /// or `false`. Worse, truly uninitialized memory like what gets returned here
656 /// is special in that the compiler knows that it does not have a fixed value.
657 /// This makes it undefined behavior to have uninitialized data in a variable even
658 /// if that variable has an integer type.
659 /// (Notice that the rules around uninitialized integers are not finalized yet, but
660 /// until they are, it is advisable to avoid them.)
661 ///
662 /// [uninit]: MaybeUninit::uninit
663 /// [assume_init]: MaybeUninit::assume_init
664 /// [inv]: MaybeUninit#initialization-invariant
665 #[inline(always)]
666 #[must_use]
667 #[rustc_deprecated(since = "1.39.0", reason = "use `mem::MaybeUninit` instead")]
668 #[stable(feature = "rust1", since = "1.0.0")]
669 #[allow(deprecated_in_future)]
670 #[allow(deprecated)]
671 #[rustc_diagnostic_item = "mem_uninitialized"]
672 #[track_caller]
uninitialized<T>() -> T673 pub unsafe fn uninitialized<T>() -> T {
674     // SAFETY: the caller must guarantee that an uninitialized value is valid for `T`.
675     unsafe {
676         intrinsics::assert_uninit_valid::<T>();
677         MaybeUninit::uninit().assume_init()
678     }
679 }
680 
681 /// Swaps the values at two mutable locations, without deinitializing either one.
682 ///
683 /// * If you want to swap with a default or dummy value, see [`take`].
684 /// * If you want to swap with a passed value, returning the old value, see [`replace`].
685 ///
686 /// # Examples
687 ///
688 /// ```
689 /// use std::mem;
690 ///
691 /// let mut x = 5;
692 /// let mut y = 42;
693 ///
694 /// mem::swap(&mut x, &mut y);
695 ///
696 /// assert_eq!(42, x);
697 /// assert_eq!(5, y);
698 /// ```
699 #[inline]
700 #[stable(feature = "rust1", since = "1.0.0")]
701 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
swap<T>(x: &mut T, y: &mut T)702 pub const fn swap<T>(x: &mut T, y: &mut T) {
703     // SAFETY: the raw pointers have been created from safe mutable references satisfying all the
704     // constraints on `ptr::swap_nonoverlapping_one`
705     unsafe {
706         ptr::swap_nonoverlapping_one(x, y);
707     }
708 }
709 
710 /// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
711 ///
712 /// * If you want to replace the values of two variables, see [`swap`].
713 /// * If you want to replace with a passed value instead of the default value, see [`replace`].
714 ///
715 /// # Examples
716 ///
717 /// A simple example:
718 ///
719 /// ```
720 /// use std::mem;
721 ///
722 /// let mut v: Vec<i32> = vec![1, 2];
723 ///
724 /// let old_v = mem::take(&mut v);
725 /// assert_eq!(vec![1, 2], old_v);
726 /// assert!(v.is_empty());
727 /// ```
728 ///
729 /// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
730 /// Without `take` you can run into issues like these:
731 ///
732 /// ```compile_fail,E0507
733 /// struct Buffer<T> { buf: Vec<T> }
734 ///
735 /// impl<T> Buffer<T> {
736 ///     fn get_and_reset(&mut self) -> Vec<T> {
737 ///         // error: cannot move out of dereference of `&mut`-pointer
738 ///         let buf = self.buf;
739 ///         self.buf = Vec::new();
740 ///         buf
741 ///     }
742 /// }
743 /// ```
744 ///
745 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
746 /// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
747 /// `self`, allowing it to be returned:
748 ///
749 /// ```
750 /// use std::mem;
751 ///
752 /// # struct Buffer<T> { buf: Vec<T> }
753 /// impl<T> Buffer<T> {
754 ///     fn get_and_reset(&mut self) -> Vec<T> {
755 ///         mem::take(&mut self.buf)
756 ///     }
757 /// }
758 ///
759 /// let mut buffer = Buffer { buf: vec![0, 1] };
760 /// assert_eq!(buffer.buf.len(), 2);
761 ///
762 /// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
763 /// assert_eq!(buffer.buf.len(), 0);
764 /// ```
765 #[inline]
766 #[stable(feature = "mem_take", since = "1.40.0")]
take<T: Default>(dest: &mut T) -> T767 pub fn take<T: Default>(dest: &mut T) -> T {
768     replace(dest, T::default())
769 }
770 
771 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
772 ///
773 /// Neither value is dropped.
774 ///
775 /// * If you want to replace the values of two variables, see [`swap`].
776 /// * If you want to replace with a default value, see [`take`].
777 ///
778 /// # Examples
779 ///
780 /// A simple example:
781 ///
782 /// ```
783 /// use std::mem;
784 ///
785 /// let mut v: Vec<i32> = vec![1, 2];
786 ///
787 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
788 /// assert_eq!(vec![1, 2], old_v);
789 /// assert_eq!(vec![3, 4, 5], v);
790 /// ```
791 ///
792 /// `replace` allows consumption of a struct field by replacing it with another value.
793 /// Without `replace` you can run into issues like these:
794 ///
795 /// ```compile_fail,E0507
796 /// struct Buffer<T> { buf: Vec<T> }
797 ///
798 /// impl<T> Buffer<T> {
799 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
800 ///         // error: cannot move out of dereference of `&mut`-pointer
801 ///         let t = self.buf[i];
802 ///         self.buf[i] = v;
803 ///         t
804 ///     }
805 /// }
806 /// ```
807 ///
808 /// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
809 /// avoid the move. But `replace` can be used to disassociate the original value at that index from
810 /// `self`, allowing it to be returned:
811 ///
812 /// ```
813 /// # #![allow(dead_code)]
814 /// use std::mem;
815 ///
816 /// # struct Buffer<T> { buf: Vec<T> }
817 /// impl<T> Buffer<T> {
818 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
819 ///         mem::replace(&mut self.buf[i], v)
820 ///     }
821 /// }
822 ///
823 /// let mut buffer = Buffer { buf: vec![0, 1] };
824 /// assert_eq!(buffer.buf[0], 0);
825 ///
826 /// assert_eq!(buffer.replace_index(0, 2), 0);
827 /// assert_eq!(buffer.buf[0], 2);
828 /// ```
829 #[inline]
830 #[stable(feature = "rust1", since = "1.0.0")]
831 #[must_use = "if you don't need the old value, you can just assign the new value directly"]
832 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
833 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")]
replace<T>(dest: &mut T, src: T) -> T834 pub const fn replace<T>(dest: &mut T, src: T) -> T {
835     // SAFETY: We read from `dest` but directly write `src` into it afterwards,
836     // such that the old value is not duplicated. Nothing is dropped and
837     // nothing here can panic.
838     unsafe {
839         let result = ptr::read(dest);
840         ptr::write(dest, src);
841         result
842     }
843 }
844 
845 /// Disposes of a value.
846 ///
847 /// This does so by calling the argument's implementation of [`Drop`][drop].
848 ///
849 /// This effectively does nothing for types which implement `Copy`, e.g.
850 /// integers. Such values are copied and _then_ moved into the function, so the
851 /// value persists after this function call.
852 ///
853 /// This function is not magic; it is literally defined as
854 ///
855 /// ```
856 /// pub fn drop<T>(_x: T) { }
857 /// ```
858 ///
859 /// Because `_x` is moved into the function, it is automatically dropped before
860 /// the function returns.
861 ///
862 /// [drop]: Drop
863 ///
864 /// # Examples
865 ///
866 /// Basic usage:
867 ///
868 /// ```
869 /// let v = vec![1, 2, 3];
870 ///
871 /// drop(v); // explicitly drop the vector
872 /// ```
873 ///
874 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
875 /// release a [`RefCell`] borrow:
876 ///
877 /// ```
878 /// use std::cell::RefCell;
879 ///
880 /// let x = RefCell::new(1);
881 ///
882 /// let mut mutable_borrow = x.borrow_mut();
883 /// *mutable_borrow = 1;
884 ///
885 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
886 ///
887 /// let borrow = x.borrow();
888 /// println!("{}", *borrow);
889 /// ```
890 ///
891 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
892 ///
893 /// ```
894 /// #[derive(Copy, Clone)]
895 /// struct Foo(u8);
896 ///
897 /// let x = 1;
898 /// let y = Foo(2);
899 /// drop(x); // a copy of `x` is moved and dropped
900 /// drop(y); // a copy of `y` is moved and dropped
901 ///
902 /// println!("x: {}, y: {}", x, y.0); // still available
903 /// ```
904 ///
905 /// [`RefCell`]: crate::cell::RefCell
906 #[inline]
907 #[stable(feature = "rust1", since = "1.0.0")]
908 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")]
drop<T>(_x: T)909 pub fn drop<T>(_x: T) {}
910 
911 /// Interprets `src` as having type `&U`, and then reads `src` without moving
912 /// the contained value.
913 ///
914 /// This function will unsafely assume the pointer `src` is valid for [`size_of::<U>`][size_of]
915 /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way
916 /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also
917 /// unsafely create a copy of the contained value instead of moving out of `src`.
918 ///
919 /// It is not a compile-time error if `T` and `U` have different sizes, but it
920 /// is highly encouraged to only invoke this function where `T` and `U` have the
921 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
922 /// `T`.
923 ///
924 /// [ub]: ../../reference/behavior-considered-undefined.html
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// use std::mem;
930 ///
931 /// #[repr(packed)]
932 /// struct Foo {
933 ///     bar: u8,
934 /// }
935 ///
936 /// let foo_array = [10u8];
937 ///
938 /// unsafe {
939 ///     // Copy the data from 'foo_array' and treat it as a 'Foo'
940 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
941 ///     assert_eq!(foo_struct.bar, 10);
942 ///
943 ///     // Modify the copied data
944 ///     foo_struct.bar = 20;
945 ///     assert_eq!(foo_struct.bar, 20);
946 /// }
947 ///
948 /// // The contents of 'foo_array' should not have changed
949 /// assert_eq!(foo_array, [10]);
950 /// ```
951 #[inline]
952 #[must_use]
953 #[stable(feature = "rust1", since = "1.0.0")]
954 #[rustc_const_unstable(feature = "const_transmute_copy", issue = "83165")]
transmute_copy<T, U>(src: &T) -> U955 pub const unsafe fn transmute_copy<T, U>(src: &T) -> U {
956     // If U has a higher alignment requirement, src might not be suitably aligned.
957     if align_of::<U>() > align_of::<T>() {
958         // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
959         // The caller must guarantee that the actual transmutation is safe.
960         unsafe { ptr::read_unaligned(src as *const T as *const U) }
961     } else {
962         // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
963         // We just checked that `src as *const U` was properly aligned.
964         // The caller must guarantee that the actual transmutation is safe.
965         unsafe { ptr::read(src as *const T as *const U) }
966     }
967 }
968 
969 /// Opaque type representing the discriminant of an enum.
970 ///
971 /// See the [`discriminant`] function in this module for more information.
972 #[stable(feature = "discriminant_value", since = "1.21.0")]
973 pub struct Discriminant<T>(<T as DiscriminantKind>::Discriminant);
974 
975 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
976 
977 #[stable(feature = "discriminant_value", since = "1.21.0")]
978 impl<T> Copy for Discriminant<T> {}
979 
980 #[stable(feature = "discriminant_value", since = "1.21.0")]
981 impl<T> clone::Clone for Discriminant<T> {
clone(&self) -> Self982     fn clone(&self) -> Self {
983         *self
984     }
985 }
986 
987 #[stable(feature = "discriminant_value", since = "1.21.0")]
988 impl<T> cmp::PartialEq for Discriminant<T> {
eq(&self, rhs: &Self) -> bool989     fn eq(&self, rhs: &Self) -> bool {
990         self.0 == rhs.0
991     }
992 }
993 
994 #[stable(feature = "discriminant_value", since = "1.21.0")]
995 impl<T> cmp::Eq for Discriminant<T> {}
996 
997 #[stable(feature = "discriminant_value", since = "1.21.0")]
998 impl<T> hash::Hash for Discriminant<T> {
hash<H: hash::Hasher>(&self, state: &mut H)999     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1000         self.0.hash(state);
1001     }
1002 }
1003 
1004 #[stable(feature = "discriminant_value", since = "1.21.0")]
1005 impl<T> fmt::Debug for Discriminant<T> {
fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result1006     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1007         fmt.debug_tuple("Discriminant").field(&self.0).finish()
1008     }
1009 }
1010 
1011 /// Returns a value uniquely identifying the enum variant in `v`.
1012 ///
1013 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1014 /// return value is unspecified.
1015 ///
1016 /// # Stability
1017 ///
1018 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
1019 /// of some variant will not change between compilations with the same compiler.
1020 ///
1021 /// # Examples
1022 ///
1023 /// This can be used to compare enums that carry data, while disregarding
1024 /// the actual data:
1025 ///
1026 /// ```
1027 /// use std::mem;
1028 ///
1029 /// enum Foo { A(&'static str), B(i32), C(i32) }
1030 ///
1031 /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
1032 /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
1033 /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
1034 /// ```
1035 #[stable(feature = "discriminant_value", since = "1.21.0")]
1036 #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")]
1037 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")]
discriminant<T>(v: &T) -> Discriminant<T>1038 pub const fn discriminant<T>(v: &T) -> Discriminant<T> {
1039     Discriminant(intrinsics::discriminant_value(v))
1040 }
1041 
1042 /// Returns the number of variants in the enum type `T`.
1043 ///
1044 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1045 /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX`
1046 /// the return value is unspecified. Uninhabited variants will be counted.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// # #![feature(never_type)]
1052 /// # #![feature(variant_count)]
1053 ///
1054 /// use std::mem;
1055 ///
1056 /// enum Void {}
1057 /// enum Foo { A(&'static str), B(i32), C(i32) }
1058 ///
1059 /// assert_eq!(mem::variant_count::<Void>(), 0);
1060 /// assert_eq!(mem::variant_count::<Foo>(), 3);
1061 ///
1062 /// assert_eq!(mem::variant_count::<Option<!>>(), 2);
1063 /// assert_eq!(mem::variant_count::<Result<!, !>>(), 2);
1064 /// ```
1065 #[inline(always)]
1066 #[must_use]
1067 #[unstable(feature = "variant_count", issue = "73662")]
1068 #[rustc_const_unstable(feature = "variant_count", issue = "73662")]
1069 #[rustc_diagnostic_item = "mem_variant_count"]
variant_count<T>() -> usize1070 pub const fn variant_count<T>() -> usize {
1071     intrinsics::variant_count::<T>()
1072 }
1073