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