]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
058c01cdf10077ac008e5cf115c78b4de591236d
[rust.git] / src / libcore / mem.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, PhantomData, Sized};
14 use crate::ptr;
15 use crate::ops::{Deref, DerefMut};
16
17 #[stable(feature = "rust1", since = "1.0.0")]
18 #[doc(inline)]
19 pub use crate::intrinsics::transmute;
20
21 /// Takes ownership and "forgets" about the value **without running its destructor**.
22 ///
23 /// Any resources the value manages, such as heap memory or a file handle, will linger
24 /// forever in an unreachable state. However, it does not guarantee that pointers
25 /// to this memory will remain valid.
26 ///
27 /// * If you want to leak memory, see [`Box::leak`][leak].
28 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`][into_raw].
29 /// * If you want to dispose of a value properly, running its destructor, see
30 /// [`mem::drop`][drop].
31 ///
32 /// # Safety
33 ///
34 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
35 /// do not include a guarantee that destructors will always run. For example,
36 /// a program can create a reference cycle using [`Rc`][rc], or call
37 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
38 /// `mem::forget` from safe code does not fundamentally change Rust's safety
39 /// guarantees.
40 ///
41 /// That said, leaking resources such as memory or I/O objects is usually undesirable,
42 /// so `forget` is only recommended for specialized use cases like those shown below.
43 ///
44 /// Because forgetting a value is allowed, any `unsafe` code you write must
45 /// allow for this possibility. You cannot return a value and expect that the
46 /// caller will necessarily run the value's destructor.
47 ///
48 /// [rc]: ../../std/rc/struct.Rc.html
49 /// [exit]: ../../std/process/fn.exit.html
50 ///
51 /// # Examples
52 ///
53 /// Leak an I/O object, never closing the file:
54 ///
55 /// ```no_run
56 /// use std::mem;
57 /// use std::fs::File;
58 ///
59 /// let file = File::open("foo.txt").unwrap();
60 /// mem::forget(file);
61 /// ```
62 ///
63 /// The practical use cases for `forget` are rather specialized and mainly come
64 /// up in unsafe or FFI code.
65 ///
66 /// [drop]: fn.drop.html
67 /// [uninit]: fn.uninitialized.html
68 /// [clone]: ../clone/trait.Clone.html
69 /// [swap]: fn.swap.html
70 /// [box]: ../../std/boxed/struct.Box.html
71 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
72 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
73 /// [ub]: ../../reference/behavior-considered-undefined.html
74 #[inline]
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub fn forget<T>(t: T) {
77     ManuallyDrop::new(t);
78 }
79
80 /// Like [`forget`], but also accepts unsized values.
81 ///
82 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
83 /// stabilized.
84 ///
85 /// [`forget`]: fn.forget.html
86 #[inline]
87 #[unstable(feature = "forget_unsized", issue = "0")]
88 pub fn forget_unsized<T: ?Sized>(t: T) {
89     unsafe { intrinsics::forget(t) }
90 }
91
92 /// Returns the size of a type in bytes.
93 ///
94 /// More specifically, this is the offset in bytes between successive elements
95 /// in an array with that item type including alignment padding. Thus, for any
96 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
97 ///
98 /// In general, the size of a type is not stable across compilations, but
99 /// specific types such as primitives are.
100 ///
101 /// The following table gives the size for primitives.
102 ///
103 /// Type | size_of::\<Type>()
104 /// ---- | ---------------
105 /// () | 0
106 /// bool | 1
107 /// u8 | 1
108 /// u16 | 2
109 /// u32 | 4
110 /// u64 | 8
111 /// u128 | 16
112 /// i8 | 1
113 /// i16 | 2
114 /// i32 | 4
115 /// i64 | 8
116 /// i128 | 16
117 /// f32 | 4
118 /// f64 | 8
119 /// char | 4
120 ///
121 /// Furthermore, `usize` and `isize` have the same size.
122 ///
123 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
124 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
125 ///
126 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
127 /// have the same size. Likewise for `*const T` and `*mut T`.
128 ///
129 /// # Size of `#[repr(C)]` items
130 ///
131 /// The `C` representation for items has a defined layout. With this layout,
132 /// the size of items is also stable as long as all fields have a stable size.
133 ///
134 /// ## Size of Structs
135 ///
136 /// For `structs`, the size is determined by the following algorithm.
137 ///
138 /// For each field in the struct ordered by declaration order:
139 ///
140 /// 1. Add the size of the field.
141 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
142 ///
143 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
144 /// The alignment of the struct is usually the largest alignment of all its
145 /// fields; this can be changed with the use of `repr(align(N))`.
146 ///
147 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
148 ///
149 /// ## Size of Enums
150 ///
151 /// Enums that carry no data other than the discriminant have the same size as C enums
152 /// on the platform they are compiled for.
153 ///
154 /// ## Size of Unions
155 ///
156 /// The size of a union is the size of its largest field.
157 ///
158 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
159 ///
160 /// # Examples
161 ///
162 /// ```
163 /// use std::mem;
164 ///
165 /// // Some primitives
166 /// assert_eq!(4, mem::size_of::<i32>());
167 /// assert_eq!(8, mem::size_of::<f64>());
168 /// assert_eq!(0, mem::size_of::<()>());
169 ///
170 /// // Some arrays
171 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
172 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
173 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
174 ///
175 ///
176 /// // Pointer size equality
177 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
178 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
179 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
180 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
181 /// ```
182 ///
183 /// Using `#[repr(C)]`.
184 ///
185 /// ```
186 /// use std::mem;
187 ///
188 /// #[repr(C)]
189 /// struct FieldStruct {
190 ///     first: u8,
191 ///     second: u16,
192 ///     third: u8
193 /// }
194 ///
195 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
196 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
197 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
198 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
199 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
200 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
201 /// // fields is 2), so add 1 to the size for padding. Size is 6.
202 /// assert_eq!(6, mem::size_of::<FieldStruct>());
203 ///
204 /// #[repr(C)]
205 /// struct TupleStruct(u8, u16, u8);
206 ///
207 /// // Tuple structs follow the same rules.
208 /// assert_eq!(6, mem::size_of::<TupleStruct>());
209 ///
210 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
211 /// // by putting `third` before `second`.
212 /// #[repr(C)]
213 /// struct FieldStructOptimized {
214 ///     first: u8,
215 ///     third: u8,
216 ///     second: u16
217 /// }
218 ///
219 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
220 ///
221 /// // Union size is the size of the largest field.
222 /// #[repr(C)]
223 /// union ExampleUnion {
224 ///     smaller: u8,
225 ///     larger: u16
226 /// }
227 ///
228 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
229 /// ```
230 ///
231 /// [alignment]: ./fn.align_of.html
232 #[inline]
233 #[stable(feature = "rust1", since = "1.0.0")]
234 #[rustc_promotable]
235 pub const fn size_of<T>() -> usize {
236     intrinsics::size_of::<T>()
237 }
238
239 /// Returns the size of the pointed-to value in bytes.
240 ///
241 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
242 /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object],
243 /// then `size_of_val` can be used to get the dynamically-known size.
244 ///
245 /// [slice]: ../../std/primitive.slice.html
246 /// [trait object]: ../../book/ch17-02-trait-objects.html
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// use std::mem;
252 ///
253 /// assert_eq!(4, mem::size_of_val(&5i32));
254 ///
255 /// let x: [u8; 13] = [0; 13];
256 /// let y: &[u8] = &x;
257 /// assert_eq!(13, mem::size_of_val(y));
258 /// ```
259 #[inline]
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
262     unsafe { intrinsics::size_of_val(val) }
263 }
264
265 /// Returns the [ABI]-required minimum alignment of a type.
266 ///
267 /// Every reference to a value of the type `T` must be a multiple of this number.
268 ///
269 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
270 ///
271 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// # #![allow(deprecated)]
277 /// use std::mem;
278 ///
279 /// assert_eq!(4, mem::min_align_of::<i32>());
280 /// ```
281 #[inline]
282 #[stable(feature = "rust1", since = "1.0.0")]
283 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
284 pub fn min_align_of<T>() -> usize {
285     intrinsics::min_align_of::<T>()
286 }
287
288 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
289 ///
290 /// Every reference to a value of the type `T` must be a multiple of this number.
291 ///
292 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// # #![allow(deprecated)]
298 /// use std::mem;
299 ///
300 /// assert_eq!(4, mem::min_align_of_val(&5i32));
301 /// ```
302 #[inline]
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
305 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
306     unsafe { intrinsics::min_align_of_val(val) }
307 }
308
309 /// Returns the [ABI]-required minimum alignment of a type.
310 ///
311 /// Every reference to a value of the type `T` must be a multiple of this number.
312 ///
313 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
314 ///
315 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use std::mem;
321 ///
322 /// assert_eq!(4, mem::align_of::<i32>());
323 /// ```
324 #[inline]
325 #[stable(feature = "rust1", since = "1.0.0")]
326 #[rustc_promotable]
327 pub const fn align_of<T>() -> usize {
328     intrinsics::min_align_of::<T>()
329 }
330
331 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
332 ///
333 /// Every reference to a value of the type `T` must be a multiple of this number.
334 ///
335 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// use std::mem;
341 ///
342 /// assert_eq!(4, mem::align_of_val(&5i32));
343 /// ```
344 #[inline]
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
347     unsafe { intrinsics::min_align_of_val(val) }
348 }
349
350 /// Returns `true` if dropping values of type `T` matters.
351 ///
352 /// This is purely an optimization hint, and may be implemented conservatively:
353 /// it may return `true` for types that don't actually need to be dropped.
354 /// As such always returning `true` would be a valid implementation of
355 /// this function. However if this function actually returns `false`, then you
356 /// can be certain dropping `T` has no side effect.
357 ///
358 /// Low level implementations of things like collections, which need to manually
359 /// drop their data, should use this function to avoid unnecessarily
360 /// trying to drop all their contents when they are destroyed. This might not
361 /// make a difference in release builds (where a loop that has no side-effects
362 /// is easily detected and eliminated), but is often a big win for debug builds.
363 ///
364 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
365 /// can be reduced to some small number of drop_in_place calls, using this is
366 /// unnecessary. In particular note that you can drop_in_place a slice, and that
367 /// will do a single needs_drop check for all the values.
368 ///
369 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
370 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
371 /// values one at a time and should use this API.
372 ///
373 ///
374 /// # Examples
375 ///
376 /// Here's an example of how a collection might make use of needs_drop:
377 ///
378 /// ```
379 /// use std::{mem, ptr};
380 ///
381 /// pub struct MyCollection<T> {
382 /// #   data: [T; 1],
383 ///     /* ... */
384 /// }
385 /// # impl<T> MyCollection<T> {
386 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
387 /// #   fn free_buffer(&mut self) {}
388 /// # }
389 ///
390 /// impl<T> Drop for MyCollection<T> {
391 ///     fn drop(&mut self) {
392 ///         unsafe {
393 ///             // drop the data
394 ///             if mem::needs_drop::<T>() {
395 ///                 for x in self.iter_mut() {
396 ///                     ptr::drop_in_place(x);
397 ///                 }
398 ///             }
399 ///             self.free_buffer();
400 ///         }
401 ///     }
402 /// }
403 /// ```
404 #[inline]
405 #[stable(feature = "needs_drop", since = "1.21.0")]
406 pub const fn needs_drop<T>() -> bool {
407     intrinsics::needs_drop::<T>()
408 }
409
410 /// Creates a value whose bytes are all zero.
411 ///
412 /// This has the same effect as [`MaybeUninit::zeroed().assume_init()`][zeroed].
413 /// It is useful for FFI sometimes, but should generally be avoided.
414 ///
415 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
416 /// some type `T`. For example, the all-zero byte-pattern is not a valid value
417 /// for reference types (`&T` and `&mut T`). Using `zeroed` on such types
418 /// causes immediate [undefined behavior][ub] because [the Rust compiler assumes][inv]
419 /// that there always is a valid value in a variable it considers initialized.
420 ///
421 /// [zeroed]: union.MaybeUninit.html#method.zeroed
422 /// [ub]: ../../reference/behavior-considered-undefined.html
423 /// [inv]: union.MaybeUninit.html#initialization-invariant
424 ///
425 /// # Examples
426 ///
427 /// Correct usage of this function: initializing an integer with zero.
428 ///
429 /// ```
430 /// use std::mem;
431 ///
432 /// let x: i32 = unsafe { mem::zeroed() };
433 /// assert_eq!(0, x);
434 /// ```
435 ///
436 /// *Incorrect* usage of this function: initializing a reference with zero.
437 ///
438 /// ```no_run
439 /// use std::mem;
440 ///
441 /// let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior!
442 /// ```
443 #[inline]
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub unsafe fn zeroed<T>() -> T {
446     intrinsics::panic_if_uninhabited::<T>();
447     intrinsics::init()
448 }
449
450 /// Bypasses Rust's normal memory-initialization checks by pretending to
451 /// produce a value of type `T`, while doing nothing at all.
452 ///
453 /// **This functon is deprecated.** Use [`MaybeUninit<T>`] instead.
454 ///
455 /// The reason for deprecation is that the function basically cannot be used
456 /// correctly: [the Rust compiler assumes][inv] that values are properly initialized.
457 /// As a consequence, calling e.g. `mem::uninitialized::<bool>()` causes immediate
458 /// undefined behavior for returning a `bool` that is not definitely either `true`
459 /// or `false`. Worse, truly uninitialized memory like what gets returned here
460 /// is special in that the compiler knows that it does not have a fixed value.
461 /// This makes it undefined behavior to have uninitialized data in a variable even
462 /// if that variable has an integer type.
463 /// (Notice that the rules around uninitialized integers are not finalized yet, but
464 /// until they are, it is advisable to avoid them.)
465 ///
466 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
467 /// [inv]: union.MaybeUninit.html#initialization-invariant
468 #[inline]
469 #[rustc_deprecated(since = "1.38.0", reason = "use `mem::MaybeUninit` instead")]
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub unsafe fn uninitialized<T>() -> T {
472     intrinsics::panic_if_uninhabited::<T>();
473     intrinsics::uninit()
474 }
475
476 /// Swaps the values at two mutable locations, without deinitializing either one.
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use std::mem;
482 ///
483 /// let mut x = 5;
484 /// let mut y = 42;
485 ///
486 /// mem::swap(&mut x, &mut y);
487 ///
488 /// assert_eq!(42, x);
489 /// assert_eq!(5, y);
490 /// ```
491 #[inline]
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn swap<T>(x: &mut T, y: &mut T) {
494     unsafe {
495         ptr::swap_nonoverlapping_one(x, y);
496     }
497 }
498
499 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
500 ///
501 /// Neither value is dropped.
502 ///
503 /// # Examples
504 ///
505 /// A simple example:
506 ///
507 /// ```
508 /// use std::mem;
509 ///
510 /// let mut v: Vec<i32> = vec![1, 2];
511 ///
512 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
513 /// assert_eq!(vec![1, 2], old_v);
514 /// assert_eq!(vec![3, 4, 5], v);
515 /// ```
516 ///
517 /// `replace` allows consumption of a struct field by replacing it with another value.
518 /// Without `replace` you can run into issues like these:
519 ///
520 /// ```compile_fail,E0507
521 /// struct Buffer<T> { buf: Vec<T> }
522 ///
523 /// impl<T> Buffer<T> {
524 ///     fn get_and_reset(&mut self) -> Vec<T> {
525 ///         // error: cannot move out of dereference of `&mut`-pointer
526 ///         let buf = self.buf;
527 ///         self.buf = Vec::new();
528 ///         buf
529 ///     }
530 /// }
531 /// ```
532 ///
533 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
534 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
535 /// `self`, allowing it to be returned:
536 ///
537 /// ```
538 /// # #![allow(dead_code)]
539 /// use std::mem;
540 ///
541 /// # struct Buffer<T> { buf: Vec<T> }
542 /// impl<T> Buffer<T> {
543 ///     fn get_and_reset(&mut self) -> Vec<T> {
544 ///         mem::replace(&mut self.buf, Vec::new())
545 ///     }
546 /// }
547 /// ```
548 ///
549 /// [`Clone`]: ../../std/clone/trait.Clone.html
550 #[inline]
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
553     swap(dest, &mut src);
554     src
555 }
556
557 /// Disposes of a value.
558 ///
559 /// This does call the argument's implementation of [`Drop`][drop].
560 ///
561 /// This effectively does nothing for types which implement `Copy`, e.g.
562 /// integers. Such values are copied and _then_ moved into the function, so the
563 /// value persists after this function call.
564 ///
565 /// This function is not magic; it is literally defined as
566 ///
567 /// ```
568 /// pub fn drop<T>(_x: T) { }
569 /// ```
570 ///
571 /// Because `_x` is moved into the function, it is automatically dropped before
572 /// the function returns.
573 ///
574 /// [drop]: ../ops/trait.Drop.html
575 ///
576 /// # Examples
577 ///
578 /// Basic usage:
579 ///
580 /// ```
581 /// let v = vec![1, 2, 3];
582 ///
583 /// drop(v); // explicitly drop the vector
584 /// ```
585 ///
586 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
587 /// release a [`RefCell`] borrow:
588 ///
589 /// ```
590 /// use std::cell::RefCell;
591 ///
592 /// let x = RefCell::new(1);
593 ///
594 /// let mut mutable_borrow = x.borrow_mut();
595 /// *mutable_borrow = 1;
596 ///
597 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
598 ///
599 /// let borrow = x.borrow();
600 /// println!("{}", *borrow);
601 /// ```
602 ///
603 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
604 ///
605 /// ```
606 /// #[derive(Copy, Clone)]
607 /// struct Foo(u8);
608 ///
609 /// let x = 1;
610 /// let y = Foo(2);
611 /// drop(x); // a copy of `x` is moved and dropped
612 /// drop(y); // a copy of `y` is moved and dropped
613 ///
614 /// println!("x: {}, y: {}", x, y.0); // still available
615 /// ```
616 ///
617 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
618 /// [`Copy`]: ../../std/marker/trait.Copy.html
619 #[inline]
620 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn drop<T>(_x: T) { }
622
623 /// Interprets `src` as having type `&U`, and then reads `src` without moving
624 /// the contained value.
625 ///
626 /// This function will unsafely assume the pointer `src` is valid for
627 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
628 /// the `&U`. It will also unsafely create a copy of the contained value instead of
629 /// moving out of `src`.
630 ///
631 /// It is not a compile-time error if `T` and `U` have different sizes, but it
632 /// is highly encouraged to only invoke this function where `T` and `U` have the
633 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
634 /// `T`.
635 ///
636 /// [ub]: ../../reference/behavior-considered-undefined.html
637 /// [size_of]: fn.size_of.html
638 ///
639 /// # Examples
640 ///
641 /// ```
642 /// use std::mem;
643 ///
644 /// #[repr(packed)]
645 /// struct Foo {
646 ///     bar: u8,
647 /// }
648 ///
649 /// let foo_slice = [10u8];
650 ///
651 /// unsafe {
652 ///     // Copy the data from 'foo_slice' and treat it as a 'Foo'
653 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
654 ///     assert_eq!(foo_struct.bar, 10);
655 ///
656 ///     // Modify the copied data
657 ///     foo_struct.bar = 20;
658 ///     assert_eq!(foo_struct.bar, 20);
659 /// }
660 ///
661 /// // The contents of 'foo_slice' should not have changed
662 /// assert_eq!(foo_slice, [10]);
663 /// ```
664 #[inline]
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
667     ptr::read_unaligned(src as *const T as *const U)
668 }
669
670 /// Opaque type representing the discriminant of an enum.
671 ///
672 /// See the [`discriminant`] function in this module for more information.
673 ///
674 /// [`discriminant`]: fn.discriminant.html
675 #[stable(feature = "discriminant_value", since = "1.21.0")]
676 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
677
678 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
679
680 #[stable(feature = "discriminant_value", since = "1.21.0")]
681 impl<T> Copy for Discriminant<T> {}
682
683 #[stable(feature = "discriminant_value", since = "1.21.0")]
684 impl<T> clone::Clone for Discriminant<T> {
685     fn clone(&self) -> Self {
686         *self
687     }
688 }
689
690 #[stable(feature = "discriminant_value", since = "1.21.0")]
691 impl<T> cmp::PartialEq for Discriminant<T> {
692     fn eq(&self, rhs: &Self) -> bool {
693         self.0 == rhs.0
694     }
695 }
696
697 #[stable(feature = "discriminant_value", since = "1.21.0")]
698 impl<T> cmp::Eq for Discriminant<T> {}
699
700 #[stable(feature = "discriminant_value", since = "1.21.0")]
701 impl<T> hash::Hash for Discriminant<T> {
702     fn hash<H: hash::Hasher>(&self, state: &mut H) {
703         self.0.hash(state);
704     }
705 }
706
707 #[stable(feature = "discriminant_value", since = "1.21.0")]
708 impl<T> fmt::Debug for Discriminant<T> {
709     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
710         fmt.debug_tuple("Discriminant")
711            .field(&self.0)
712            .finish()
713     }
714 }
715
716 /// Returns a value uniquely identifying the enum variant in `v`.
717 ///
718 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
719 /// return value is unspecified.
720 ///
721 /// # Stability
722 ///
723 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
724 /// of some variant will not change between compilations with the same compiler.
725 ///
726 /// # Examples
727 ///
728 /// This can be used to compare enums that carry data, while disregarding
729 /// the actual data:
730 ///
731 /// ```
732 /// use std::mem;
733 ///
734 /// enum Foo { A(&'static str), B(i32), C(i32) }
735 ///
736 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
737 /// assert!(mem::discriminant(&Foo::B(1))     == mem::discriminant(&Foo::B(2)));
738 /// assert!(mem::discriminant(&Foo::B(3))     != mem::discriminant(&Foo::C(3)));
739 /// ```
740 #[stable(feature = "discriminant_value", since = "1.21.0")]
741 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
742     unsafe {
743         Discriminant(intrinsics::discriminant_value(v), PhantomData)
744     }
745 }
746
747 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
748 ///
749 /// This wrapper is 0-cost.
750 ///
751 /// `ManuallyDrop<T>` is subject to the same layout optimizations as `T`.
752 /// As a consequence, it has *no effect* on the assumptions that the compiler makes
753 /// about all values being initialized at their type.  In particular, initializing
754 /// a `ManuallyDrop<&mut T>` with [`mem::zeroed`] is undefined behavior.
755 /// If you need to handle uninitialized data, use [`MaybeUninit<T>`] instead.
756 ///
757 /// # Examples
758 ///
759 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
760 /// the type:
761 ///
762 /// ```rust
763 /// use std::mem::ManuallyDrop;
764 /// struct Peach;
765 /// struct Banana;
766 /// struct Melon;
767 /// struct FruitBox {
768 ///     // Immediately clear there’s something non-trivial going on with these fields.
769 ///     peach: ManuallyDrop<Peach>,
770 ///     melon: Melon, // Field that’s independent of the other two.
771 ///     banana: ManuallyDrop<Banana>,
772 /// }
773 ///
774 /// impl Drop for FruitBox {
775 ///     fn drop(&mut self) {
776 ///         unsafe {
777 ///             // Explicit ordering in which field destructors are run specified in the intuitive
778 ///             // location â€“ the destructor of the structure containing the fields.
779 ///             // Moreover, one can now reorder fields within the struct however much they want.
780 ///             ManuallyDrop::drop(&mut self.peach);
781 ///             ManuallyDrop::drop(&mut self.banana);
782 ///         }
783 ///         // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
784 ///         // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
785 ///     }
786 /// }
787 /// ```
788 ///
789 /// [`mem::zeroed`]: fn.zeroed.html
790 /// [`MaybeUninit<T>`]: union.MaybeUninit.html
791 #[stable(feature = "manually_drop", since = "1.20.0")]
792 #[lang = "manually_drop"]
793 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
794 #[repr(transparent)]
795 pub struct ManuallyDrop<T: ?Sized> {
796     value: T,
797 }
798
799 impl<T> ManuallyDrop<T> {
800     /// Wrap a value to be manually dropped.
801     ///
802     /// # Examples
803     ///
804     /// ```rust
805     /// use std::mem::ManuallyDrop;
806     /// ManuallyDrop::new(Box::new(()));
807     /// ```
808     #[stable(feature = "manually_drop", since = "1.20.0")]
809     #[inline(always)]
810     pub const fn new(value: T) -> ManuallyDrop<T> {
811         ManuallyDrop { value }
812     }
813
814     /// Extracts the value from the `ManuallyDrop` container.
815     ///
816     /// This allows the value to be dropped again.
817     ///
818     /// # Examples
819     ///
820     /// ```rust
821     /// use std::mem::ManuallyDrop;
822     /// let x = ManuallyDrop::new(Box::new(()));
823     /// let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`.
824     /// ```
825     #[stable(feature = "manually_drop", since = "1.20.0")]
826     #[inline(always)]
827     pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
828         slot.value
829     }
830
831     /// Takes the contained value out.
832     ///
833     /// This method is primarily intended for moving out values in drop.
834     /// Instead of using [`ManuallyDrop::drop`] to manually drop the value,
835     /// you can use this method to take the value and use it however desired.
836     /// `Drop` will be invoked on the returned value following normal end-of-scope rules.
837     ///
838     /// If you have ownership of the container, you can use [`ManuallyDrop::into_inner`] instead.
839     ///
840     /// # Safety
841     ///
842     /// This function semantically moves out the contained value without preventing further usage.
843     /// It is up to the user of this method to ensure that this container is not used again.
844     ///
845     /// [`ManuallyDrop::drop`]: #method.drop
846     /// [`ManuallyDrop::into_inner`]: #method.into_inner
847     #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"]
848     #[unstable(feature = "manually_drop_take", issue = "55422")]
849     #[inline]
850     pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
851         ManuallyDrop::into_inner(ptr::read(slot))
852     }
853 }
854
855 impl<T: ?Sized> ManuallyDrop<T> {
856     /// Manually drops the contained value.
857     ///
858     /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead.
859     ///
860     /// # Safety
861     ///
862     /// This function runs the destructor of the contained value and thus the wrapped value
863     /// now represents uninitialized data. It is up to the user of this method to ensure the
864     /// uninitialized data is not actually used.
865     ///
866     /// [`ManuallyDrop::into_inner`]: #method.into_inner
867     #[stable(feature = "manually_drop", since = "1.20.0")]
868     #[inline]
869     pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
870         ptr::drop_in_place(&mut slot.value)
871     }
872 }
873
874 #[stable(feature = "manually_drop", since = "1.20.0")]
875 impl<T: ?Sized> Deref for ManuallyDrop<T> {
876     type Target = T;
877     #[inline(always)]
878     fn deref(&self) -> &T {
879         &self.value
880     }
881 }
882
883 #[stable(feature = "manually_drop", since = "1.20.0")]
884 impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
885     #[inline(always)]
886     fn deref_mut(&mut self) -> &mut T {
887         &mut self.value
888     }
889 }
890
891 /// A wrapper type to construct uninitialized instances of `T`.
892 ///
893 /// # Initialization invariant
894 ///
895 /// The compiler, in general, assumes that variables are properly initialized
896 /// at their respective type. For example, a variable of reference type must
897 /// be aligned and non-NULL. This is an invariant that must *always* be upheld,
898 /// even in unsafe code. As a consequence, zero-initializing a variable of reference
899 /// type causes instantaneous [undefined behavior][ub], no matter whether that reference
900 /// ever gets used to access memory:
901 ///
902 /// ```rust,no_run
903 /// use std::mem::{self, MaybeUninit};
904 ///
905 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior!
906 /// // The equivalent code with `MaybeUninit<&i32>`:
907 /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior!
908 /// ```
909 ///
910 /// This is exploited by the compiler for various optimizations, such as eliding
911 /// run-time checks and optimizing `enum` layout.
912 ///
913 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must
914 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior:
915 ///
916 /// ```rust,no_run
917 /// use std::mem::{self, MaybeUninit};
918 ///
919 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior!
920 /// // The equivalent code with `MaybeUninit<bool>`:
921 /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior!
922 /// ```
923 ///
924 /// Moreover, uninitialized memory is special in that the compiler knows that
925 /// it does not have a fixed value. This makes it undefined behavior to have
926 /// uninitialized data in a variable even if that variable has an integer type,
927 /// which otherwise can hold any *fixed* bit pattern:
928 ///
929 /// ```rust,no_run
930 /// use std::mem::{self, MaybeUninit};
931 ///
932 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior!
933 /// // The equivalent code with `MaybeUninit<i32>`:
934 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior!
935 /// ```
936 /// (Notice that the rules around uninitialized integers are not finalized yet, but
937 /// until they are, it is advisable to avoid them.)
938 ///
939 /// On top of that, remember that most types have additional invariants beyond merely
940 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
941 /// is considered initialized because the only requirement the compiler knows about it
942 /// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
943 /// *immediate* undefined behavior, but will cause undefined behavior with most
944 /// safe operations (including dropping it).
945 ///
946 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html
947 ///
948 /// # Examples
949 ///
950 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data.
951 /// It is a signal to the compiler indicating that the data here might *not*
952 /// be initialized:
953 ///
954 /// ```rust
955 /// use std::mem::MaybeUninit;
956 ///
957 /// // Create an explicitly uninitialized reference. The compiler knows that data inside
958 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB:
959 /// let mut x = MaybeUninit::<&i32>::uninit();
960 /// // Set it to a valid value.
961 /// unsafe { x.as_mut_ptr().write(&0); }
962 /// // Extract the initialized data -- this is only allowed *after* properly
963 /// // initializing `x`!
964 /// let x = unsafe { x.assume_init() };
965 /// ```
966 ///
967 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
968 ///
969 /// You can think of `MaybeUninit<T>` and being a bit like `Option<T>` but without
970 /// any of the run-time tracking and without any of the safety checks.
971 ///
972 /// ## out-pointers
973 ///
974 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
975 /// from a function, pass it a pointer to some (uninitialized) memory to put the
976 /// result into. This can be useful when it is important for the caller to control
977 /// how the memory the result is stored in gets allocated, and you want to avoid
978 /// unnecessary moves.
979 ///
980 /// ```
981 /// use std::mem::MaybeUninit;
982 ///
983 /// unsafe fn make_vec(out: *mut Vec<i32>) {
984 ///     // `write` does not drop the old contents, which is important.
985 ///     out.write(vec![1, 2, 3]);
986 /// }
987 ///
988 /// let mut v = MaybeUninit::uninit();
989 /// unsafe { make_vec(v.as_mut_ptr()); }
990 /// // Now we know `v` is initialized! This also makes sure the vector gets
991 /// // properly dropped.
992 /// let v = unsafe { v.assume_init() };
993 /// assert_eq!(&v, &[1, 2, 3]);
994 /// ```
995 ///
996 /// ## Initializing an array element-by-element
997 ///
998 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
999 ///
1000 /// ```
1001 /// use std::mem::{self, MaybeUninit};
1002 /// use std::ptr;
1003 ///
1004 /// let data = {
1005 ///     // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
1006 ///     // safe because the type we are claiming to have initialized here is a
1007 ///     // bunch of `MaybeUninit`s, which do not require initialization.
1008 ///     let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe {
1009 ///         MaybeUninit::uninit().assume_init()
1010 ///     };
1011 ///
1012 ///     // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
1013 ///     // we have a memory leak, but there is no memory safety issue.
1014 ///     for elem in &mut data[..] {
1015 ///         unsafe { ptr::write(elem.as_mut_ptr(), vec![42]); }
1016 ///     }
1017 ///
1018 ///     // Everything is initialized. Transmute the array to the
1019 ///     // initialized type.
1020 ///     unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
1021 /// };
1022 ///
1023 /// assert_eq!(&data[0], &[42]);
1024 /// ```
1025 ///
1026 /// You can also work with partially initialized arrays, which could
1027 /// be found in low-level datastructures.
1028 ///
1029 /// ```
1030 /// use std::mem::MaybeUninit;
1031 /// use std::ptr;
1032 ///
1033 /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
1034 /// // safe because the type we are claiming to have initialized here is a
1035 /// // bunch of `MaybeUninit`s, which do not require initialization.
1036 /// let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() };
1037 /// // Count the number of elements we have assigned.
1038 /// let mut data_len: usize = 0;
1039 ///
1040 /// for elem in &mut data[0..500] {
1041 ///     unsafe { ptr::write(elem.as_mut_ptr(), String::from("hello")); }
1042 ///     data_len += 1;
1043 /// }
1044 ///
1045 /// // For each item in the array, drop if we allocated it.
1046 /// for elem in &mut data[0..data_len] {
1047 ///     unsafe { ptr::drop_in_place(elem.as_mut_ptr()); }
1048 /// }
1049 /// ```
1050 ///
1051 /// ## Initializing a struct field-by-field
1052 ///
1053 /// There is currently no supported way to create a raw pointer or reference
1054 /// to a field of a struct inside `MaybeUninit<Struct>`. That means it is not possible
1055 /// to create a struct by calling `MaybeUninit::uninit::<Struct>()` and then writing
1056 /// to its fields.
1057 ///
1058 /// [ub]: ../../reference/behavior-considered-undefined.html
1059 ///
1060 /// # Layout
1061 ///
1062 /// `MaybeUninit<T>` is guaranteed to have the same size and alignment as `T`:
1063 ///
1064 /// ```rust
1065 /// use std::mem::{MaybeUninit, size_of, align_of};
1066 /// assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>());
1067 /// assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>());
1068 /// ```
1069 ///
1070 /// However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same
1071 /// layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as
1072 /// a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit
1073 /// value is valid for a `MaybeUninit<T>` the compiler can't apply non-zero/niche-filling
1074 /// optimizations, potentially resulting in a larger size:
1075 ///
1076 /// ```rust
1077 /// # use std::mem::{MaybeUninit, size_of};
1078 /// assert_eq!(size_of::<Option<bool>>(), 1);
1079 /// assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2);
1080 /// ```
1081 #[allow(missing_debug_implementations)]
1082 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1083 #[derive(Copy)]
1084 pub union MaybeUninit<T> {
1085     uninit: (),
1086     value: ManuallyDrop<T>,
1087 }
1088
1089 #[stable(feature = "maybe_uninit", since = "1.36.0")]
1090 impl<T: Copy> Clone for MaybeUninit<T> {
1091     #[inline(always)]
1092     fn clone(&self) -> Self {
1093         // Not calling `T::clone()`, we cannot know if we are initialized enough for that.
1094         *self
1095     }
1096 }
1097
1098 impl<T> MaybeUninit<T> {
1099     /// Creates a new `MaybeUninit<T>` initialized with the given value.
1100     /// It is safe to call [`assume_init`] on the return value of this function.
1101     ///
1102     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1103     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1104     ///
1105     /// [`assume_init`]: #method.assume_init
1106     #[stable(feature = "maybe_uninit", since = "1.36.0")]
1107     #[inline(always)]
1108     pub const fn new(val: T) -> MaybeUninit<T> {
1109         MaybeUninit { value: ManuallyDrop::new(val) }
1110     }
1111
1112     /// Creates a new `MaybeUninit<T>` in an uninitialized state.
1113     ///
1114     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1115     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1116     ///
1117     /// See the [type-level documentation][type] for some examples.
1118     ///
1119     /// [type]: union.MaybeUninit.html
1120     #[stable(feature = "maybe_uninit", since = "1.36.0")]
1121     #[inline(always)]
1122     pub const fn uninit() -> MaybeUninit<T> {
1123         MaybeUninit { uninit: () }
1124     }
1125
1126     /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being
1127     /// filled with `0` bytes. It depends on `T` whether that already makes for
1128     /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
1129     /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
1130     /// be null.
1131     ///
1132     /// Note that dropping a `MaybeUninit<T>` will never call `T`'s drop code.
1133     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1134     ///
1135     /// # Example
1136     ///
1137     /// Correct usage of this function: initializing a struct with zero, where all
1138     /// fields of the struct can hold the bit-pattern 0 as a valid value.
1139     ///
1140     /// ```rust
1141     /// use std::mem::MaybeUninit;
1142     ///
1143     /// let x = MaybeUninit::<(u8, bool)>::zeroed();
1144     /// let x = unsafe { x.assume_init() };
1145     /// assert_eq!(x, (0, false));
1146     /// ```
1147     ///
1148     /// *Incorrect* usage of this function: initializing a struct with zero, where some fields
1149     /// cannot hold 0 as a valid value.
1150     ///
1151     /// ```rust,no_run
1152     /// use std::mem::MaybeUninit;
1153     ///
1154     /// enum NotZero { One = 1, Two = 2 };
1155     ///
1156     /// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
1157     /// let x = unsafe { x.assume_init() };
1158     /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant.
1159     /// // This is undefined behavior.
1160     /// ```
1161     #[stable(feature = "maybe_uninit", since = "1.36.0")]
1162     #[inline]
1163     pub fn zeroed() -> MaybeUninit<T> {
1164         let mut u = MaybeUninit::<T>::uninit();
1165         unsafe {
1166             u.as_mut_ptr().write_bytes(0u8, 1);
1167         }
1168         u
1169     }
1170
1171     /// Sets the value of the `MaybeUninit<T>`. This overwrites any previous value
1172     /// without dropping it, so be careful not to use this twice unless you want to
1173     /// skip running the destructor. For your convenience, this also returns a mutable
1174     /// reference to the (now safely initialized) contents of `self`.
1175     #[unstable(feature = "maybe_uninit_extra", issue = "53491")]
1176     #[inline(always)]
1177     pub fn write(&mut self, val: T) -> &mut T {
1178         unsafe {
1179             self.value = ManuallyDrop::new(val);
1180             self.get_mut()
1181         }
1182     }
1183
1184     /// Gets a pointer to the contained value. Reading from this pointer or turning it
1185     /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
1186     /// Writing to memory that this pointer (non-transitively) points to is undefined behavior
1187     /// (except inside an `UnsafeCell<T>`).
1188     ///
1189     /// # Examples
1190     ///
1191     /// Correct usage of this method:
1192     ///
1193     /// ```rust
1194     /// use std::mem::MaybeUninit;
1195     ///
1196     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
1197     /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
1198     /// // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it.
1199     /// let x_vec = unsafe { &*x.as_ptr() };
1200     /// assert_eq!(x_vec.len(), 3);
1201     /// ```
1202     ///
1203     /// *Incorrect* usage of this method:
1204     ///
1205     /// ```rust,no_run
1206     /// use std::mem::MaybeUninit;
1207     ///
1208     /// let x = MaybeUninit::<Vec<u32>>::uninit();
1209     /// let x_vec = unsafe { &*x.as_ptr() };
1210     /// // We have created a reference to an uninitialized vector! This is undefined behavior.
1211     /// ```
1212     ///
1213     /// (Notice that the rules around references to uninitialized data are not finalized yet, but
1214     /// until they are, it is advisable to avoid them.)
1215     #[stable(feature = "maybe_uninit", since = "1.36.0")]
1216     #[inline(always)]
1217     pub fn as_ptr(&self) -> *const T {
1218         unsafe { &*self.value as *const T }
1219     }
1220
1221     /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it
1222     /// into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized.
1223     ///
1224     /// # Examples
1225     ///
1226     /// Correct usage of this method:
1227     ///
1228     /// ```rust
1229     /// use std::mem::MaybeUninit;
1230     ///
1231     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
1232     /// unsafe { x.as_mut_ptr().write(vec![0,1,2]); }
1233     /// // Create a reference into the `MaybeUninit<Vec<u32>>`.
1234     /// // This is okay because we initialized it.
1235     /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1236     /// x_vec.push(3);
1237     /// assert_eq!(x_vec.len(), 4);
1238     /// ```
1239     ///
1240     /// *Incorrect* usage of this method:
1241     ///
1242     /// ```rust,no_run
1243     /// use std::mem::MaybeUninit;
1244     ///
1245     /// let mut x = MaybeUninit::<Vec<u32>>::uninit();
1246     /// let x_vec = unsafe { &mut *x.as_mut_ptr() };
1247     /// // We have created a reference to an uninitialized vector! This is undefined behavior.
1248     /// ```
1249     ///
1250     /// (Notice that the rules around references to uninitialized data are not finalized yet, but
1251     /// until they are, it is advisable to avoid them.)
1252     #[stable(feature = "maybe_uninit", since = "1.36.0")]
1253     #[inline(always)]
1254     pub fn as_mut_ptr(&mut self) -> *mut T {
1255         unsafe { &mut *self.value as *mut T }
1256     }
1257
1258     /// Extracts the value from the `MaybeUninit<T>` container. This is a great way
1259     /// to ensure that the data will get dropped, because the resulting `T` is
1260     /// subject to the usual drop handling.
1261     ///
1262     /// # Safety
1263     ///
1264     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1265     /// state. Calling this when the content is not yet fully initialized causes immediate undefined
1266     /// behavior. The [type-level documentation][inv] contains more information about
1267     /// this initialization invariant.
1268     ///
1269     /// [inv]: #initialization-invariant
1270     ///
1271     /// # Examples
1272     ///
1273     /// Correct usage of this method:
1274     ///
1275     /// ```rust
1276     /// use std::mem::MaybeUninit;
1277     ///
1278     /// let mut x = MaybeUninit::<bool>::uninit();
1279     /// unsafe { x.as_mut_ptr().write(true); }
1280     /// let x_init = unsafe { x.assume_init() };
1281     /// assert_eq!(x_init, true);
1282     /// ```
1283     ///
1284     /// *Incorrect* usage of this method:
1285     ///
1286     /// ```rust,no_run
1287     /// use std::mem::MaybeUninit;
1288     ///
1289     /// let x = MaybeUninit::<Vec<u32>>::uninit();
1290     /// let x_init = unsafe { x.assume_init() };
1291     /// // `x` had not been initialized yet, so this last line caused undefined behavior.
1292     /// ```
1293     #[stable(feature = "maybe_uninit", since = "1.36.0")]
1294     #[inline(always)]
1295     pub unsafe fn assume_init(self) -> T {
1296         intrinsics::panic_if_uninhabited::<T>();
1297         ManuallyDrop::into_inner(self.value)
1298     }
1299
1300     /// Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject
1301     /// to the usual drop handling.
1302     ///
1303     /// Whenever possible, it is preferrable to use [`assume_init`] instead, which
1304     /// prevents duplicating the content of the `MaybeUninit<T>`.
1305     ///
1306     /// # Safety
1307     ///
1308     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1309     /// state. Calling this when the content is not yet fully initialized causes undefined
1310     /// behavior. The [type-level documentation][inv] contains more information about
1311     /// this initialization invariant.
1312     ///
1313     /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit<T>`. When using
1314     /// multiple copies of the data (by calling `read` multiple times, or first
1315     /// calling `read` and then [`assume_init`]), it is your responsibility
1316     /// to ensure that that data may indeed be duplicated.
1317     ///
1318     /// [inv]: #initialization-invariant
1319     /// [`assume_init`]: #method.assume_init
1320     ///
1321     /// # Examples
1322     ///
1323     /// Correct usage of this method:
1324     ///
1325     /// ```rust
1326     /// #![feature(maybe_uninit_extra)]
1327     /// use std::mem::MaybeUninit;
1328     ///
1329     /// let mut x = MaybeUninit::<u32>::uninit();
1330     /// x.write(13);
1331     /// let x1 = unsafe { x.read() };
1332     /// // `u32` is `Copy`, so we may read multiple times.
1333     /// let x2 = unsafe { x.read() };
1334     /// assert_eq!(x1, x2);
1335     ///
1336     /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
1337     /// x.write(None);
1338     /// let x1 = unsafe { x.read() };
1339     /// // Duplicating a `None` value is okay, so we may read multiple times.
1340     /// let x2 = unsafe { x.read() };
1341     /// assert_eq!(x1, x2);
1342     /// ```
1343     ///
1344     /// *Incorrect* usage of this method:
1345     ///
1346     /// ```rust,no_run
1347     /// #![feature(maybe_uninit_extra)]
1348     /// use std::mem::MaybeUninit;
1349     ///
1350     /// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
1351     /// x.write(Some(vec![0,1,2]));
1352     /// let x1 = unsafe { x.read() };
1353     /// let x2 = unsafe { x.read() };
1354     /// // We now created two copies of the same vector, leading to a double-free when
1355     /// // they both get dropped!
1356     /// ```
1357     #[unstable(feature = "maybe_uninit_extra", issue = "53491")]
1358     #[inline(always)]
1359     pub unsafe fn read(&self) -> T {
1360         intrinsics::panic_if_uninhabited::<T>();
1361         self.as_ptr().read()
1362     }
1363
1364     /// Gets a reference to the contained value.
1365     ///
1366     /// # Safety
1367     ///
1368     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1369     /// state. Calling this when the content is not yet fully initialized causes undefined
1370     /// behavior.
1371     #[unstable(feature = "maybe_uninit_ref", issue = "53491")]
1372     #[inline(always)]
1373     pub unsafe fn get_ref(&self) -> &T {
1374         &*self.value
1375     }
1376
1377     /// Gets a mutable reference to the contained value.
1378     ///
1379     /// # Safety
1380     ///
1381     /// It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized
1382     /// state. Calling this when the content is not yet fully initialized causes undefined
1383     /// behavior.
1384     // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
1385     // to uninitialized data (e.g., in `libcore/fmt/float.rs`).  We should make
1386     // a final decision about the rules before stabilization.
1387     #[unstable(feature = "maybe_uninit_ref", issue = "53491")]
1388     #[inline(always)]
1389     pub unsafe fn get_mut(&mut self) -> &mut T {
1390         &mut *self.value
1391     }
1392
1393     /// Gets a pointer to the first element of the array.
1394     #[unstable(feature = "maybe_uninit_slice", issue = "53491")]
1395     #[inline(always)]
1396     pub fn first_ptr(this: &[MaybeUninit<T>]) -> *const T {
1397         this as *const [MaybeUninit<T>] as *const T
1398     }
1399
1400     /// Gets a mutable pointer to the first element of the array.
1401     #[unstable(feature = "maybe_uninit_slice", issue = "53491")]
1402     #[inline(always)]
1403     pub fn first_ptr_mut(this: &mut [MaybeUninit<T>]) -> *mut T {
1404         this as *mut [MaybeUninit<T>] as *mut T
1405     }
1406 }