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