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