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