]> git.lizzy.rs Git - rust.git/blob - library/core/src/mem/mod.rs
stage-step cfgs
[rust.git] / library / core / src / 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, 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 mod transmutability;
25 #[unstable(feature = "transmutability", issue = "99571")]
26 pub use transmutability::{Assume, BikeshedIntrinsicFrom};
27
28 #[stable(feature = "rust1", since = "1.0.0")]
29 #[doc(inline)]
30 pub use crate::intrinsics::transmute;
31
32 /// Takes ownership and "forgets" about the value **without running its destructor**.
33 ///
34 /// Any resources the value manages, such as heap memory or a file handle, will linger
35 /// forever in an unreachable state. However, it does not guarantee that pointers
36 /// to this memory will remain valid.
37 ///
38 /// * If you want to leak memory, see [`Box::leak`].
39 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`].
40 /// * If you want to dispose of a value properly, running its destructor, see
41 /// [`mem::drop`].
42 ///
43 /// # Safety
44 ///
45 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
46 /// do not include a guarantee that destructors will always run. For example,
47 /// a program can create a reference cycle using [`Rc`][rc], or call
48 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
49 /// `mem::forget` from safe code does not fundamentally change Rust's safety
50 /// guarantees.
51 ///
52 /// That said, leaking resources such as memory or I/O objects is usually undesirable.
53 /// The need comes up in some specialized use cases for FFI or unsafe code, but even
54 /// then, [`ManuallyDrop`] is typically preferred.
55 ///
56 /// Because forgetting a value is allowed, any `unsafe` code you write must
57 /// allow for this possibility. You cannot return a value and expect that the
58 /// caller will necessarily run the value's destructor.
59 ///
60 /// [rc]: ../../std/rc/struct.Rc.html
61 /// [exit]: ../../std/process/fn.exit.html
62 ///
63 /// # Examples
64 ///
65 /// The canonical safe use of `mem::forget` is to circumvent a value's destructor
66 /// implemented by the `Drop` trait. For example, this will leak a `File`, i.e. reclaim
67 /// the space taken by the variable but never close the underlying system resource:
68 ///
69 /// ```no_run
70 /// use std::mem;
71 /// use std::fs::File;
72 ///
73 /// let file = File::open("foo.txt").unwrap();
74 /// mem::forget(file);
75 /// ```
76 ///
77 /// This is useful when the ownership of the underlying resource was previously
78 /// transferred to code outside of Rust, for example by transmitting the raw
79 /// file descriptor to C code.
80 ///
81 /// # Relationship with `ManuallyDrop`
82 ///
83 /// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone.
84 /// [`ManuallyDrop`] should be used instead. Consider, for example, this code:
85 ///
86 /// ```
87 /// use std::mem;
88 ///
89 /// let mut v = vec![65, 122];
90 /// // Build a `String` using the contents of `v`
91 /// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) };
92 /// // leak `v` because its memory is now managed by `s`
93 /// mem::forget(v);  // ERROR - v is invalid and must not be passed to a function
94 /// assert_eq!(s, "Az");
95 /// // `s` is implicitly dropped and its memory deallocated.
96 /// ```
97 ///
98 /// There are two issues with the above example:
99 ///
100 /// * If more code were added between the construction of `String` and the invocation of
101 ///   `mem::forget()`, a panic within it would cause a double free because the same memory
102 ///   is handled by both `v` and `s`.
103 /// * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`,
104 ///   the `v` value is invalid. Even when a value is just moved to `mem::forget` (which won't
105 ///   inspect it), some types have strict requirements on their values that
106 ///   make them invalid when dangling or no longer owned. Using invalid values in any
107 ///   way, including passing them to or returning them from functions, constitutes
108 ///   undefined behavior and may break the assumptions made by the compiler.
109 ///
110 /// Switching to `ManuallyDrop` avoids both issues:
111 ///
112 /// ```
113 /// use std::mem::ManuallyDrop;
114 ///
115 /// let v = vec![65, 122];
116 /// // Before we disassemble `v` into its raw parts, make sure it
117 /// // does not get dropped!
118 /// let mut v = ManuallyDrop::new(v);
119 /// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
120 /// let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity());
121 /// // Finally, build a `String`.
122 /// let s = unsafe { String::from_raw_parts(ptr, len, cap) };
123 /// assert_eq!(s, "Az");
124 /// // `s` is implicitly dropped and its memory deallocated.
125 /// ```
126 ///
127 /// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor
128 /// before doing anything else. `mem::forget()` doesn't allow this because it consumes its
129 /// argument, forcing us to call it only after extracting anything we need from `v`. Even
130 /// if a panic were introduced between construction of `ManuallyDrop` and building the
131 /// string (which cannot happen in the code as shown), it would result in a leak and not a
132 /// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of
133 /// erring on the side of (double-)dropping.
134 ///
135 /// Also, `ManuallyDrop` prevents us from having to "touch" `v` after transferring the
136 /// ownership to `s` — the final step of interacting with `v` to dispose of it without
137 /// running its destructor is entirely avoided.
138 ///
139 /// [`Box`]: ../../std/boxed/struct.Box.html
140 /// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak
141 /// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw
142 /// [`mem::drop`]: drop
143 /// [ub]: ../../reference/behavior-considered-undefined.html
144 #[inline]
145 #[rustc_const_stable(feature = "const_forget", since = "1.46.0")]
146 #[stable(feature = "rust1", since = "1.0.0")]
147 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_forget")]
148 pub const fn forget<T>(t: T) {
149     let _ = 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 #[inline]
157 #[unstable(feature = "forget_unsized", issue = "none")]
158 pub fn forget_unsized<T: ?Sized>(t: T) {
159     intrinsics::forget(t)
160 }
161
162 /// Returns the size of a type in bytes.
163 ///
164 /// More specifically, this is the offset in bytes between successive elements
165 /// in an array with that item type including alignment padding. Thus, for any
166 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
167 ///
168 /// In general, the size of a type is not stable across compilations, but
169 /// specific types such as primitives are.
170 ///
171 /// The following table gives the size for primitives.
172 ///
173 /// Type | size_of::\<Type>()
174 /// ---- | ---------------
175 /// () | 0
176 /// bool | 1
177 /// u8 | 1
178 /// u16 | 2
179 /// u32 | 4
180 /// u64 | 8
181 /// u128 | 16
182 /// i8 | 1
183 /// i16 | 2
184 /// i32 | 4
185 /// i64 | 8
186 /// i128 | 16
187 /// f32 | 4
188 /// f64 | 8
189 /// char | 4
190 ///
191 /// Furthermore, `usize` and `isize` have the same size.
192 ///
193 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
194 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
195 ///
196 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
197 /// have the same size. Likewise for `*const T` and `*mut T`.
198 ///
199 /// # Size of `#[repr(C)]` items
200 ///
201 /// The `C` representation for items has a defined layout. With this layout,
202 /// the size of items is also stable as long as all fields have a stable size.
203 ///
204 /// ## Size of Structs
205 ///
206 /// For `structs`, the size is determined by the following algorithm.
207 ///
208 /// For each field in the struct ordered by declaration order:
209 ///
210 /// 1. Add the size of the field.
211 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
212 ///
213 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
214 /// The alignment of the struct is usually the largest alignment of all its
215 /// fields; this can be changed with the use of `repr(align(N))`.
216 ///
217 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
218 ///
219 /// ## Size of Enums
220 ///
221 /// Enums that carry no data other than the discriminant have the same size as C enums
222 /// on the platform they are compiled for.
223 ///
224 /// ## Size of Unions
225 ///
226 /// The size of a union is the size of its largest field.
227 ///
228 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// use std::mem;
234 ///
235 /// // Some primitives
236 /// assert_eq!(4, mem::size_of::<i32>());
237 /// assert_eq!(8, mem::size_of::<f64>());
238 /// assert_eq!(0, mem::size_of::<()>());
239 ///
240 /// // Some arrays
241 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
242 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
243 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
244 ///
245 ///
246 /// // Pointer size equality
247 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
248 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
249 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
250 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
251 /// ```
252 ///
253 /// Using `#[repr(C)]`.
254 ///
255 /// ```
256 /// use std::mem;
257 ///
258 /// #[repr(C)]
259 /// struct FieldStruct {
260 ///     first: u8,
261 ///     second: u16,
262 ///     third: u8
263 /// }
264 ///
265 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
266 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
267 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
268 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
269 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
270 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
271 /// // fields is 2), so add 1 to the size for padding. Size is 6.
272 /// assert_eq!(6, mem::size_of::<FieldStruct>());
273 ///
274 /// #[repr(C)]
275 /// struct TupleStruct(u8, u16, u8);
276 ///
277 /// // Tuple structs follow the same rules.
278 /// assert_eq!(6, mem::size_of::<TupleStruct>());
279 ///
280 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
281 /// // by putting `third` before `second`.
282 /// #[repr(C)]
283 /// struct FieldStructOptimized {
284 ///     first: u8,
285 ///     third: u8,
286 ///     second: u16
287 /// }
288 ///
289 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
290 ///
291 /// // Union size is the size of the largest field.
292 /// #[repr(C)]
293 /// union ExampleUnion {
294 ///     smaller: u8,
295 ///     larger: u16
296 /// }
297 ///
298 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
299 /// ```
300 ///
301 /// [alignment]: align_of
302 #[inline(always)]
303 #[must_use]
304 #[stable(feature = "rust1", since = "1.0.0")]
305 #[rustc_promotable]
306 #[rustc_const_stable(feature = "const_mem_size_of", since = "1.24.0")]
307 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of")]
308 pub const fn size_of<T>() -> usize {
309     intrinsics::size_of::<T>()
310 }
311
312 /// Returns the size of the pointed-to value in bytes.
313 ///
314 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
315 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
316 /// then `size_of_val` can be used to get the dynamically-known size.
317 ///
318 /// [trait object]: ../../book/ch17-02-trait-objects.html
319 ///
320 /// # Examples
321 ///
322 /// ```
323 /// use std::mem;
324 ///
325 /// assert_eq!(4, mem::size_of_val(&5i32));
326 ///
327 /// let x: [u8; 13] = [0; 13];
328 /// let y: &[u8] = &x;
329 /// assert_eq!(13, mem::size_of_val(y));
330 /// ```
331 #[inline]
332 #[must_use]
333 #[stable(feature = "rust1", since = "1.0.0")]
334 #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")]
335 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")]
336 pub const fn size_of_val<T: ?Sized>(val: &T) -> usize {
337     // SAFETY: `val` is a reference, so it's a valid raw pointer
338     unsafe { intrinsics::size_of_val(val) }
339 }
340
341 /// Returns the size of the pointed-to value in bytes.
342 ///
343 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
344 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
345 /// then `size_of_val_raw` can be used to get the dynamically-known size.
346 ///
347 /// # Safety
348 ///
349 /// This function is only safe to call if the following conditions hold:
350 ///
351 /// - If `T` is `Sized`, this function is always safe to call.
352 /// - If the unsized tail of `T` is:
353 ///     - a [slice], then the length of the slice tail must be an initialized
354 ///       integer, and the size of the *entire value*
355 ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
356 ///     - a [trait object], then the vtable part of the pointer must point
357 ///       to a valid vtable acquired by an unsizing coercion, and the size
358 ///       of the *entire value* (dynamic tail length + statically sized prefix)
359 ///       must fit in `isize`.
360 ///     - an (unstable) [extern type], then this function is always safe to
361 ///       call, but may panic or otherwise return the wrong value, as the
362 ///       extern type's layout is not known. This is the same behavior as
363 ///       [`size_of_val`] on a reference to a type with an extern type tail.
364 ///     - otherwise, it is conservatively not allowed to call this function.
365 ///
366 /// [trait object]: ../../book/ch17-02-trait-objects.html
367 /// [extern type]: ../../unstable-book/language-features/extern-types.html
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// #![feature(layout_for_ptr)]
373 /// use std::mem;
374 ///
375 /// assert_eq!(4, mem::size_of_val(&5i32));
376 ///
377 /// let x: [u8; 13] = [0; 13];
378 /// let y: &[u8] = &x;
379 /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) });
380 /// ```
381 #[inline]
382 #[must_use]
383 #[unstable(feature = "layout_for_ptr", issue = "69835")]
384 #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")]
385 pub const unsafe fn size_of_val_raw<T: ?Sized>(val: *const T) -> usize {
386     // SAFETY: the caller must provide a valid raw pointer
387     unsafe { intrinsics::size_of_val(val) }
388 }
389
390 /// Returns the [ABI]-required minimum alignment of a type in bytes.
391 ///
392 /// Every reference to a value of the type `T` must be a multiple of this number.
393 ///
394 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
395 ///
396 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// # #![allow(deprecated)]
402 /// use std::mem;
403 ///
404 /// assert_eq!(4, mem::min_align_of::<i32>());
405 /// ```
406 #[inline]
407 #[must_use]
408 #[stable(feature = "rust1", since = "1.0.0")]
409 #[deprecated(note = "use `align_of` instead", since = "1.2.0")]
410 pub fn min_align_of<T>() -> usize {
411     intrinsics::min_align_of::<T>()
412 }
413
414 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
415 /// bytes.
416 ///
417 /// Every reference to a value of the type `T` must be a multiple of this number.
418 ///
419 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// # #![allow(deprecated)]
425 /// use std::mem;
426 ///
427 /// assert_eq!(4, mem::min_align_of_val(&5i32));
428 /// ```
429 #[inline]
430 #[must_use]
431 #[stable(feature = "rust1", since = "1.0.0")]
432 #[deprecated(note = "use `align_of_val` instead", since = "1.2.0")]
433 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
434     // SAFETY: val is a reference, so it's a valid raw pointer
435     unsafe { intrinsics::min_align_of_val(val) }
436 }
437
438 /// Returns the [ABI]-required minimum alignment of a type in bytes.
439 ///
440 /// Every reference to a value of the type `T` must be a multiple of this number.
441 ///
442 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
443 ///
444 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
445 ///
446 /// # Examples
447 ///
448 /// ```
449 /// use std::mem;
450 ///
451 /// assert_eq!(4, mem::align_of::<i32>());
452 /// ```
453 #[inline(always)]
454 #[must_use]
455 #[stable(feature = "rust1", since = "1.0.0")]
456 #[rustc_promotable]
457 #[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
458 pub const fn align_of<T>() -> usize {
459     intrinsics::min_align_of::<T>()
460 }
461
462 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
463 /// bytes.
464 ///
465 /// Every reference to a value of the type `T` must be a multiple of this number.
466 ///
467 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
468 ///
469 /// # Examples
470 ///
471 /// ```
472 /// use std::mem;
473 ///
474 /// assert_eq!(4, mem::align_of_val(&5i32));
475 /// ```
476 #[inline]
477 #[must_use]
478 #[stable(feature = "rust1", since = "1.0.0")]
479 #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")]
480 #[allow(deprecated)]
481 pub const fn align_of_val<T: ?Sized>(val: &T) -> usize {
482     // SAFETY: val is a reference, so it's a valid raw pointer
483     unsafe { intrinsics::min_align_of_val(val) }
484 }
485
486 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
487 /// bytes.
488 ///
489 /// Every reference to a value of the type `T` must be a multiple of this number.
490 ///
491 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
492 ///
493 /// # Safety
494 ///
495 /// This function is only safe to call if the following conditions hold:
496 ///
497 /// - If `T` is `Sized`, this function is always safe to call.
498 /// - If the unsized tail of `T` is:
499 ///     - a [slice], then the length of the slice tail must be an initialized
500 ///       integer, and the size of the *entire value*
501 ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
502 ///     - a [trait object], then the vtable part of the pointer must point
503 ///       to a valid vtable acquired by an unsizing coercion, and the size
504 ///       of the *entire value* (dynamic tail length + statically sized prefix)
505 ///       must fit in `isize`.
506 ///     - an (unstable) [extern type], then this function is always safe to
507 ///       call, but may panic or otherwise return the wrong value, as the
508 ///       extern type's layout is not known. This is the same behavior as
509 ///       [`align_of_val`] on a reference to a type with an extern type tail.
510 ///     - otherwise, it is conservatively not allowed to call this function.
511 ///
512 /// [trait object]: ../../book/ch17-02-trait-objects.html
513 /// [extern type]: ../../unstable-book/language-features/extern-types.html
514 ///
515 /// # Examples
516 ///
517 /// ```
518 /// #![feature(layout_for_ptr)]
519 /// use std::mem;
520 ///
521 /// assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) });
522 /// ```
523 #[inline]
524 #[must_use]
525 #[unstable(feature = "layout_for_ptr", issue = "69835")]
526 #[rustc_const_unstable(feature = "const_align_of_val_raw", issue = "46571")]
527 pub const unsafe fn align_of_val_raw<T: ?Sized>(val: *const T) -> usize {
528     // SAFETY: the caller must provide a valid raw pointer
529     unsafe { intrinsics::min_align_of_val(val) }
530 }
531
532 /// Returns `true` if dropping values of type `T` matters.
533 ///
534 /// This is purely an optimization hint, and may be implemented conservatively:
535 /// it may return `true` for types that don't actually need to be dropped.
536 /// As such always returning `true` would be a valid implementation of
537 /// this function. However if this function actually returns `false`, then you
538 /// can be certain dropping `T` has no side effect.
539 ///
540 /// Low level implementations of things like collections, which need to manually
541 /// drop their data, should use this function to avoid unnecessarily
542 /// trying to drop all their contents when they are destroyed. This might not
543 /// make a difference in release builds (where a loop that has no side-effects
544 /// is easily detected and eliminated), but is often a big win for debug builds.
545 ///
546 /// Note that [`drop_in_place`] already performs this check, so if your workload
547 /// can be reduced to some small number of [`drop_in_place`] calls, using this is
548 /// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
549 /// will do a single needs_drop check for all the values.
550 ///
551 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
552 /// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
553 /// values one at a time and should use this API.
554 ///
555 /// [`drop_in_place`]: crate::ptr::drop_in_place
556 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
557 ///
558 /// # Examples
559 ///
560 /// Here's an example of how a collection might make use of `needs_drop`:
561 ///
562 /// ```
563 /// use std::{mem, ptr};
564 ///
565 /// pub struct MyCollection<T> {
566 /// #   data: [T; 1],
567 ///     /* ... */
568 /// }
569 /// # impl<T> MyCollection<T> {
570 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
571 /// #   fn free_buffer(&mut self) {}
572 /// # }
573 ///
574 /// impl<T> Drop for MyCollection<T> {
575 ///     fn drop(&mut self) {
576 ///         unsafe {
577 ///             // drop the data
578 ///             if mem::needs_drop::<T>() {
579 ///                 for x in self.iter_mut() {
580 ///                     ptr::drop_in_place(x);
581 ///                 }
582 ///             }
583 ///             self.free_buffer();
584 ///         }
585 ///     }
586 /// }
587 /// ```
588 #[inline]
589 #[must_use]
590 #[stable(feature = "needs_drop", since = "1.21.0")]
591 #[rustc_const_stable(feature = "const_mem_needs_drop", since = "1.36.0")]
592 #[rustc_diagnostic_item = "needs_drop"]
593 pub const fn needs_drop<T: ?Sized>() -> bool {
594     intrinsics::needs_drop::<T>()
595 }
596
597 /// Returns the value of type `T` represented by the all-zero byte-pattern.
598 ///
599 /// This means that, for example, the padding byte in `(u8, u16)` is not
600 /// necessarily zeroed.
601 ///
602 /// There is no guarantee that an all-zero byte-pattern represents a valid value
603 /// of some type `T`. For example, the all-zero byte-pattern is not a valid value
604 /// for reference types (`&T`, `&mut T`) and functions pointers. Using `zeroed`
605 /// on such types causes immediate [undefined behavior][ub] because [the Rust
606 /// compiler assumes][inv] that there always is a valid value in a variable it
607 /// considers initialized.
608 ///
609 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
610 /// It is useful for FFI sometimes, but should generally be avoided.
611 ///
612 /// [zeroed]: MaybeUninit::zeroed
613 /// [ub]: ../../reference/behavior-considered-undefined.html
614 /// [inv]: MaybeUninit#initialization-invariant
615 ///
616 /// # Examples
617 ///
618 /// Correct usage of this function: initializing an integer with zero.
619 ///
620 /// ```
621 /// use std::mem;
622 ///
623 /// let x: i32 = unsafe { mem::zeroed() };
624 /// assert_eq!(0, x);
625 /// ```
626 ///
627 /// *Incorrect* usage of this function: initializing a reference with zero.
628 ///
629 /// ```rust,no_run
630 /// # #![allow(invalid_value)]
631 /// use std::mem;
632 ///
633 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
634 /// let _y: fn() = unsafe { mem::zeroed() }; // And again!
635 /// ```
636 #[inline(always)]
637 #[must_use]
638 #[stable(feature = "rust1", since = "1.0.0")]
639 #[allow(deprecated_in_future)]
640 #[allow(deprecated)]
641 #[rustc_diagnostic_item = "mem_zeroed"]
642 #[track_caller]
643 pub unsafe fn zeroed<T>() -> T {
644     // SAFETY: the caller must guarantee that an all-zero value is valid for `T`.
645     unsafe {
646         intrinsics::assert_zero_valid::<T>();
647         MaybeUninit::zeroed().assume_init()
648     }
649 }
650
651 /// Bypasses Rust's normal memory-initialization checks by pretending to
652 /// produce a value of type `T`, while doing nothing at all.
653 ///
654 /// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
655 /// It also might be slower than using `MaybeUninit<T>` due to mitigations that were put in place to
656 /// limit the potential harm caused by incorrect use of this function in legacy code.
657 ///
658 /// The reason for deprecation is that the function basically cannot be used
659 /// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
660 /// As the [`assume_init` documentation][assume_init] explains,
661 /// [the Rust compiler assumes][inv] that values are properly initialized.
662 ///
663 /// Truly uninitialized memory like what gets returned here
664 /// is special in that the compiler knows that it does not have a fixed value.
665 /// This makes it undefined behavior to have uninitialized data in a variable even
666 /// if that variable has an integer type.
667 ///
668 /// Therefore, it is immediate undefined behavior to call this function on nearly all types,
669 /// including integer types and arrays of integer types, and even if the result is unused.
670 ///
671 /// [uninit]: MaybeUninit::uninit
672 /// [assume_init]: MaybeUninit::assume_init
673 /// [inv]: MaybeUninit#initialization-invariant
674 #[inline(always)]
675 #[must_use]
676 #[deprecated(since = "1.39.0", note = "use `mem::MaybeUninit` instead")]
677 #[stable(feature = "rust1", since = "1.0.0")]
678 #[allow(deprecated_in_future)]
679 #[allow(deprecated)]
680 #[rustc_diagnostic_item = "mem_uninitialized"]
681 #[track_caller]
682 pub unsafe fn uninitialized<T>() -> T {
683     // SAFETY: the caller must guarantee that an uninitialized value is valid for `T`.
684     unsafe {
685         intrinsics::assert_mem_uninitialized_valid::<T>();
686         let mut val = MaybeUninit::<T>::uninit();
687
688         // Fill memory with 0x01, as an imperfect mitigation for old code that uses this function on
689         // bool, nonnull, and noundef types. But don't do this if we actively want to detect UB.
690         if !cfg!(any(miri, sanitize = "memory")) {
691             val.as_mut_ptr().write_bytes(0x01, 1);
692         }
693
694         val.assume_init()
695     }
696 }
697
698 /// Swaps the values at two mutable locations, without deinitializing either one.
699 ///
700 /// * If you want to swap with a default or dummy value, see [`take`].
701 /// * If you want to swap with a passed value, returning the old value, see [`replace`].
702 ///
703 /// # Examples
704 ///
705 /// ```
706 /// use std::mem;
707 ///
708 /// let mut x = 5;
709 /// let mut y = 42;
710 ///
711 /// mem::swap(&mut x, &mut y);
712 ///
713 /// assert_eq!(42, x);
714 /// assert_eq!(5, y);
715 /// ```
716 #[inline]
717 #[stable(feature = "rust1", since = "1.0.0")]
718 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
719 pub const fn swap<T>(x: &mut T, y: &mut T) {
720     // NOTE(eddyb) SPIR-V's Logical addressing model doesn't allow for arbitrary
721     // reinterpretation of values as (chunkable) byte arrays, and the loop in the
722     // block optimization in `swap_slice` is hard to rewrite back
723     // into the (unoptimized) direct swapping implementation, so we disable it.
724     // FIXME(eddyb) the block optimization also prevents MIR optimizations from
725     // understanding `mem::replace`, `Option::take`, etc. - a better overall
726     // solution might be to make `ptr::swap_nonoverlapping` into an intrinsic, which
727     // a backend can choose to implement using the block optimization, or not.
728     #[cfg(not(any(target_arch = "spirv")))]
729     {
730         // For types that are larger multiples of their alignment, the simple way
731         // tends to copy the whole thing to stack rather than doing it one part
732         // at a time, so instead treat them as one-element slices and piggy-back
733         // the slice optimizations that will split up the swaps.
734         if size_of::<T>() / align_of::<T>() > 4 {
735             // SAFETY: exclusive references always point to one non-overlapping
736             // element and are non-null and properly aligned.
737             return unsafe { ptr::swap_nonoverlapping(x, y, 1) };
738         }
739     }
740
741     // If a scalar consists of just a small number of alignment units, let
742     // the codegen just swap those pieces directly, as it's likely just a
743     // few instructions and anything else is probably overcomplicated.
744     //
745     // Most importantly, this covers primitives and simd types that tend to
746     // have size=align where doing anything else can be a pessimization.
747     // (This will also be used for ZSTs, though any solution works for them.)
748     swap_simple(x, y);
749 }
750
751 /// Same as [`swap`] semantically, but always uses the simple implementation.
752 ///
753 /// Used elsewhere in `mem` and `ptr` at the bottom layer of calls.
754 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
755 #[inline]
756 pub(crate) const fn swap_simple<T>(x: &mut T, y: &mut T) {
757     // We arrange for this to typically be called with small types,
758     // so this reads-and-writes approach is actually better than using
759     // copy_nonoverlapping as it easily puts things in LLVM registers
760     // directly and doesn't end up inlining allocas.
761     // And LLVM actually optimizes it to 3×memcpy if called with
762     // a type larger than it's willing to keep in a register.
763     // Having typed reads and writes in MIR here is also good as
764     // it lets MIRI and CTFE understand them better, including things
765     // like enforcing type validity for them.
766     // Importantly, read+copy_nonoverlapping+write introduces confusing
767     // asymmetry to the behaviour where one value went through read+write
768     // whereas the other was copied over by the intrinsic (see #94371).
769
770     // SAFETY: exclusive references are always valid to read/write,
771     // including being aligned, and nothing here panics so it's drop-safe.
772     unsafe {
773         let a = ptr::read(x);
774         let b = ptr::read(y);
775         ptr::write(x, b);
776         ptr::write(y, a);
777     }
778 }
779
780 /// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
781 ///
782 /// * If you want to replace the values of two variables, see [`swap`].
783 /// * If you want to replace with a passed value instead of the default value, see [`replace`].
784 ///
785 /// # Examples
786 ///
787 /// A simple example:
788 ///
789 /// ```
790 /// use std::mem;
791 ///
792 /// let mut v: Vec<i32> = vec![1, 2];
793 ///
794 /// let old_v = mem::take(&mut v);
795 /// assert_eq!(vec![1, 2], old_v);
796 /// assert!(v.is_empty());
797 /// ```
798 ///
799 /// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
800 /// Without `take` you can run into issues like these:
801 ///
802 /// ```compile_fail,E0507
803 /// struct Buffer<T> { buf: Vec<T> }
804 ///
805 /// impl<T> Buffer<T> {
806 ///     fn get_and_reset(&mut self) -> Vec<T> {
807 ///         // error: cannot move out of dereference of `&mut`-pointer
808 ///         let buf = self.buf;
809 ///         self.buf = Vec::new();
810 ///         buf
811 ///     }
812 /// }
813 /// ```
814 ///
815 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
816 /// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
817 /// `self`, allowing it to be returned:
818 ///
819 /// ```
820 /// use std::mem;
821 ///
822 /// # struct Buffer<T> { buf: Vec<T> }
823 /// impl<T> Buffer<T> {
824 ///     fn get_and_reset(&mut self) -> Vec<T> {
825 ///         mem::take(&mut self.buf)
826 ///     }
827 /// }
828 ///
829 /// let mut buffer = Buffer { buf: vec![0, 1] };
830 /// assert_eq!(buffer.buf.len(), 2);
831 ///
832 /// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
833 /// assert_eq!(buffer.buf.len(), 0);
834 /// ```
835 #[inline]
836 #[stable(feature = "mem_take", since = "1.40.0")]
837 pub fn take<T: Default>(dest: &mut T) -> T {
838     replace(dest, T::default())
839 }
840
841 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
842 ///
843 /// Neither value is dropped.
844 ///
845 /// * If you want to replace the values of two variables, see [`swap`].
846 /// * If you want to replace with a default value, see [`take`].
847 ///
848 /// # Examples
849 ///
850 /// A simple example:
851 ///
852 /// ```
853 /// use std::mem;
854 ///
855 /// let mut v: Vec<i32> = vec![1, 2];
856 ///
857 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
858 /// assert_eq!(vec![1, 2], old_v);
859 /// assert_eq!(vec![3, 4, 5], v);
860 /// ```
861 ///
862 /// `replace` allows consumption of a struct field by replacing it with another value.
863 /// Without `replace` you can run into issues like these:
864 ///
865 /// ```compile_fail,E0507
866 /// struct Buffer<T> { buf: Vec<T> }
867 ///
868 /// impl<T> Buffer<T> {
869 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
870 ///         // error: cannot move out of dereference of `&mut`-pointer
871 ///         let t = self.buf[i];
872 ///         self.buf[i] = v;
873 ///         t
874 ///     }
875 /// }
876 /// ```
877 ///
878 /// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
879 /// avoid the move. But `replace` can be used to disassociate the original value at that index from
880 /// `self`, allowing it to be returned:
881 ///
882 /// ```
883 /// # #![allow(dead_code)]
884 /// use std::mem;
885 ///
886 /// # struct Buffer<T> { buf: Vec<T> }
887 /// impl<T> Buffer<T> {
888 ///     fn replace_index(&mut self, i: usize, v: T) -> T {
889 ///         mem::replace(&mut self.buf[i], v)
890 ///     }
891 /// }
892 ///
893 /// let mut buffer = Buffer { buf: vec![0, 1] };
894 /// assert_eq!(buffer.buf[0], 0);
895 ///
896 /// assert_eq!(buffer.replace_index(0, 2), 0);
897 /// assert_eq!(buffer.buf[0], 2);
898 /// ```
899 #[inline]
900 #[stable(feature = "rust1", since = "1.0.0")]
901 #[must_use = "if you don't need the old value, you can just assign the new value directly"]
902 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
903 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")]
904 pub const fn replace<T>(dest: &mut T, src: T) -> T {
905     // SAFETY: We read from `dest` but directly write `src` into it afterwards,
906     // such that the old value is not duplicated. Nothing is dropped and
907     // nothing here can panic.
908     unsafe {
909         let result = ptr::read(dest);
910         ptr::write(dest, src);
911         result
912     }
913 }
914
915 /// Disposes of a value.
916 ///
917 /// This does so by calling the argument's implementation of [`Drop`][drop].
918 ///
919 /// This effectively does nothing for types which implement `Copy`, e.g.
920 /// integers. Such values are copied and _then_ moved into the function, so the
921 /// value persists after this function call.
922 ///
923 /// This function is not magic; it is literally defined as
924 ///
925 /// ```
926 /// pub fn drop<T>(_x: T) { }
927 /// ```
928 ///
929 /// Because `_x` is moved into the function, it is automatically dropped before
930 /// the function returns.
931 ///
932 /// [drop]: Drop
933 ///
934 /// # Examples
935 ///
936 /// Basic usage:
937 ///
938 /// ```
939 /// let v = vec![1, 2, 3];
940 ///
941 /// drop(v); // explicitly drop the vector
942 /// ```
943 ///
944 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
945 /// release a [`RefCell`] borrow:
946 ///
947 /// ```
948 /// use std::cell::RefCell;
949 ///
950 /// let x = RefCell::new(1);
951 ///
952 /// let mut mutable_borrow = x.borrow_mut();
953 /// *mutable_borrow = 1;
954 ///
955 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
956 ///
957 /// let borrow = x.borrow();
958 /// println!("{}", *borrow);
959 /// ```
960 ///
961 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
962 ///
963 /// ```
964 /// #[derive(Copy, Clone)]
965 /// struct Foo(u8);
966 ///
967 /// let x = 1;
968 /// let y = Foo(2);
969 /// drop(x); // a copy of `x` is moved and dropped
970 /// drop(y); // a copy of `y` is moved and dropped
971 ///
972 /// println!("x: {}, y: {}", x, y.0); // still available
973 /// ```
974 ///
975 /// [`RefCell`]: crate::cell::RefCell
976 #[inline]
977 #[stable(feature = "rust1", since = "1.0.0")]
978 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")]
979 pub fn drop<T>(_x: T) {}
980
981 /// Bitwise-copies a value.
982 ///
983 /// This function is not magic; it is literally defined as
984 /// ```
985 /// pub fn copy<T: Copy>(x: &T) -> T { *x }
986 /// ```
987 ///
988 /// It is useful when you want to pass a function pointer to a combinator, rather than defining a new closure.
989 ///
990 /// Example:
991 /// ```
992 /// #![feature(mem_copy_fn)]
993 /// use core::mem::copy;
994 /// let result_from_ffi_function: Result<(), &i32> = Err(&1);
995 /// let result_copied: Result<(), i32> = result_from_ffi_function.map_err(copy);
996 /// ```
997 #[inline]
998 #[unstable(feature = "mem_copy_fn", issue = "98262")]
999 pub const fn copy<T: Copy>(x: &T) -> T {
1000     *x
1001 }
1002
1003 /// Interprets `src` as having type `&Dst`, and then reads `src` without moving
1004 /// the contained value.
1005 ///
1006 /// This function will unsafely assume the pointer `src` is valid for [`size_of::<Dst>`][size_of]
1007 /// bytes by transmuting `&Src` to `&Dst` and then reading the `&Dst` (except that this is done
1008 /// in a way that is correct even when `&Dst` has stricter alignment requirements than `&Src`).
1009 /// It will also unsafely create a copy of the contained value instead of moving out of `src`.
1010 ///
1011 /// It is not a compile-time error if `Src` and `Dst` have different sizes, but it
1012 /// is highly encouraged to only invoke this function where `Src` and `Dst` have the
1013 /// same size. This function triggers [undefined behavior][ub] if `Dst` is larger than
1014 /// `Src`.
1015 ///
1016 /// [ub]: ../../reference/behavior-considered-undefined.html
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// use std::mem;
1022 ///
1023 /// #[repr(packed)]
1024 /// struct Foo {
1025 ///     bar: u8,
1026 /// }
1027 ///
1028 /// let foo_array = [10u8];
1029 ///
1030 /// unsafe {
1031 ///     // Copy the data from 'foo_array' and treat it as a 'Foo'
1032 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
1033 ///     assert_eq!(foo_struct.bar, 10);
1034 ///
1035 ///     // Modify the copied data
1036 ///     foo_struct.bar = 20;
1037 ///     assert_eq!(foo_struct.bar, 20);
1038 /// }
1039 ///
1040 /// // The contents of 'foo_array' should not have changed
1041 /// assert_eq!(foo_array, [10]);
1042 /// ```
1043 #[inline]
1044 #[must_use]
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 #[rustc_const_unstable(feature = "const_transmute_copy", issue = "83165")]
1047 pub const unsafe fn transmute_copy<Src, Dst>(src: &Src) -> Dst {
1048     assert!(
1049         size_of::<Src>() >= size_of::<Dst>(),
1050         "cannot transmute_copy if Dst is larger than Src"
1051     );
1052
1053     // If Dst has a higher alignment requirement, src might not be suitably aligned.
1054     if align_of::<Dst>() > align_of::<Src>() {
1055         // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
1056         // The caller must guarantee that the actual transmutation is safe.
1057         unsafe { ptr::read_unaligned(src as *const Src as *const Dst) }
1058     } else {
1059         // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
1060         // We just checked that `src as *const Dst` was properly aligned.
1061         // The caller must guarantee that the actual transmutation is safe.
1062         unsafe { ptr::read(src as *const Src as *const Dst) }
1063     }
1064 }
1065
1066 /// Opaque type representing the discriminant of an enum.
1067 ///
1068 /// See the [`discriminant`] function in this module for more information.
1069 #[stable(feature = "discriminant_value", since = "1.21.0")]
1070 pub struct Discriminant<T>(<T as DiscriminantKind>::Discriminant);
1071
1072 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
1073
1074 #[stable(feature = "discriminant_value", since = "1.21.0")]
1075 impl<T> Copy for Discriminant<T> {}
1076
1077 #[stable(feature = "discriminant_value", since = "1.21.0")]
1078 impl<T> clone::Clone for Discriminant<T> {
1079     fn clone(&self) -> Self {
1080         *self
1081     }
1082 }
1083
1084 #[stable(feature = "discriminant_value", since = "1.21.0")]
1085 impl<T> cmp::PartialEq for Discriminant<T> {
1086     fn eq(&self, rhs: &Self) -> bool {
1087         self.0 == rhs.0
1088     }
1089 }
1090
1091 #[stable(feature = "discriminant_value", since = "1.21.0")]
1092 impl<T> cmp::Eq for Discriminant<T> {}
1093
1094 #[stable(feature = "discriminant_value", since = "1.21.0")]
1095 impl<T> hash::Hash for Discriminant<T> {
1096     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1097         self.0.hash(state);
1098     }
1099 }
1100
1101 #[stable(feature = "discriminant_value", since = "1.21.0")]
1102 impl<T> fmt::Debug for Discriminant<T> {
1103     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1104         fmt.debug_tuple("Discriminant").field(&self.0).finish()
1105     }
1106 }
1107
1108 /// Returns a value uniquely identifying the enum variant in `v`.
1109 ///
1110 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1111 /// return value is unspecified.
1112 ///
1113 /// # Stability
1114 ///
1115 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
1116 /// of some variant will not change between compilations with the same compiler. See the [Reference]
1117 /// for more information.
1118 ///
1119 /// [Reference]: ../../reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
1120 ///
1121 /// # Examples
1122 ///
1123 /// This can be used to compare enums that carry data, while disregarding
1124 /// the actual data:
1125 ///
1126 /// ```
1127 /// use std::mem;
1128 ///
1129 /// enum Foo { A(&'static str), B(i32), C(i32) }
1130 ///
1131 /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
1132 /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
1133 /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
1134 /// ```
1135 ///
1136 /// ## Accessing the numeric value of the discriminant
1137 ///
1138 /// Note that it is *undefined behavior* to [`transmute`] from [`Discriminant`] to a primitive!
1139 ///
1140 /// If an enum has only unit variants, then the numeric value of the discriminant can be accessed
1141 /// with an [`as`] cast:
1142 ///
1143 /// ```
1144 /// enum Enum {
1145 ///     Foo,
1146 ///     Bar,
1147 ///     Baz,
1148 /// }
1149 ///
1150 /// assert_eq!(0, Enum::Foo as isize);
1151 /// assert_eq!(1, Enum::Bar as isize);
1152 /// assert_eq!(2, Enum::Baz as isize);
1153 /// ```
1154 ///
1155 /// If an enum has opted-in to having a [primitive representation] for its discriminant,
1156 /// then it's possible to use pointers to read the memory location storing the discriminant.
1157 /// That **cannot** be done for enums using the [default representation], however, as it's
1158 /// undefined what layout the discriminant has and where it's stored — it might not even be
1159 /// stored at all!
1160 ///
1161 /// [`as`]: ../../std/keyword.as.html
1162 /// [primitive representation]: ../../reference/type-layout.html#primitive-representations
1163 /// [default representation]: ../../reference/type-layout.html#the-default-representation
1164 /// ```
1165 /// #[repr(u8)]
1166 /// enum Enum {
1167 ///     Unit,
1168 ///     Tuple(bool),
1169 ///     Struct { a: bool },
1170 /// }
1171 ///
1172 /// impl Enum {
1173 ///     fn discriminant(&self) -> u8 {
1174 ///         // SAFETY: Because `Self` is marked `repr(u8)`, its layout is a `repr(C)` `union`
1175 ///         // between `repr(C)` structs, each of which has the `u8` discriminant as its first
1176 ///         // field, so we can read the discriminant without offsetting the pointer.
1177 ///         unsafe { *<*const _>::from(self).cast::<u8>() }
1178 ///     }
1179 /// }
1180 ///
1181 /// let unit_like = Enum::Unit;
1182 /// let tuple_like = Enum::Tuple(true);
1183 /// let struct_like = Enum::Struct { a: false };
1184 /// assert_eq!(0, unit_like.discriminant());
1185 /// assert_eq!(1, tuple_like.discriminant());
1186 /// assert_eq!(2, struct_like.discriminant());
1187 ///
1188 /// // ⚠️ This is undefined behavior. Don't do this. ⚠️
1189 /// // assert_eq!(0, unsafe { std::mem::transmute::<_, u8>(std::mem::discriminant(&unit_like)) });
1190 /// ```
1191 #[stable(feature = "discriminant_value", since = "1.21.0")]
1192 #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")]
1193 #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")]
1194 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1195 pub const fn discriminant<T>(v: &T) -> Discriminant<T> {
1196     Discriminant(intrinsics::discriminant_value(v))
1197 }
1198
1199 /// Returns the number of variants in the enum type `T`.
1200 ///
1201 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
1202 /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX`
1203 /// the return value is unspecified. Uninhabited variants will be counted.
1204 ///
1205 /// Note that an enum may be expanded with additional variants in the future
1206 /// as a non-breaking change, for example if it is marked `#[non_exhaustive]`,
1207 /// which will change the result of this function.
1208 ///
1209 /// # Examples
1210 ///
1211 /// ```
1212 /// # #![feature(never_type)]
1213 /// # #![feature(variant_count)]
1214 ///
1215 /// use std::mem;
1216 ///
1217 /// enum Void {}
1218 /// enum Foo { A(&'static str), B(i32), C(i32) }
1219 ///
1220 /// assert_eq!(mem::variant_count::<Void>(), 0);
1221 /// assert_eq!(mem::variant_count::<Foo>(), 3);
1222 ///
1223 /// assert_eq!(mem::variant_count::<Option<!>>(), 2);
1224 /// assert_eq!(mem::variant_count::<Result<!, !>>(), 2);
1225 /// ```
1226 #[inline(always)]
1227 #[must_use]
1228 #[unstable(feature = "variant_count", issue = "73662")]
1229 #[rustc_const_unstable(feature = "variant_count", issue = "73662")]
1230 #[rustc_diagnostic_item = "mem_variant_count"]
1231 pub const fn variant_count<T>() -> usize {
1232     intrinsics::variant_count::<T>()
1233 }
1234
1235 /// Provides associated constants for various useful properties of types,
1236 /// to give them a canonical form in our code and make them easier to read.
1237 ///
1238 /// This is here only to simplify all the ZST checks we need in the library.
1239 /// It's not on a stabilization track right now.
1240 #[doc(hidden)]
1241 #[unstable(feature = "sized_type_properties", issue = "none")]
1242 pub trait SizedTypeProperties: Sized {
1243     /// `true` if this type requires no storage.
1244     /// `false` if its [size](size_of) is greater than zero.
1245     ///
1246     /// # Examples
1247     ///
1248     /// ```
1249     /// #![feature(sized_type_properties)]
1250     /// use core::mem::SizedTypeProperties;
1251     ///
1252     /// fn do_something_with<T>() {
1253     ///     if T::IS_ZST {
1254     ///         // ... special approach ...
1255     ///     } else {
1256     ///         // ... the normal thing ...
1257     ///     }
1258     /// }
1259     ///
1260     /// struct MyUnit;
1261     /// assert!(MyUnit::IS_ZST);
1262     ///
1263     /// // For negative checks, consider using UFCS to emphasize the negation
1264     /// assert!(!<i32>::IS_ZST);
1265     /// // As it can sometimes hide in the type otherwise
1266     /// assert!(!String::IS_ZST);
1267     /// ```
1268     #[doc(hidden)]
1269     #[unstable(feature = "sized_type_properties", issue = "none")]
1270     const IS_ZST: bool = size_of::<Self>() == 0;
1271 }
1272 #[doc(hidden)]
1273 #[unstable(feature = "sized_type_properties", issue = "none")]
1274 impl<T> SizedTypeProperties for T {}