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