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::alloc::Layout;
9
#[cfg(feature = "ferrocene_certified")]
10
use crate::intrinsics;
11
#[cfg(not(feature = "ferrocene_certified"))]
12
use crate::marker::DiscriminantKind;
13
#[cfg(not(feature = "ferrocene_certified"))]
14
use crate::{clone, cmp, fmt, hash, intrinsics, ptr};
15

            
16
#[cfg(not(feature = "ferrocene_certified"))]
17
mod manually_drop;
18
#[stable(feature = "manually_drop", since = "1.20.0")]
19
#[cfg(not(feature = "ferrocene_certified"))]
20
pub use manually_drop::ManuallyDrop;
21

            
22
#[cfg(not(feature = "ferrocene_certified"))]
23
mod maybe_uninit;
24
#[stable(feature = "maybe_uninit", since = "1.36.0")]
25
#[cfg(not(feature = "ferrocene_certified"))]
26
pub use maybe_uninit::MaybeUninit;
27

            
28
#[cfg(not(feature = "ferrocene_certified"))]
29
mod transmutability;
30
#[unstable(feature = "transmutability", issue = "99571")]
31
#[cfg(not(feature = "ferrocene_certified"))]
32
pub use transmutability::{Assume, TransmuteFrom};
33

            
34
#[cfg(not(feature = "ferrocene_certified"))]
35
mod drop_guard;
36
#[unstable(feature = "drop_guard", issue = "144426")]
37
#[cfg(not(feature = "ferrocene_certified"))]
38
pub use drop_guard::DropGuard;
39

            
40
// This one has to be a re-export (rather than wrapping the underlying intrinsic) so that we can do
41
// the special magic "types have equal size" check at the call site.
42
#[stable(feature = "rust1", since = "1.0.0")]
43
#[doc(inline)]
44
pub use crate::intrinsics::transmute;
45

            
46
/// Takes ownership and "forgets" about the value **without running its destructor**.
47
///
48
/// Any resources the value manages, such as heap memory or a file handle, will linger
49
/// forever in an unreachable state. However, it does not guarantee that pointers
50
/// to this memory will remain valid.
51
///
52
/// * If you want to leak memory, see [`Box::leak`].
53
/// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`].
54
/// * If you want to dispose of a value properly, running its destructor, see
55
///   [`mem::drop`].
56
///
57
/// # Safety
58
///
59
/// `forget` is not marked as `unsafe`, because Rust's safety guarantees
60
/// do not include a guarantee that destructors will always run. For example,
61
/// a program can create a reference cycle using [`Rc`][rc], or call
62
/// [`process::exit`][exit] to exit without running destructors. Thus, allowing
63
/// `mem::forget` from safe code does not fundamentally change Rust's safety
64
/// guarantees.
65
///
66
/// That said, leaking resources such as memory or I/O objects is usually undesirable.
67
/// The need comes up in some specialized use cases for FFI or unsafe code, but even
68
/// then, [`ManuallyDrop`] is typically preferred.
69
///
70
/// Because forgetting a value is allowed, any `unsafe` code you write must
71
/// allow for this possibility. You cannot return a value and expect that the
72
/// caller will necessarily run the value's destructor.
73
///
74
/// [rc]: ../../std/rc/struct.Rc.html
75
/// [exit]: ../../std/process/fn.exit.html
76
///
77
/// # Examples
78
///
79
/// The canonical safe use of `mem::forget` is to circumvent a value's destructor
80
/// implemented by the `Drop` trait. For example, this will leak a `File`, i.e. reclaim
81
/// the space taken by the variable but never close the underlying system resource:
82
///
83
/// ```no_run
84
/// use std::mem;
85
/// use std::fs::File;
86
///
87
/// let file = File::open("foo.txt").unwrap();
88
/// mem::forget(file);
89
/// ```
90
///
91
/// This is useful when the ownership of the underlying resource was previously
92
/// transferred to code outside of Rust, for example by transmitting the raw
93
/// file descriptor to C code.
94
///
95
/// # Relationship with `ManuallyDrop`
96
///
97
/// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone.
98
/// [`ManuallyDrop`] should be used instead. Consider, for example, this code:
99
///
100
/// ```
101
/// use std::mem;
102
///
103
/// let mut v = vec![65, 122];
104
/// // Build a `String` using the contents of `v`
105
/// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) };
106
/// // leak `v` because its memory is now managed by `s`
107
/// mem::forget(v);  // ERROR - v is invalid and must not be passed to a function
108
/// assert_eq!(s, "Az");
109
/// // `s` is implicitly dropped and its memory deallocated.
110
/// ```
111
///
112
/// There are two issues with the above example:
113
///
114
/// * If more code were added between the construction of `String` and the invocation of
115
///   `mem::forget()`, a panic within it would cause a double free because the same memory
116
///   is handled by both `v` and `s`.
117
/// * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`,
118
///   the `v` value is invalid. Even when a value is just moved to `mem::forget` (which won't
119
///   inspect it), some types have strict requirements on their values that
120
///   make them invalid when dangling or no longer owned. Using invalid values in any
121
///   way, including passing them to or returning them from functions, constitutes
122
///   undefined behavior and may break the assumptions made by the compiler.
123
///
124
/// Switching to `ManuallyDrop` avoids both issues:
125
///
126
/// ```
127
/// use std::mem::ManuallyDrop;
128
///
129
/// let v = vec![65, 122];
130
/// // Before we disassemble `v` into its raw parts, make sure it
131
/// // does not get dropped!
132
/// let mut v = ManuallyDrop::new(v);
133
/// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak.
134
/// let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity());
135
/// // Finally, build a `String`.
136
/// let s = unsafe { String::from_raw_parts(ptr, len, cap) };
137
/// assert_eq!(s, "Az");
138
/// // `s` is implicitly dropped and its memory deallocated.
139
/// ```
140
///
141
/// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor
142
/// before doing anything else. `mem::forget()` doesn't allow this because it consumes its
143
/// argument, forcing us to call it only after extracting anything we need from `v`. Even
144
/// if a panic were introduced between construction of `ManuallyDrop` and building the
145
/// string (which cannot happen in the code as shown), it would result in a leak and not a
146
/// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of
147
/// erring on the side of (double-)dropping.
148
///
149
/// Also, `ManuallyDrop` prevents us from having to "touch" `v` after transferring the
150
/// ownership to `s` — the final step of interacting with `v` to dispose of it without
151
/// running its destructor is entirely avoided.
152
///
153
/// [`Box`]: ../../std/boxed/struct.Box.html
154
/// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak
155
/// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw
156
/// [`mem::drop`]: drop
157
/// [ub]: ../../reference/behavior-considered-undefined.html
158
#[inline]
159
#[rustc_const_stable(feature = "const_forget", since = "1.46.0")]
160
#[stable(feature = "rust1", since = "1.0.0")]
161
#[rustc_diagnostic_item = "mem_forget"]
162
#[cfg(not(feature = "ferrocene_certified"))]
163
pub const fn forget<T>(t: T) {
164
    let _ = ManuallyDrop::new(t);
165
}
166

            
167
/// Like [`forget`], but also accepts unsized values.
168
///
169
/// While Rust does not permit unsized locals since its removal in [#111942] it is
170
/// still possible to call functions with unsized values from a function argument
171
/// or place expression.
172
///
173
/// ```rust
174
/// #![feature(unsized_fn_params, forget_unsized)]
175
/// #![allow(internal_features)]
176
///
177
/// use std::mem::forget_unsized;
178
///
179
/// pub fn in_place() {
180
///     forget_unsized(*Box::<str>::from("str"));
181
/// }
182
///
183
/// pub fn param(x: str) {
184
///     forget_unsized(x);
185
/// }
186
/// ```
187
///
188
/// This works because the compiler will alter these functions to pass the parameter
189
/// by reference instead. This trick is necessary to support `Box<dyn FnOnce()>: FnOnce()`.
190
/// See [#68304] and [#71170] for more information.
191
///
192
/// [#111942]: https://github.com/rust-lang/rust/issues/111942
193
/// [#68304]: https://github.com/rust-lang/rust/issues/68304
194
/// [#71170]: https://github.com/rust-lang/rust/pull/71170
195
#[inline]
196
#[unstable(feature = "forget_unsized", issue = "none")]
197
#[cfg(not(feature = "ferrocene_certified"))]
198
pub fn forget_unsized<T: ?Sized>(t: T) {
199
    intrinsics::forget(t)
200
}
201

            
202
/// Returns the size of a type in bytes.
203
///
204
/// More specifically, this is the offset in bytes between successive elements
205
/// in an array with that item type including alignment padding. Thus, for any
206
/// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
207
///
208
/// In general, the size of a type is not stable across compilations, but
209
/// specific types such as primitives are.
210
///
211
/// The following table gives the size for primitives.
212
///
213
/// Type | `size_of::<Type>()`
214
/// ---- | ---------------
215
/// () | 0
216
/// bool | 1
217
/// u8 | 1
218
/// u16 | 2
219
/// u32 | 4
220
/// u64 | 8
221
/// u128 | 16
222
/// i8 | 1
223
/// i16 | 2
224
/// i32 | 4
225
/// i64 | 8
226
/// i128 | 16
227
/// f32 | 4
228
/// f64 | 8
229
/// char | 4
230
///
231
/// Furthermore, `usize` and `isize` have the same size.
232
///
233
/// The types [`*const T`], `&T`, [`Box<T>`], [`Option<&T>`], and `Option<Box<T>>` all have
234
/// the same size. If `T` is `Sized`, all of those types have the same size as `usize`.
235
///
236
/// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
237
/// have the same size. Likewise for `*const T` and `*mut T`.
238
///
239
/// # Size of `#[repr(C)]` items
240
///
241
/// The `C` representation for items has a defined layout. With this layout,
242
/// the size of items is also stable as long as all fields have a stable size.
243
///
244
/// ## Size of Structs
245
///
246
/// For `struct`s, the size is determined by the following algorithm.
247
///
248
/// For each field in the struct ordered by declaration order:
249
///
250
/// 1. Add the size of the field.
251
/// 2. Round up the current size to the nearest multiple of the next field's [alignment].
252
///
253
/// Finally, round the size of the struct to the nearest multiple of its [alignment].
254
/// The alignment of the struct is usually the largest alignment of all its
255
/// fields; this can be changed with the use of `repr(align(N))`.
256
///
257
/// Unlike `C`, zero sized structs are not rounded up to one byte in size.
258
///
259
/// ## Size of Enums
260
///
261
/// Enums that carry no data other than the discriminant have the same size as C enums
262
/// on the platform they are compiled for.
263
///
264
/// ## Size of Unions
265
///
266
/// The size of a union is the size of its largest field.
267
///
268
/// Unlike `C`, zero sized unions are not rounded up to one byte in size.
269
///
270
/// # Examples
271
///
272
/// ```
273
/// // Some primitives
274
/// assert_eq!(4, size_of::<i32>());
275
/// assert_eq!(8, size_of::<f64>());
276
/// assert_eq!(0, size_of::<()>());
277
///
278
/// // Some arrays
279
/// assert_eq!(8, size_of::<[i32; 2]>());
280
/// assert_eq!(12, size_of::<[i32; 3]>());
281
/// assert_eq!(0, size_of::<[i32; 0]>());
282
///
283
///
284
/// // Pointer size equality
285
/// assert_eq!(size_of::<&i32>(), size_of::<*const i32>());
286
/// assert_eq!(size_of::<&i32>(), size_of::<Box<i32>>());
287
/// assert_eq!(size_of::<&i32>(), size_of::<Option<&i32>>());
288
/// assert_eq!(size_of::<Box<i32>>(), size_of::<Option<Box<i32>>>());
289
/// ```
290
///
291
/// Using `#[repr(C)]`.
292
///
293
/// ```
294
/// #[repr(C)]
295
/// struct FieldStruct {
296
///     first: u8,
297
///     second: u16,
298
///     third: u8
299
/// }
300
///
301
/// // The size of the first field is 1, so add 1 to the size. Size is 1.
302
/// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
303
/// // The size of the second field is 2, so add 2 to the size. Size is 4.
304
/// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
305
/// // The size of the third field is 1, so add 1 to the size. Size is 5.
306
/// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
307
/// // fields is 2), so add 1 to the size for padding. Size is 6.
308
/// assert_eq!(6, size_of::<FieldStruct>());
309
///
310
/// #[repr(C)]
311
/// struct TupleStruct(u8, u16, u8);
312
///
313
/// // Tuple structs follow the same rules.
314
/// assert_eq!(6, size_of::<TupleStruct>());
315
///
316
/// // Note that reordering the fields can lower the size. We can remove both padding bytes
317
/// // by putting `third` before `second`.
318
/// #[repr(C)]
319
/// struct FieldStructOptimized {
320
///     first: u8,
321
///     third: u8,
322
///     second: u16
323
/// }
324
///
325
/// assert_eq!(4, size_of::<FieldStructOptimized>());
326
///
327
/// // Union size is the size of the largest field.
328
/// #[repr(C)]
329
/// union ExampleUnion {
330
///     smaller: u8,
331
///     larger: u16
332
/// }
333
///
334
/// assert_eq!(2, size_of::<ExampleUnion>());
335
/// ```
336
///
337
/// [alignment]: align_of
338
/// [`*const T`]: primitive@pointer
339
/// [`Box<T>`]: ../../std/boxed/struct.Box.html
340
/// [`Option<&T>`]: crate::option::Option
341
///
342
#[inline(always)]
343
#[must_use]
344
#[stable(feature = "rust1", since = "1.0.0")]
345
#[rustc_promotable]
346
#[rustc_const_stable(feature = "const_mem_size_of", since = "1.24.0")]
347
#[rustc_diagnostic_item = "mem_size_of"]
348
5503873
pub const fn size_of<T>() -> usize {
349
5503873
    intrinsics::size_of::<T>()
350
5503873
}
351

            
352
/// Returns the size of the pointed-to value in bytes.
353
///
354
/// This is usually the same as [`size_of::<T>()`]. However, when `T` *has* no
355
/// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
356
/// then `size_of_val` can be used to get the dynamically-known size.
357
///
358
/// [trait object]: ../../book/ch17-02-trait-objects.html
359
///
360
/// # Examples
361
///
362
/// ```
363
/// assert_eq!(4, size_of_val(&5i32));
364
///
365
/// let x: [u8; 13] = [0; 13];
366
/// let y: &[u8] = &x;
367
/// assert_eq!(13, size_of_val(y));
368
/// ```
369
///
370
/// [`size_of::<T>()`]: size_of
371
#[inline]
372
#[must_use]
373
#[stable(feature = "rust1", since = "1.0.0")]
374
#[rustc_const_stable(feature = "const_size_of_val", since = "1.85.0")]
375
#[rustc_diagnostic_item = "mem_size_of_val"]
376
#[cfg(not(feature = "ferrocene_certified"))]
377
pub const fn size_of_val<T: ?Sized>(val: &T) -> usize {
378
    // SAFETY: `val` is a reference, so it's a valid raw pointer
379
    unsafe { intrinsics::size_of_val(val) }
380
}
381

            
382
/// Returns the size of the pointed-to value in bytes.
383
///
384
/// This is usually the same as [`size_of::<T>()`]. However, when `T` *has* no
385
/// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
386
/// then `size_of_val_raw` can be used to get the dynamically-known size.
387
///
388
/// # Safety
389
///
390
/// This function is only safe to call if the following conditions hold:
391
///
392
/// - If `T` is `Sized`, this function is always safe to call.
393
/// - If the unsized tail of `T` is:
394
///     - a [slice], then the length of the slice tail must be an initialized
395
///       integer, and the size of the *entire value*
396
///       (dynamic tail length + statically sized prefix) must fit in `isize`.
397
///       For the special case where the dynamic tail length is 0, this function
398
///       is safe to call.
399
//        NOTE: the reason this is safe is that if an overflow were to occur already with size 0,
400
//        then we would stop compilation as even the "statically known" part of the type would
401
//        already be too big (or the call may be in dead code and optimized away, but then it
402
//        doesn't matter).
403
///     - a [trait object], then the vtable part of the pointer must point
404
///       to a valid vtable acquired by an unsizing coercion, and the size
405
///       of the *entire value* (dynamic tail length + statically sized prefix)
406
///       must fit in `isize`.
407
///     - an (unstable) [extern type], then this function is always safe to
408
///       call, but may panic or otherwise return the wrong value, as the
409
///       extern type's layout is not known. This is the same behavior as
410
///       [`size_of_val`] on a reference to a type with an extern type tail.
411
///     - otherwise, it is conservatively not allowed to call this function.
412
///
413
/// [`size_of::<T>()`]: size_of
414
/// [trait object]: ../../book/ch17-02-trait-objects.html
415
/// [extern type]: ../../unstable-book/language-features/extern-types.html
416
///
417
/// # Examples
418
///
419
/// ```
420
/// #![feature(layout_for_ptr)]
421
/// use std::mem;
422
///
423
/// assert_eq!(4, size_of_val(&5i32));
424
///
425
/// let x: [u8; 13] = [0; 13];
426
/// let y: &[u8] = &x;
427
/// assert_eq!(13, unsafe { mem::size_of_val_raw(y) });
428
/// ```
429
#[inline]
430
#[must_use]
431
#[unstable(feature = "layout_for_ptr", issue = "69835")]
432
#[cfg(not(feature = "ferrocene_certified"))]
433
pub const unsafe fn size_of_val_raw<T: ?Sized>(val: *const T) -> usize {
434
    // SAFETY: the caller must provide a valid raw pointer
435
    unsafe { intrinsics::size_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
/// # #![allow(deprecated)]
450
/// use std::mem;
451
///
452
/// assert_eq!(4, mem::min_align_of::<i32>());
453
/// ```
454
#[inline]
455
#[must_use]
456
#[stable(feature = "rust1", since = "1.0.0")]
457
#[deprecated(note = "use `align_of` instead", since = "1.2.0", suggestion = "align_of")]
458
#[cfg(not(feature = "ferrocene_certified"))]
459
pub fn min_align_of<T>() -> usize {
460
    intrinsics::align_of::<T>()
461
}
462

            
463
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
464
/// bytes.
465
///
466
/// Every reference to a value of the type `T` must be a multiple of this number.
467
///
468
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
469
///
470
/// # Examples
471
///
472
/// ```
473
/// # #![allow(deprecated)]
474
/// use std::mem;
475
///
476
/// assert_eq!(4, mem::min_align_of_val(&5i32));
477
/// ```
478
#[inline]
479
#[must_use]
480
#[stable(feature = "rust1", since = "1.0.0")]
481
#[deprecated(note = "use `align_of_val` instead", since = "1.2.0", suggestion = "align_of_val")]
482
#[cfg(not(feature = "ferrocene_certified"))]
483
pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
484
    // SAFETY: val is a reference, so it's a valid raw pointer
485
    unsafe { intrinsics::align_of_val(val) }
486
}
487

            
488
/// Returns the [ABI]-required minimum alignment of a type in bytes.
489
///
490
/// Every reference to a value of the type `T` must be a multiple of this number.
491
///
492
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
493
///
494
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
495
///
496
/// # Examples
497
///
498
/// ```
499
/// assert_eq!(4, align_of::<i32>());
500
/// ```
501
#[inline(always)]
502
#[must_use]
503
#[stable(feature = "rust1", since = "1.0.0")]
504
#[rustc_promotable]
505
#[rustc_const_stable(feature = "const_align_of", since = "1.24.0")]
506
#[rustc_diagnostic_item = "mem_align_of"]
507
2896801
pub const fn align_of<T>() -> usize {
508
2896801
    intrinsics::align_of::<T>()
509
2896801
}
510

            
511
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
512
/// bytes.
513
///
514
/// Every reference to a value of the type `T` must be a multiple of this number.
515
///
516
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
517
///
518
/// # Examples
519
///
520
/// ```
521
/// assert_eq!(4, align_of_val(&5i32));
522
/// ```
523
#[inline]
524
#[must_use]
525
#[stable(feature = "rust1", since = "1.0.0")]
526
#[rustc_const_stable(feature = "const_align_of_val", since = "1.85.0")]
527
#[cfg(not(feature = "ferrocene_certified"))]
528
pub const fn align_of_val<T: ?Sized>(val: &T) -> usize {
529
    // SAFETY: val is a reference, so it's a valid raw pointer
530
    unsafe { intrinsics::align_of_val(val) }
531
}
532

            
533
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to in
534
/// bytes.
535
///
536
/// Every reference to a value of the type `T` must be a multiple of this number.
537
///
538
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
539
///
540
/// # Safety
541
///
542
/// This function is only safe to call if the following conditions hold:
543
///
544
/// - If `T` is `Sized`, this function is always safe to call.
545
/// - If the unsized tail of `T` is:
546
///     - a [slice], then the length of the slice tail must be an initialized
547
///       integer, and the size of the *entire value*
548
///       (dynamic tail length + statically sized prefix) must fit in `isize`.
549
///       For the special case where the dynamic tail length is 0, this function
550
///       is safe to call.
551
///     - a [trait object], then the vtable part of the pointer must point
552
///       to a valid vtable acquired by an unsizing coercion, and the size
553
///       of the *entire value* (dynamic tail length + statically sized prefix)
554
///       must fit in `isize`.
555
///     - an (unstable) [extern type], then this function is always safe to
556
///       call, but may panic or otherwise return the wrong value, as the
557
///       extern type's layout is not known. This is the same behavior as
558
///       [`align_of_val`] on a reference to a type with an extern type tail.
559
///     - otherwise, it is conservatively not allowed to call this function.
560
///
561
/// [trait object]: ../../book/ch17-02-trait-objects.html
562
/// [extern type]: ../../unstable-book/language-features/extern-types.html
563
///
564
/// # Examples
565
///
566
/// ```
567
/// #![feature(layout_for_ptr)]
568
/// use std::mem;
569
///
570
/// assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) });
571
/// ```
572
#[inline]
573
#[must_use]
574
#[unstable(feature = "layout_for_ptr", issue = "69835")]
575
#[cfg(not(feature = "ferrocene_certified"))]
576
pub const unsafe fn align_of_val_raw<T: ?Sized>(val: *const T) -> usize {
577
    // SAFETY: the caller must provide a valid raw pointer
578
    unsafe { intrinsics::align_of_val(val) }
579
}
580

            
581
/// Returns `true` if dropping values of type `T` matters.
582
///
583
/// This is purely an optimization hint, and may be implemented conservatively:
584
/// it may return `true` for types that don't actually need to be dropped.
585
/// As such always returning `true` would be a valid implementation of
586
/// this function. However if this function actually returns `false`, then you
587
/// can be certain dropping `T` has no side effect.
588
///
589
/// Low level implementations of things like collections, which need to manually
590
/// drop their data, should use this function to avoid unnecessarily
591
/// trying to drop all their contents when they are destroyed. This might not
592
/// make a difference in release builds (where a loop that has no side-effects
593
/// is easily detected and eliminated), but is often a big win for debug builds.
594
///
595
/// Note that [`drop_in_place`] already performs this check, so if your workload
596
/// can be reduced to some small number of [`drop_in_place`] calls, using this is
597
/// unnecessary. In particular note that you can [`drop_in_place`] a slice, and that
598
/// will do a single needs_drop check for all the values.
599
///
600
/// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
601
/// `needs_drop` explicitly. Types like [`HashMap`], on the other hand, have to drop
602
/// values one at a time and should use this API.
603
///
604
/// [`drop_in_place`]: crate::ptr::drop_in_place
605
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
606
///
607
/// # Examples
608
///
609
/// Here's an example of how a collection might make use of `needs_drop`:
610
///
611
/// ```
612
/// use std::{mem, ptr};
613
///
614
/// pub struct MyCollection<T> {
615
/// #   data: [T; 1],
616
///     /* ... */
617
/// }
618
/// # impl<T> MyCollection<T> {
619
/// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
620
/// #   fn free_buffer(&mut self) {}
621
/// # }
622
///
623
/// impl<T> Drop for MyCollection<T> {
624
///     fn drop(&mut self) {
625
///         unsafe {
626
///             // drop the data
627
///             if mem::needs_drop::<T>() {
628
///                 for x in self.iter_mut() {
629
///                     ptr::drop_in_place(x);
630
///                 }
631
///             }
632
///             self.free_buffer();
633
///         }
634
///     }
635
/// }
636
/// ```
637
#[inline]
638
#[must_use]
639
#[stable(feature = "needs_drop", since = "1.21.0")]
640
#[rustc_const_stable(feature = "const_mem_needs_drop", since = "1.36.0")]
641
#[rustc_diagnostic_item = "needs_drop"]
642
#[cfg(not(feature = "ferrocene_certified"))]
643
pub const fn needs_drop<T: ?Sized>() -> bool {
644
    const { intrinsics::needs_drop::<T>() }
645
}
646

            
647
/// Returns the value of type `T` represented by the all-zero byte-pattern.
648
///
649
/// This means that, for example, the padding byte in `(u8, u16)` is not
650
/// necessarily zeroed.
651
///
652
/// There is no guarantee that an all-zero byte-pattern represents a valid value
653
/// of some type `T`. For example, the all-zero byte-pattern is not a valid value
654
/// for reference types (`&T`, `&mut T`) and function pointers. Using `zeroed`
655
/// on such types causes immediate [undefined behavior][ub] because [the Rust
656
/// compiler assumes][inv] that there always is a valid value in a variable it
657
/// considers initialized.
658
///
659
/// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
660
/// It is useful for FFI sometimes, but should generally be avoided.
661
///
662
/// [zeroed]: MaybeUninit::zeroed
663
/// [ub]: ../../reference/behavior-considered-undefined.html
664
/// [inv]: MaybeUninit#initialization-invariant
665
///
666
/// # Examples
667
///
668
/// Correct usage of this function: initializing an integer with zero.
669
///
670
/// ```
671
/// use std::mem;
672
///
673
/// let x: i32 = unsafe { mem::zeroed() };
674
/// assert_eq!(0, x);
675
/// ```
676
///
677
/// *Incorrect* usage of this function: initializing a reference with zero.
678
///
679
/// ```rust,no_run
680
/// # #![allow(invalid_value)]
681
/// use std::mem;
682
///
683
/// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
684
/// let _y: fn() = unsafe { mem::zeroed() }; // And again!
685
/// ```
686
#[inline(always)]
687
#[must_use]
688
#[stable(feature = "rust1", since = "1.0.0")]
689
#[rustc_diagnostic_item = "mem_zeroed"]
690
#[track_caller]
691
#[rustc_const_stable(feature = "const_mem_zeroed", since = "1.75.0")]
692
#[cfg(not(feature = "ferrocene_certified"))]
693
pub const unsafe fn zeroed<T>() -> T {
694
    // SAFETY: the caller must guarantee that an all-zero value is valid for `T`.
695
    unsafe {
696
        intrinsics::assert_zero_valid::<T>();
697
        MaybeUninit::zeroed().assume_init()
698
    }
699
}
700

            
701
/// Bypasses Rust's normal memory-initialization checks by pretending to
702
/// produce a value of type `T`, while doing nothing at all.
703
///
704
/// **This function is deprecated.** Use [`MaybeUninit<T>`] instead.
705
/// It also might be slower than using `MaybeUninit<T>` due to mitigations that were put in place to
706
/// limit the potential harm caused by incorrect use of this function in legacy code.
707
///
708
/// The reason for deprecation is that the function basically cannot be used
709
/// correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`][uninit].
710
/// As the [`assume_init` documentation][assume_init] explains,
711
/// [the Rust compiler assumes][inv] that values are properly initialized.
712
///
713
/// Truly uninitialized memory like what gets returned here
714
/// is special in that the compiler knows that it does not have a fixed value.
715
/// This makes it undefined behavior to have uninitialized data in a variable even
716
/// if that variable has an integer type.
717
///
718
/// Therefore, it is immediate undefined behavior to call this function on nearly all types,
719
/// including integer types and arrays of integer types, and even if the result is unused.
720
///
721
/// [uninit]: MaybeUninit::uninit
722
/// [assume_init]: MaybeUninit::assume_init
723
/// [inv]: MaybeUninit#initialization-invariant
724
#[inline(always)]
725
#[must_use]
726
#[deprecated(since = "1.39.0", note = "use `mem::MaybeUninit` instead")]
727
#[stable(feature = "rust1", since = "1.0.0")]
728
#[rustc_diagnostic_item = "mem_uninitialized"]
729
#[track_caller]
730
#[cfg(not(feature = "ferrocene_certified"))]
731
pub unsafe fn uninitialized<T>() -> T {
732
    // SAFETY: the caller must guarantee that an uninitialized value is valid for `T`.
733
    unsafe {
734
        intrinsics::assert_mem_uninitialized_valid::<T>();
735
        let mut val = MaybeUninit::<T>::uninit();
736

            
737
        // Fill memory with 0x01, as an imperfect mitigation for old code that uses this function on
738
        // bool, nonnull, and noundef types. But don't do this if we actively want to detect UB.
739
        if !cfg!(any(miri, sanitize = "memory")) {
740
            val.as_mut_ptr().write_bytes(0x01, 1);
741
        }
742

            
743
        val.assume_init()
744
    }
745
}
746

            
747
/// Swaps the values at two mutable locations, without deinitializing either one.
748
///
749
/// * If you want to swap with a default or dummy value, see [`take`].
750
/// * If you want to swap with a passed value, returning the old value, see [`replace`].
751
///
752
/// # Examples
753
///
754
/// ```
755
/// use std::mem;
756
///
757
/// let mut x = 5;
758
/// let mut y = 42;
759
///
760
/// mem::swap(&mut x, &mut y);
761
///
762
/// assert_eq!(42, x);
763
/// assert_eq!(5, y);
764
/// ```
765
#[inline]
766
#[stable(feature = "rust1", since = "1.0.0")]
767
#[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
768
#[rustc_diagnostic_item = "mem_swap"]
769
#[cfg(not(feature = "ferrocene_certified"))]
770
pub const fn swap<T>(x: &mut T, y: &mut T) {
771
    // SAFETY: `&mut` guarantees these are typed readable and writable
772
    // as well as non-overlapping.
773
    unsafe { intrinsics::typed_swap_nonoverlapping(x, y) }
774
}
775

            
776
/// Replaces `dest` with the default value of `T`, returning the previous `dest` value.
777
///
778
/// * If you want to replace the values of two variables, see [`swap`].
779
/// * If you want to replace with a passed value instead of the default value, see [`replace`].
780
///
781
/// # Examples
782
///
783
/// A simple example:
784
///
785
/// ```
786
/// use std::mem;
787
///
788
/// let mut v: Vec<i32> = vec![1, 2];
789
///
790
/// let old_v = mem::take(&mut v);
791
/// assert_eq!(vec![1, 2], old_v);
792
/// assert!(v.is_empty());
793
/// ```
794
///
795
/// `take` allows taking ownership of a struct field by replacing it with an "empty" value.
796
/// Without `take` you can run into issues like these:
797
///
798
/// ```compile_fail,E0507
799
/// struct Buffer<T> { buf: Vec<T> }
800
///
801
/// impl<T> Buffer<T> {
802
///     fn get_and_reset(&mut self) -> Vec<T> {
803
///         // error: cannot move out of dereference of `&mut`-pointer
804
///         let buf = self.buf;
805
///         self.buf = Vec::new();
806
///         buf
807
///     }
808
/// }
809
/// ```
810
///
811
/// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
812
/// `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from
813
/// `self`, allowing it to be returned:
814
///
815
/// ```
816
/// use std::mem;
817
///
818
/// # struct Buffer<T> { buf: Vec<T> }
819
/// impl<T> Buffer<T> {
820
///     fn get_and_reset(&mut self) -> Vec<T> {
821
///         mem::take(&mut self.buf)
822
///     }
823
/// }
824
///
825
/// let mut buffer = Buffer { buf: vec![0, 1] };
826
/// assert_eq!(buffer.buf.len(), 2);
827
///
828
/// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
829
/// assert_eq!(buffer.buf.len(), 0);
830
/// ```
831
#[inline]
832
#[stable(feature = "mem_take", since = "1.40.0")]
833
#[cfg(not(feature = "ferrocene_certified"))]
834
pub fn take<T: Default>(dest: &mut T) -> T {
835
    replace(dest, T::default())
836
}
837

            
838
/// Moves `src` into the referenced `dest`, returning the previous `dest` value.
839
///
840
/// Neither value is dropped.
841
///
842
/// * If you want to replace the values of two variables, see [`swap`].
843
/// * If you want to replace with a default value, see [`take`].
844
///
845
/// # Examples
846
///
847
/// A simple example:
848
///
849
/// ```
850
/// use std::mem;
851
///
852
/// let mut v: Vec<i32> = vec![1, 2];
853
///
854
/// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
855
/// assert_eq!(vec![1, 2], old_v);
856
/// assert_eq!(vec![3, 4, 5], v);
857
/// ```
858
///
859
/// `replace` allows consumption of a struct field by replacing it with another value.
860
/// Without `replace` you can run into issues like these:
861
///
862
/// ```compile_fail,E0507
863
/// struct Buffer<T> { buf: Vec<T> }
864
///
865
/// impl<T> Buffer<T> {
866
///     fn replace_index(&mut self, i: usize, v: T) -> T {
867
///         // error: cannot move out of dereference of `&mut`-pointer
868
///         let t = self.buf[i];
869
///         self.buf[i] = v;
870
///         t
871
///     }
872
/// }
873
/// ```
874
///
875
/// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
876
/// avoid the move. But `replace` can be used to disassociate the original value at that index from
877
/// `self`, allowing it to be returned:
878
///
879
/// ```
880
/// # #![allow(dead_code)]
881
/// use std::mem;
882
///
883
/// # struct Buffer<T> { buf: Vec<T> }
884
/// impl<T> Buffer<T> {
885
///     fn replace_index(&mut self, i: usize, v: T) -> T {
886
///         mem::replace(&mut self.buf[i], v)
887
///     }
888
/// }
889
///
890
/// let mut buffer = Buffer { buf: vec![0, 1] };
891
/// assert_eq!(buffer.buf[0], 0);
892
///
893
/// assert_eq!(buffer.replace_index(0, 2), 0);
894
/// assert_eq!(buffer.buf[0], 2);
895
/// ```
896
#[inline]
897
#[stable(feature = "rust1", since = "1.0.0")]
898
#[must_use = "if you don't need the old value, you can just assign the new value directly"]
899
#[rustc_const_stable(feature = "const_replace", since = "1.83.0")]
900
#[rustc_diagnostic_item = "mem_replace"]
901
#[cfg(not(feature = "ferrocene_certified"))]
902
pub const fn replace<T>(dest: &mut T, src: T) -> T {
903
    // It may be tempting to use `swap` to avoid `unsafe` here. Don't!
904
    // The compiler optimizes the implementation below to two `memcpy`s
905
    // while `swap` would require at least three. See PR#83022 for details.
906

            
907
    // SAFETY: We read from `dest` but directly write `src` into it afterwards,
908
    // such that the old value is not duplicated. Nothing is dropped and
909
    // nothing here can panic.
910
    unsafe {
911
        // Ideally we wouldn't use the intrinsics here, but going through the
912
        // `ptr` methods introduces two unnecessary UbChecks, so until we can
913
        // remove those for pointers that come from references, this uses the
914
        // intrinsics instead so this stays very cheap in MIR (and debug).
915

            
916
        let result = crate::intrinsics::read_via_copy(dest);
917
        crate::intrinsics::write_via_move(dest, src);
918
        result
919
    }
920
}
921

            
922
/// Disposes of a value.
923
///
924
/// This does so by calling the argument's implementation of [`Drop`][drop].
925
///
926
/// This effectively does nothing for types which implement `Copy`, e.g.
927
/// integers. Such values are copied and _then_ moved into the function, so the
928
/// value persists after this function call.
929
///
930
/// This function is not magic; it is literally defined as
931
///
932
/// ```
933
/// pub fn drop<T>(_x: T) {}
934
/// ```
935
///
936
/// Because `_x` is moved into the function, it is automatically dropped before
937
/// the function returns.
938
///
939
/// [drop]: Drop
940
///
941
/// # Examples
942
///
943
/// Basic usage:
944
///
945
/// ```
946
/// let v = vec![1, 2, 3];
947
///
948
/// drop(v); // explicitly drop the vector
949
/// ```
950
///
951
/// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
952
/// release a [`RefCell`] borrow:
953
///
954
/// ```
955
/// use std::cell::RefCell;
956
///
957
/// let x = RefCell::new(1);
958
///
959
/// let mut mutable_borrow = x.borrow_mut();
960
/// *mutable_borrow = 1;
961
///
962
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
963
///
964
/// let borrow = x.borrow();
965
/// println!("{}", *borrow);
966
/// ```
967
///
968
/// Integers and other types implementing [`Copy`] are unaffected by `drop`.
969
///
970
/// ```
971
/// # #![allow(dropping_copy_types)]
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
#[rustc_diagnostic_item = "mem_drop"]
987
2833
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 const 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
/// ```
/// #![feature(mem_copy_fn)]
/// use core::mem::copy;
/// let result_from_ffi_function: Result<(), &i32> = Err(&1);
/// let result_copied: Result<(), i32> = result_from_ffi_function.map_err(copy);
/// ```
#[inline]
#[unstable(feature = "mem_copy_fn", issue = "98262")]
#[cfg(not(feature = "ferrocene_certified"))]
pub const fn copy<T: Copy>(x: &T) -> T {
    *x
}
/// Interprets `src` as having type `&Dst`, and then reads `src` without moving
/// the contained value.
///
/// This function will unsafely assume the pointer `src` is valid for [`size_of::<Dst>`][size_of]
/// bytes by transmuting `&Src` to `&Dst` and then reading the `&Dst` (except that this is done
/// in a way that is correct even when `&Dst` has stricter alignment requirements than `&Src`).
/// It will also unsafely create a copy of the contained value instead of moving out of `src`.
///
/// It is not a compile-time error if `Src` and `Dst` have different sizes, but it
/// is highly encouraged to only invoke this function where `Src` and `Dst` have the
/// same size. This function triggers [undefined behavior][ub] if `Dst` is larger than
/// `Src`.
///
/// [ub]: ../../reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// #[repr(packed)]
/// struct Foo {
///     bar: u8,
/// }
///
/// let foo_array = [10u8];
///
/// unsafe {
///     // Copy the data from 'foo_array' and treat it as a 'Foo'
///     let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
///     assert_eq!(foo_struct.bar, 10);
///
///     // Modify the copied data
///     foo_struct.bar = 20;
///     assert_eq!(foo_struct.bar, 20);
/// }
///
/// // The contents of 'foo_array' should not have changed
/// assert_eq!(foo_array, [10]);
/// ```
#[inline]
#[must_use]
#[track_caller]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_transmute_copy", since = "1.74.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub const unsafe fn transmute_copy<Src, Dst>(src: &Src) -> Dst {
    assert!(
        size_of::<Src>() >= size_of::<Dst>(),
        "cannot transmute_copy if Dst is larger than Src"
    );
    // If Dst has a higher alignment requirement, src might not be suitably aligned.
    if align_of::<Dst>() > align_of::<Src>() {
        // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
        // The caller must guarantee that the actual transmutation is safe.
        unsafe { ptr::read_unaligned(src as *const Src as *const Dst) }
    } else {
        // SAFETY: `src` is a reference which is guaranteed to be valid for reads.
        // We just checked that `src as *const Dst` was properly aligned.
        // The caller must guarantee that the actual transmutation is safe.
        unsafe { ptr::read(src as *const Src as *const Dst) }
    }
}
/// Opaque type representing the discriminant of an enum.
///
/// See the [`discriminant`] function in this module for more information.
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
pub struct Discriminant<T>(<T as DiscriminantKind>::Discriminant);
// N.B. These trait implementations cannot be derived because we don't want any bounds on T.
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> Copy for Discriminant<T> {}
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> clone::Clone for Discriminant<T> {
    fn clone(&self) -> Self {
        *self
    }
}
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> cmp::PartialEq for Discriminant<T> {
    fn eq(&self, rhs: &Self) -> bool {
        self.0 == rhs.0
    }
}
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> cmp::Eq for Discriminant<T> {}
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> hash::Hash for Discriminant<T> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[cfg(not(feature = "ferrocene_certified"))]
impl<T> fmt::Debug for Discriminant<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_tuple("Discriminant").field(&self.0).finish()
    }
}
/// Returns a value uniquely identifying the enum variant in `v`.
///
/// If `T` is not an enum, calling this function will not result in undefined behavior, but the
/// return value is unspecified.
///
/// # Stability
///
/// The discriminant of an enum variant may change if the enum definition changes. A discriminant
/// of some variant will not change between compilations with the same compiler. See the [Reference]
/// for more information.
///
/// [Reference]: ../../reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
///
/// The value of a [`Discriminant<T>`] is independent of any *free lifetimes* in `T`. As such,
/// reading or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via
/// [`transmute`] or otherwise) is always sound. Note that this is **not** true for other kinds
/// of generic parameters and for higher-ranked lifetimes; `Discriminant<Foo<A>>` and
/// `Discriminant<Foo<B>>` as well as `Discriminant<Bar<dyn for<'a> Trait<'a>>>` and
/// `Discriminant<Bar<dyn Trait<'static>>>` may be incompatible.
///
/// # Examples
///
/// This can be used to compare enums that carry data, while disregarding
/// the actual data:
///
/// ```
/// use std::mem;
///
/// enum Foo { A(&'static str), B(i32), C(i32) }
///
/// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
/// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
/// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));
/// ```
///
/// ## Accessing the numeric value of the discriminant
///
/// Note that it is *undefined behavior* to [`transmute`] from [`Discriminant`] to a primitive!
///
/// If an enum has only unit variants, then the numeric value of the discriminant can be accessed
/// with an [`as`] cast:
///
/// ```
/// enum Enum {
///     Foo,
///     Bar,
///     Baz,
/// }
///
/// assert_eq!(0, Enum::Foo as isize);
/// assert_eq!(1, Enum::Bar as isize);
/// assert_eq!(2, Enum::Baz as isize);
/// ```
///
/// If an enum has opted-in to having a [primitive representation] for its discriminant,
/// then it's possible to use pointers to read the memory location storing the discriminant.
/// That **cannot** be done for enums using the [default representation], however, as it's
/// undefined what layout the discriminant has and where it's stored — it might not even be
/// stored at all!
///
/// [`as`]: ../../std/keyword.as.html
/// [primitive representation]: ../../reference/type-layout.html#primitive-representations
/// [default representation]: ../../reference/type-layout.html#the-default-representation
/// ```
/// #[repr(u8)]
/// enum Enum {
///     Unit,
///     Tuple(bool),
///     Struct { a: bool },
/// }
///
/// impl Enum {
///     fn discriminant(&self) -> u8 {
///         // SAFETY: Because `Self` is marked `repr(u8)`, its layout is a `repr(C)` `union`
///         // between `repr(C)` structs, each of which has the `u8` discriminant as its first
///         // field, so we can read the discriminant without offsetting the pointer.
///         unsafe { *<*const _>::from(self).cast::<u8>() }
///     }
/// }
///
/// let unit_like = Enum::Unit;
/// let tuple_like = Enum::Tuple(true);
/// let struct_like = Enum::Struct { a: false };
/// assert_eq!(0, unit_like.discriminant());
/// assert_eq!(1, tuple_like.discriminant());
/// assert_eq!(2, struct_like.discriminant());
///
/// // ⚠️ This is undefined behavior. Don't do this. ⚠️
/// // assert_eq!(0, unsafe { std::mem::transmute::<_, u8>(std::mem::discriminant(&unit_like)) });
/// ```
#[stable(feature = "discriminant_value", since = "1.21.0")]
#[rustc_const_stable(feature = "const_discriminant", since = "1.75.0")]
#[rustc_diagnostic_item = "mem_discriminant"]
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
#[cfg(not(feature = "ferrocene_certified"))]
pub const fn discriminant<T>(v: &T) -> Discriminant<T> {
    Discriminant(intrinsics::discriminant_value(v))
}
/// Returns the number of variants in the enum type `T`.
///
/// If `T` is not an enum, calling this function will not result in undefined behavior, but the
/// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX`
/// the return value is unspecified. Uninhabited variants will be counted.
///
/// Note that an enum may be expanded with additional variants in the future
/// as a non-breaking change, for example if it is marked `#[non_exhaustive]`,
/// which will change the result of this function.
///
/// # Examples
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(variant_count)]
///
/// use std::mem;
///
/// enum Void {}
/// enum Foo { A(&'static str), B(i32), C(i32) }
///
/// assert_eq!(mem::variant_count::<Void>(), 0);
/// assert_eq!(mem::variant_count::<Foo>(), 3);
///
/// assert_eq!(mem::variant_count::<Option<!>>(), 2);
/// assert_eq!(mem::variant_count::<Result<!, !>>(), 2);
/// ```
#[inline(always)]
#[must_use]
#[unstable(feature = "variant_count", issue = "73662")]
#[rustc_const_unstable(feature = "variant_count", issue = "73662")]
#[rustc_diagnostic_item = "mem_variant_count"]
#[cfg(not(feature = "ferrocene_certified"))]
pub const fn variant_count<T>() -> usize {
    const { intrinsics::variant_count::<T>() }
}
/// Provides associated constants for various useful properties of types,
/// to give them a canonical form in our code and make them easier to read.
///
/// This is here only to simplify all the ZST checks we need in the library.
/// It's not on a stabilization track right now.
#[doc(hidden)]
#[unstable(feature = "sized_type_properties", issue = "none")]
pub trait SizedTypeProperties: Sized {
    /// `true` if this type requires no storage.
    /// `false` if its [size](size_of) is greater than zero.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(sized_type_properties)]
    /// use core::mem::SizedTypeProperties;
    ///
    /// fn do_something_with<T>() {
    ///     if T::IS_ZST {
    ///         // ... special approach ...
    ///     } else {
    ///         // ... the normal thing ...
    ///     }
    /// }
    ///
    /// struct MyUnit;
    /// assert!(MyUnit::IS_ZST);
    ///
    /// // For negative checks, consider using UFCS to emphasize the negation
    /// assert!(!<i32>::IS_ZST);
    /// // As it can sometimes hide in the type otherwise
    /// assert!(!String::IS_ZST);
    /// ```
    #[doc(hidden)]
    #[unstable(feature = "sized_type_properties", issue = "none")]
    const IS_ZST: bool = size_of::<Self>() == 0;
    #[doc(hidden)]
    #[unstable(feature = "sized_type_properties", issue = "none")]
    const LAYOUT: Layout = Layout::new::<Self>();
    /// The largest safe length for a `[Self]`.
    ///
    /// Anything larger than this would make `size_of_val` overflow `isize::MAX`,
    /// which is never allowed for a single object.
    #[doc(hidden)]
    #[unstable(feature = "sized_type_properties", issue = "none")]
    const MAX_SLICE_LEN: usize = match size_of::<Self>() {
        0 => usize::MAX,
        n => (isize::MAX as usize) / n,
    };
}
#[doc(hidden)]
#[unstable(feature = "sized_type_properties", issue = "none")]
impl<T> SizedTypeProperties for T {}
/// Expands to the offset in bytes of a field from the beginning of the given type.
///
/// The type may be a `struct`, `enum`, `union`, or tuple.
///
/// The field may be a nested field (`field1.field2`), but not an array index.
/// The field must be visible to the call site.
///
/// The offset is returned as a [`usize`].
///
/// # Offsets of, and in, dynamically sized types
///
/// The field’s type must be [`Sized`], but it may be located in a [dynamically sized] container.
/// If the field type is dynamically sized, then you cannot use `offset_of!` (since the field's
/// alignment, and therefore its offset, may also be dynamic) and must take the offset from an
/// actual pointer to the container instead.
///
/// ```
/// # use core::mem;
/// # use core::fmt::Debug;
/// #[repr(C)]
/// pub struct Struct<T: ?Sized> {
///     a: u8,
///     b: T,
/// }
///
/// #[derive(Debug)]
/// #[repr(C, align(4))]
/// struct Align4(u32);
///
/// assert_eq!(mem::offset_of!(Struct<dyn Debug>, a), 0); // OK — Sized field
/// assert_eq!(mem::offset_of!(Struct<Align4>, b), 4); // OK — not DST
///
/// // assert_eq!(mem::offset_of!(Struct<dyn Debug>, b), 1);
/// // ^^^ error[E0277]: ... cannot be known at compilation time
///
/// // To obtain the offset of a !Sized field, examine a concrete value
/// // instead of using offset_of!.
/// let value: Struct<Align4> = Struct { a: 1, b: Align4(2) };
/// let ref_unsized: &Struct<dyn Debug> = &value;
/// let offset_of_b = unsafe {
///     (&raw const ref_unsized.b).byte_offset_from_unsigned(ref_unsized)
/// };
/// assert_eq!(offset_of_b, 4);
/// ```
///
/// If you need to obtain the offset of a field of a `!Sized` type, then, since the offset may
/// depend on the particular value being stored (in particular, `dyn Trait` values have a
/// dynamically-determined alignment), you must retrieve the offset from a specific reference
/// or pointer, and so you cannot use `offset_of!` to work without one.
///
/// # Layout is subject to change
///
/// Note that type layout is, in general, [subject to change and
/// platform-specific](https://doc.rust-lang.org/reference/type-layout.html). If
/// layout stability is required, consider using an [explicit `repr` attribute].
///
/// Rust guarantees that the offset of a given field within a given type will not
/// change over the lifetime of the program. However, two different compilations of
/// the same program may result in different layouts. Also, even within a single
/// program execution, no guarantees are made about types which are *similar* but
/// not *identical*, e.g.:
///
/// ```
/// struct Wrapper<T, U>(T, U);
///
/// type A = Wrapper<u8, u8>;
/// type B = Wrapper<u8, i8>;
///
/// // Not necessarily identical even though `u8` and `i8` have the same layout!
/// // assert_eq!(mem::offset_of!(A, 1), mem::offset_of!(B, 1));
///
/// #[repr(transparent)]
/// struct U8(u8);
///
/// type C = Wrapper<u8, U8>;
///
/// // Not necessarily identical even though `u8` and `U8` have the same layout!
/// // assert_eq!(mem::offset_of!(A, 1), mem::offset_of!(C, 1));
///
/// struct Empty<T>(core::marker::PhantomData<T>);
///
/// // Not necessarily identical even though `PhantomData` always has the same layout!
/// // assert_eq!(mem::offset_of!(Empty<u8>, 0), mem::offset_of!(Empty<i8>, 0));
/// ```
///
/// [explicit `repr` attribute]: https://doc.rust-lang.org/reference/type-layout.html#representations
///
/// # Unstable features
///
/// The following unstable features expand the functionality of `offset_of!`:
///
/// * [`offset_of_enum`] — allows `enum` variants to be traversed as if they were fields.
/// * [`offset_of_slice`] — allows getting the offset of a field of type `[T]`.
///
/// # Examples
///
/// ```
/// use std::mem;
/// #[repr(C)]
/// struct FieldStruct {
///     first: u8,
///     second: u16,
///     third: u8
/// }
///
/// assert_eq!(mem::offset_of!(FieldStruct, first), 0);
/// assert_eq!(mem::offset_of!(FieldStruct, second), 2);
/// assert_eq!(mem::offset_of!(FieldStruct, third), 4);
///
/// #[repr(C)]
/// struct NestedA {
///     b: NestedB
/// }
///
/// #[repr(C)]
/// struct NestedB(u8);
///
/// assert_eq!(mem::offset_of!(NestedA, b.0), 0);
/// ```
///
/// [dynamically sized]: https://doc.rust-lang.org/reference/dynamically-sized-types.html
/// [`offset_of_enum`]: https://doc.rust-lang.org/nightly/unstable-book/language-features/offset-of-enum.html
/// [`offset_of_slice`]: https://doc.rust-lang.org/nightly/unstable-book/language-features/offset-of-slice.html
#[stable(feature = "offset_of", since = "1.77.0")]
#[allow_internal_unstable(builtin_syntax)]
#[cfg(not(feature = "ferrocene_certified"))]
pub macro offset_of($Container:ty, $($fields:expr)+ $(,)?) {
    // The `{}` is for better error messages
    {builtin # offset_of($Container, $($fields)+)}
}