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