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