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