]> git.lizzy.rs Git - rust.git/blob - src/libcore/mem.rs
Convert old doc links to current edition
[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 clone;
9 use cmp;
10 use fmt;
11 use hash;
12 use intrinsics;
13 use marker::{Copy, PhantomData, Sized};
14 use ptr;
15 use ops::{Deref, DerefMut};
16
17 #[stable(feature = "rust1", since = "1.0.0")]
18 pub use intrinsics::transmute;
19
20 /// Takes ownership and "forgets" about the value **without running its destructor**.
21 ///
22 /// Any resources the value manages, such as heap memory or a file handle, will linger
23 /// forever in an unreachable state. However, it does not guarantee that pointers
24 /// to this memory will remain valid.
25 ///
26 /// * If you want to leak memory, see [`Box::leak`][leak].
27 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`][into_raw].
28 /// * If you want to dispose of a value properly, running its destructor, see
29 /// [`mem::drop`][drop].
30 ///
31 /// # Safety
32 ///
33 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
34 /// do not include a guarantee that destructors will always run. For example,
35 /// a program can create a reference cycle using [`Rc`][rc], or call
36 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing
37 /// `mem::forget` from safe code does not fundamentally change Rust's safety
38 /// guarantees.
39 ///
40 /// That said, leaking resources such as memory or I/O objects is usually undesirable,
41 /// so `forget` is only recommended for specialized use cases like those shown below.
42 ///
43 /// Because forgetting a value is allowed, any `unsafe` code you write must
44 /// allow for this possibility. You cannot return a value and expect that the
45 /// caller will necessarily run the value's destructor.
46 ///
47 /// [rc]: ../../std/rc/struct.Rc.html
48 /// [exit]: ../../std/process/fn.exit.html
49 ///
50 /// # Examples
51 ///
52 /// Leak an I/O object, never closing the file:
53 ///
54 /// ```no_run
55 /// use std::mem;
56 /// use std::fs::File;
57 ///
58 /// let file = File::open("foo.txt").unwrap();
59 /// mem::forget(file);
60 /// ```
61 ///
62 /// The practical use cases for `forget` are rather specialized and mainly come
63 /// up in unsafe or FFI code.
64 ///
65 /// ## Use case 1
66 ///
67 /// You have created an uninitialized value using [`mem::uninitialized`][uninit].
68 /// You must either initialize or `forget` it on every computation path before
69 /// Rust drops it automatically, like at the end of a scope or after a panic.
70 /// Running the destructor on an uninitialized value would be [undefined behavior][ub].
71 ///
72 /// ```
73 /// use std::mem;
74 /// use std::ptr;
75 ///
76 /// # let some_condition = false;
77 /// unsafe {
78 ///     let mut uninit_vec: Vec<u32> = mem::uninitialized();
79 ///
80 ///     if some_condition {
81 ///         // Initialize the variable.
82 ///         ptr::write(&mut uninit_vec, Vec::new());
83 ///     } else {
84 ///         // Forget the uninitialized value so its destructor doesn't run.
85 ///         mem::forget(uninit_vec);
86 ///     }
87 /// }
88 /// ```
89 ///
90 /// ## Use case 2
91 ///
92 /// You have duplicated the bytes making up a value, without doing a proper
93 /// [`Clone`][clone]. You need the value's destructor to run only once,
94 /// because a double `free` is undefined behavior.
95 ///
96 /// An example is a possible implementation of [`mem::swap`][swap]:
97 ///
98 /// ```
99 /// use std::mem;
100 /// use std::ptr;
101 ///
102 /// # #[allow(dead_code)]
103 /// fn swap<T>(x: &mut T, y: &mut T) {
104 ///     unsafe {
105 ///         // Give ourselves some scratch space to work with
106 ///         let mut t: T = mem::uninitialized();
107 ///
108 ///         // Perform the swap, `&mut` pointers never alias
109 ///         ptr::copy_nonoverlapping(&*x, &mut t, 1);
110 ///         ptr::copy_nonoverlapping(&*y, x, 1);
111 ///         ptr::copy_nonoverlapping(&t, y, 1);
112 ///
113 ///         // y and t now point to the same thing, but we need to completely
114 ///         // forget `t` because we do not want to run the destructor for `T`
115 ///         // on its value, which is still owned somewhere outside this function.
116 ///         mem::forget(t);
117 ///     }
118 /// }
119 /// ```
120 ///
121 /// [drop]: fn.drop.html
122 /// [uninit]: fn.uninitialized.html
123 /// [clone]: ../clone/trait.Clone.html
124 /// [swap]: fn.swap.html
125 /// [box]: ../../std/boxed/struct.Box.html
126 /// [leak]: ../../std/boxed/struct.Box.html#method.leak
127 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
128 /// [ub]: ../../reference/behavior-considered-undefined.html
129 #[inline]
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub fn forget<T>(t: T) {
132     ManuallyDrop::new(t);
133 }
134
135 /// Like [`forget`], but also accepts unsized values.
136 ///
137 /// This function is just a shim intended to be removed when the `unsized_locals` feature gets
138 /// stabilized.
139 ///
140 /// [`forget`]: fn.forget.html
141 #[inline]
142 #[unstable(feature = "forget_unsized", issue = "0")]
143 pub fn forget_unsized<T: ?Sized>(t: T) {
144     unsafe { intrinsics::forget(t) }
145 }
146
147 /// Returns the size of a type in bytes.
148 ///
149 /// More specifically, this is the offset in bytes between successive elements
150 /// in an array with that item type including alignment padding. Thus, for any
151 /// type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`.
152 ///
153 /// In general, the size of a type is not stable across compilations, but
154 /// specific types such as primitives are.
155 ///
156 /// The following table gives the size for primitives.
157 ///
158 /// Type | size_of::\<Type>()
159 /// ---- | ---------------
160 /// () | 0
161 /// bool | 1
162 /// u8 | 1
163 /// u16 | 2
164 /// u32 | 4
165 /// u64 | 8
166 /// u128 | 16
167 /// i8 | 1
168 /// i16 | 2
169 /// i32 | 4
170 /// i64 | 8
171 /// i128 | 16
172 /// f32 | 4
173 /// f64 | 8
174 /// char | 4
175 ///
176 /// Furthermore, `usize` and `isize` have the same size.
177 ///
178 /// The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have
179 /// the same size. If `T` is Sized, all of those types have the same size as `usize`.
180 ///
181 /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T`
182 /// have the same size. Likewise for `*const T` and `*mut T`.
183 ///
184 /// # Size of `#[repr(C)]` items
185 ///
186 /// The `C` representation for items has a defined layout. With this layout,
187 /// the size of items is also stable as long as all fields have a stable size.
188 ///
189 /// ## Size of Structs
190 ///
191 /// For `structs`, the size is determined by the following algorithm.
192 ///
193 /// For each field in the struct ordered by declaration order:
194 ///
195 /// 1. Add the size of the field.
196 /// 2. Round up the current size to the nearest multiple of the next field's [alignment].
197 ///
198 /// Finally, round the size of the struct to the nearest multiple of its [alignment].
199 /// The alignment of the struct is usually the largest alignment of all its
200 /// fields; this can be changed with the use of `repr(align(N))`.
201 ///
202 /// Unlike `C`, zero sized structs are not rounded up to one byte in size.
203 ///
204 /// ## Size of Enums
205 ///
206 /// Enums that carry no data other than the discriminant have the same size as C enums
207 /// on the platform they are compiled for.
208 ///
209 /// ## Size of Unions
210 ///
211 /// The size of a union is the size of its largest field.
212 ///
213 /// Unlike `C`, zero sized unions are not rounded up to one byte in size.
214 ///
215 /// # Examples
216 ///
217 /// ```
218 /// use std::mem;
219 ///
220 /// // Some primitives
221 /// assert_eq!(4, mem::size_of::<i32>());
222 /// assert_eq!(8, mem::size_of::<f64>());
223 /// assert_eq!(0, mem::size_of::<()>());
224 ///
225 /// // Some arrays
226 /// assert_eq!(8, mem::size_of::<[i32; 2]>());
227 /// assert_eq!(12, mem::size_of::<[i32; 3]>());
228 /// assert_eq!(0, mem::size_of::<[i32; 0]>());
229 ///
230 ///
231 /// // Pointer size equality
232 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
233 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
234 /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
235 /// assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());
236 /// ```
237 ///
238 /// Using `#[repr(C)]`.
239 ///
240 /// ```
241 /// use std::mem;
242 ///
243 /// #[repr(C)]
244 /// struct FieldStruct {
245 ///     first: u8,
246 ///     second: u16,
247 ///     third: u8
248 /// }
249 ///
250 /// // The size of the first field is 1, so add 1 to the size. Size is 1.
251 /// // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
252 /// // The size of the second field is 2, so add 2 to the size. Size is 4.
253 /// // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
254 /// // The size of the third field is 1, so add 1 to the size. Size is 5.
255 /// // Finally, the alignment of the struct is 2 (because the largest alignment amongst its
256 /// // fields is 2), so add 1 to the size for padding. Size is 6.
257 /// assert_eq!(6, mem::size_of::<FieldStruct>());
258 ///
259 /// #[repr(C)]
260 /// struct TupleStruct(u8, u16, u8);
261 ///
262 /// // Tuple structs follow the same rules.
263 /// assert_eq!(6, mem::size_of::<TupleStruct>());
264 ///
265 /// // Note that reordering the fields can lower the size. We can remove both padding bytes
266 /// // by putting `third` before `second`.
267 /// #[repr(C)]
268 /// struct FieldStructOptimized {
269 ///     first: u8,
270 ///     third: u8,
271 ///     second: u16
272 /// }
273 ///
274 /// assert_eq!(4, mem::size_of::<FieldStructOptimized>());
275 ///
276 /// // Union size is the size of the largest field.
277 /// #[repr(C)]
278 /// union ExampleUnion {
279 ///     smaller: u8,
280 ///     larger: u16
281 /// }
282 ///
283 /// assert_eq!(2, mem::size_of::<ExampleUnion>());
284 /// ```
285 ///
286 /// [alignment]: ./fn.align_of.html
287 #[inline]
288 #[stable(feature = "rust1", since = "1.0.0")]
289 #[rustc_promotable]
290 pub const fn size_of<T>() -> usize {
291     intrinsics::size_of::<T>()
292 }
293
294 /// Returns the size of the pointed-to value in bytes.
295 ///
296 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
297 /// statically known size, e.g., a slice [`[T]`][slice] or a [trait object],
298 /// then `size_of_val` can be used to get the dynamically-known size.
299 ///
300 /// [slice]: ../../std/primitive.slice.html
301 /// [trait object]: ../../book/ch17-02-trait-objects.html
302 ///
303 /// # Examples
304 ///
305 /// ```
306 /// use std::mem;
307 ///
308 /// assert_eq!(4, mem::size_of_val(&5i32));
309 ///
310 /// let x: [u8; 13] = [0; 13];
311 /// let y: &[u8] = &x;
312 /// assert_eq!(13, mem::size_of_val(y));
313 /// ```
314 #[inline]
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
317     unsafe { intrinsics::size_of_val(val) }
318 }
319
320 /// Returns the [ABI]-required minimum alignment of a type.
321 ///
322 /// Every reference to a value of the type `T` must be a multiple of this number.
323 ///
324 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
325 ///
326 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// # #![allow(deprecated)]
332 /// use std::mem;
333 ///
334 /// assert_eq!(4, mem::min_align_of::<i32>());
335 /// ```
336 #[inline]
337 #[stable(feature = "rust1", since = "1.0.0")]
338 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
339 pub fn min_align_of<T>() -> usize {
340     intrinsics::min_align_of::<T>()
341 }
342
343 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
344 ///
345 /// Every reference to a value of the type `T` must be a multiple of this number.
346 ///
347 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
348 ///
349 /// # Examples
350 ///
351 /// ```
352 /// # #![allow(deprecated)]
353 /// use std::mem;
354 ///
355 /// assert_eq!(4, mem::min_align_of_val(&5i32));
356 /// ```
357 #[inline]
358 #[stable(feature = "rust1", since = "1.0.0")]
359 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
360 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
361     unsafe { intrinsics::min_align_of_val(val) }
362 }
363
364 /// Returns the [ABI]-required minimum alignment of a type.
365 ///
366 /// Every reference to a value of the type `T` must be a multiple of this number.
367 ///
368 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
369 ///
370 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
371 ///
372 /// # Examples
373 ///
374 /// ```
375 /// use std::mem;
376 ///
377 /// assert_eq!(4, mem::align_of::<i32>());
378 /// ```
379 #[inline]
380 #[stable(feature = "rust1", since = "1.0.0")]
381 #[rustc_promotable]
382 pub const fn align_of<T>() -> usize {
383     intrinsics::min_align_of::<T>()
384 }
385
386 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
387 ///
388 /// Every reference to a value of the type `T` must be a multiple of this number.
389 ///
390 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
391 ///
392 /// # Examples
393 ///
394 /// ```
395 /// use std::mem;
396 ///
397 /// assert_eq!(4, mem::align_of_val(&5i32));
398 /// ```
399 #[inline]
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
402     unsafe { intrinsics::min_align_of_val(val) }
403 }
404
405 /// Returns whether dropping values of type `T` matters.
406 ///
407 /// This is purely an optimization hint, and may be implemented conservatively:
408 /// it may return `true` for types that don't actually need to be dropped.
409 /// As such always returning `true` would be a valid implementation of
410 /// this function. However if this function actually returns `false`, then you
411 /// can be certain dropping `T` has no side effect.
412 ///
413 /// Low level implementations of things like collections, which need to manually
414 /// drop their data, should use this function to avoid unnecessarily
415 /// trying to drop all their contents when they are destroyed. This might not
416 /// make a difference in release builds (where a loop that has no side-effects
417 /// is easily detected and eliminated), but is often a big win for debug builds.
418 ///
419 /// Note that `ptr::drop_in_place` already performs this check, so if your workload
420 /// can be reduced to some small number of drop_in_place calls, using this is
421 /// unnecessary. In particular note that you can drop_in_place a slice, and that
422 /// will do a single needs_drop check for all the values.
423 ///
424 /// Types like Vec therefore just `drop_in_place(&mut self[..])` without using
425 /// needs_drop explicitly. Types like HashMap, on the other hand, have to drop
426 /// values one at a time and should use this API.
427 ///
428 ///
429 /// # Examples
430 ///
431 /// Here's an example of how a collection might make use of needs_drop:
432 ///
433 /// ```
434 /// use std::{mem, ptr};
435 ///
436 /// pub struct MyCollection<T> {
437 /// #   data: [T; 1],
438 ///     /* ... */
439 /// }
440 /// # impl<T> MyCollection<T> {
441 /// #   fn iter_mut(&mut self) -> &mut [T] { &mut self.data }
442 /// #   fn free_buffer(&mut self) {}
443 /// # }
444 ///
445 /// impl<T> Drop for MyCollection<T> {
446 ///     fn drop(&mut self) {
447 ///         unsafe {
448 ///             // drop the data
449 ///             if mem::needs_drop::<T>() {
450 ///                 for x in self.iter_mut() {
451 ///                     ptr::drop_in_place(x);
452 ///                 }
453 ///             }
454 ///             self.free_buffer();
455 ///         }
456 ///     }
457 /// }
458 /// ```
459 #[inline]
460 #[stable(feature = "needs_drop", since = "1.21.0")]
461 #[rustc_const_unstable(feature = "const_needs_drop")]
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 allocating space with
469 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
470 /// FFI sometimes, but should generally be avoided.
471 ///
472 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
473 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
474 /// a panic or the end of a scope) before being initialized, then the destructor
475 /// will run on zeroed data, likely leading to [undefined behavior][ub].
476 ///
477 /// See also the documentation for [`mem::uninitialized`][uninit], which has
478 /// many of the same caveats.
479 ///
480 /// [uninit]: fn.uninitialized.html
481 /// [ub]: ../../reference/behavior-considered-undefined.html
482 ///
483 /// # Examples
484 ///
485 /// ```
486 /// use std::mem;
487 ///
488 /// let x: i32 = unsafe { mem::zeroed() };
489 /// assert_eq!(0, x);
490 /// ```
491 #[inline]
492 #[rustc_deprecated(since = "2.0.0", reason = "use `mem::MaybeUninit::zeroed` instead")]
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub unsafe fn zeroed<T>() -> T {
495     #[cfg(not(stage0))]
496     intrinsics::panic_if_uninhabited::<T>();
497     intrinsics::init()
498 }
499
500 /// Bypasses Rust's normal memory-initialization checks by pretending to
501 /// produce a value of type `T`, while doing nothing at all.
502 ///
503 /// **This is incredibly dangerous and should not be done lightly. Deeply
504 /// consider initializing your memory with a default value instead.**
505 ///
506 /// This is useful for FFI functions and initializing arrays sometimes,
507 /// but should generally be avoided.
508 ///
509 /// # Undefined behavior
510 ///
511 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
512 /// uninitialized boolean. For instance, if you branch on the value of such
513 /// a boolean, your program may take one, both, or neither of the branches.
514 ///
515 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
516 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
517 /// value and its fields if you try to overwrite it in a normal manner. The only way
518 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
519 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
520 ///
521 /// If the value does implement [`Drop`], it must be initialized before
522 /// it goes out of scope (and therefore would be dropped). Note that this
523 /// includes a `panic` occurring and unwinding the stack suddenly.
524 ///
525 /// If you partially initialize an array, you may need to use
526 /// [`ptr::drop_in_place`][drop_in_place] to remove the elements you have fully
527 /// initialized followed by [`mem::forget`][mem_forget] to prevent drop running
528 /// on the array. If a partially allocated array is dropped this will lead to
529 /// undefined behaviour.
530 ///
531 /// # Examples
532 ///
533 /// Here's how to safely initialize an array of [`Vec`]s.
534 ///
535 /// ```
536 /// use std::mem;
537 /// use std::ptr;
538 ///
539 /// // Only declare the array. This safely leaves it
540 /// // uninitialized in a way that Rust will track for us.
541 /// // However we can't initialize it element-by-element
542 /// // safely, and we can't use the `[value; 1000]`
543 /// // constructor because it only works with `Copy` data.
544 /// let mut data: [Vec<u32>; 1000];
545 ///
546 /// unsafe {
547 ///     // So we need to do this to initialize it.
548 ///     data = mem::uninitialized();
549 ///
550 ///     // DANGER ZONE: if anything panics or otherwise
551 ///     // incorrectly reads the array here, we will have
552 ///     // Undefined Behavior.
553 ///
554 ///     // It's ok to mutably iterate the data, since this
555 ///     // doesn't involve reading it at all.
556 ///     // (ptr and len are statically known for arrays)
557 ///     for elem in &mut data[..] {
558 ///         // *elem = Vec::new() would try to drop the
559 ///         // uninitialized memory at `elem` -- bad!
560 ///         //
561 ///         // Vec::new doesn't allocate or do really
562 ///         // anything. It's only safe to call here
563 ///         // because we know it won't panic.
564 ///         ptr::write(elem, Vec::new());
565 ///     }
566 ///
567 ///     // SAFE ZONE: everything is initialized.
568 /// }
569 ///
570 /// println!("{:?}", &data[0]);
571 /// ```
572 ///
573 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
574 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
575 /// value that is only [`Clone`], so the following is semantically equivalent and
576 /// vastly less dangerous, as long as you can live with an extra heap
577 /// allocation:
578 ///
579 /// ```
580 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
581 /// println!("{:?}", &data[0]);
582 /// ```
583 ///
584 /// This example shows how to handle partially initialized arrays, which could
585 /// be found in low-level datastructures.
586 ///
587 /// ```
588 /// use std::mem;
589 /// use std::ptr;
590 ///
591 /// // Count the number of elements we have assigned.
592 /// let mut data_len: usize = 0;
593 /// let mut data: [String; 1000];
594 ///
595 /// unsafe {
596 ///     data = mem::uninitialized();
597 ///
598 ///     for elem in &mut data[0..500] {
599 ///         ptr::write(elem, String::from("hello"));
600 ///         data_len += 1;
601 ///     }
602 ///
603 ///     // For each item in the array, drop if we allocated it.
604 ///     for i in &mut data[0..data_len] {
605 ///         ptr::drop_in_place(i);
606 ///     }
607 /// }
608 /// // Forget the data. If this is allowed to drop, you may see a crash such as:
609 /// // 'mem_uninit_test(2457,0x7fffb55dd380) malloc: *** error for object
610 /// // 0x7ff3b8402920: pointer being freed was not allocated'
611 /// mem::forget(data);
612 /// ```
613 ///
614 /// [`Vec`]: ../../std/vec/struct.Vec.html
615 /// [`vec!`]: ../../std/macro.vec.html
616 /// [`Clone`]: ../../std/clone/trait.Clone.html
617 /// [ub]: ../../reference/behavior-considered-undefined.html
618 /// [write]: ../ptr/fn.write.html
619 /// [drop_in_place]: ../ptr/fn.drop_in_place.html
620 /// [mem_zeroed]: fn.zeroed.html
621 /// [mem_forget]: fn.forget.html
622 /// [copy]: ../intrinsics/fn.copy.html
623 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
624 /// [`Drop`]: ../ops/trait.Drop.html
625 #[inline]
626 #[rustc_deprecated(since = "2.0.0", reason = "use `mem::MaybeUninit::uninitialized` instead")]
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub unsafe fn uninitialized<T>() -> T {
629     #[cfg(not(stage0))]
630     intrinsics::panic_if_uninhabited::<T>();
631     intrinsics::uninit()
632 }
633
634 /// Swaps the values at two mutable locations, without deinitializing either one.
635 ///
636 /// # Examples
637 ///
638 /// ```
639 /// use std::mem;
640 ///
641 /// let mut x = 5;
642 /// let mut y = 42;
643 ///
644 /// mem::swap(&mut x, &mut y);
645 ///
646 /// assert_eq!(42, x);
647 /// assert_eq!(5, y);
648 /// ```
649 #[inline]
650 #[stable(feature = "rust1", since = "1.0.0")]
651 pub fn swap<T>(x: &mut T, y: &mut T) {
652     unsafe {
653         ptr::swap_nonoverlapping_one(x, y);
654     }
655 }
656
657 /// Moves `src` into the referenced `dest`, returning the previous `dest` value.
658 ///
659 /// Neither value is dropped.
660 ///
661 /// # Examples
662 ///
663 /// A simple example:
664 ///
665 /// ```
666 /// use std::mem;
667 ///
668 /// let mut v: Vec<i32> = vec![1, 2];
669 ///
670 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
671 /// assert_eq!(2, old_v.len());
672 /// assert_eq!(3, v.len());
673 /// ```
674 ///
675 /// `replace` allows consumption of a struct field by replacing it with another value.
676 /// Without `replace` you can run into issues like these:
677 ///
678 /// ```compile_fail,E0507
679 /// struct Buffer<T> { buf: Vec<T> }
680 ///
681 /// impl<T> Buffer<T> {
682 ///     fn get_and_reset(&mut self) -> Vec<T> {
683 ///         // error: cannot move out of dereference of `&mut`-pointer
684 ///         let buf = self.buf;
685 ///         self.buf = Vec::new();
686 ///         buf
687 ///     }
688 /// }
689 /// ```
690 ///
691 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
692 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
693 /// `self`, allowing it to be returned:
694 ///
695 /// ```
696 /// # #![allow(dead_code)]
697 /// use std::mem;
698 ///
699 /// # struct Buffer<T> { buf: Vec<T> }
700 /// impl<T> Buffer<T> {
701 ///     fn get_and_reset(&mut self) -> Vec<T> {
702 ///         mem::replace(&mut self.buf, Vec::new())
703 ///     }
704 /// }
705 /// ```
706 ///
707 /// [`Clone`]: ../../std/clone/trait.Clone.html
708 #[inline]
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
711     swap(dest, &mut src);
712     src
713 }
714
715 /// Disposes of a value.
716 ///
717 /// While this does call the argument's implementation of [`Drop`][drop],
718 /// it will not release any borrows, as borrows are based on lexical scope.
719 ///
720 /// This effectively does nothing for types which implement `Copy`, e.g.
721 /// integers. Such values are copied and _then_ moved into the function, so the
722 /// value persists after this function call.
723 ///
724 /// This function is not magic; it is literally defined as
725 ///
726 /// ```
727 /// pub fn drop<T>(_x: T) { }
728 /// ```
729 ///
730 /// Because `_x` is moved into the function, it is automatically dropped before
731 /// the function returns.
732 ///
733 /// [drop]: ../ops/trait.Drop.html
734 ///
735 /// # Examples
736 ///
737 /// Basic usage:
738 ///
739 /// ```
740 /// let v = vec![1, 2, 3];
741 ///
742 /// drop(v); // explicitly drop the vector
743 /// ```
744 ///
745 /// Borrows are based on lexical scope, so this produces an error:
746 ///
747 /// ```compile_fail,E0502
748 /// let mut v = vec![1, 2, 3];
749 /// let x = &v[0];
750 ///
751 /// drop(x); // explicitly drop the reference, but the borrow still exists
752 ///
753 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
754 ///            // borrowed as immutable
755 /// ```
756 ///
757 /// An inner scope is needed to fix this:
758 ///
759 /// ```
760 /// let mut v = vec![1, 2, 3];
761 ///
762 /// {
763 ///     let x = &v[0];
764 ///
765 ///     drop(x); // this is now redundant, as `x` is going out of scope anyway
766 /// }
767 ///
768 /// v.push(4); // no problems
769 /// ```
770 ///
771 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
772 /// release a [`RefCell`] borrow:
773 ///
774 /// ```
775 /// use std::cell::RefCell;
776 ///
777 /// let x = RefCell::new(1);
778 ///
779 /// let mut mutable_borrow = x.borrow_mut();
780 /// *mutable_borrow = 1;
781 ///
782 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
783 ///
784 /// let borrow = x.borrow();
785 /// println!("{}", *borrow);
786 /// ```
787 ///
788 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
789 ///
790 /// ```
791 /// #[derive(Copy, Clone)]
792 /// struct Foo(u8);
793 ///
794 /// let x = 1;
795 /// let y = Foo(2);
796 /// drop(x); // a copy of `x` is moved and dropped
797 /// drop(y); // a copy of `y` is moved and dropped
798 ///
799 /// println!("x: {}, y: {}", x, y.0); // still available
800 /// ```
801 ///
802 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
803 /// [`Copy`]: ../../std/marker/trait.Copy.html
804 #[inline]
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn drop<T>(_x: T) { }
807
808 /// Interprets `src` as having type `&U`, and then reads `src` without moving
809 /// the contained value.
810 ///
811 /// This function will unsafely assume the pointer `src` is valid for
812 /// [`size_of::<U>`][size_of] bytes by transmuting `&T` to `&U` and then reading
813 /// the `&U`. It will also unsafely create a copy of the contained value instead of
814 /// moving out of `src`.
815 ///
816 /// It is not a compile-time error if `T` and `U` have different sizes, but it
817 /// is highly encouraged to only invoke this function where `T` and `U` have the
818 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
819 /// `T`.
820 ///
821 /// [ub]: ../../reference/behavior-considered-undefined.html
822 /// [size_of]: fn.size_of.html
823 ///
824 /// # Examples
825 ///
826 /// ```
827 /// use std::mem;
828 ///
829 /// #[repr(packed)]
830 /// struct Foo {
831 ///     bar: u8,
832 /// }
833 ///
834 /// let foo_slice = [10u8];
835 ///
836 /// unsafe {
837 ///     // Copy the data from 'foo_slice' and treat it as a 'Foo'
838 ///     let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
839 ///     assert_eq!(foo_struct.bar, 10);
840 ///
841 ///     // Modify the copied data
842 ///     foo_struct.bar = 20;
843 ///     assert_eq!(foo_struct.bar, 20);
844 /// }
845 ///
846 /// // The contents of 'foo_slice' should not have changed
847 /// assert_eq!(foo_slice, [10]);
848 /// ```
849 #[inline]
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
852     ptr::read_unaligned(src as *const T as *const U)
853 }
854
855 /// Opaque type representing the discriminant of an enum.
856 ///
857 /// See the [`discriminant`] function in this module for more information.
858 ///
859 /// [`discriminant`]: fn.discriminant.html
860 #[stable(feature = "discriminant_value", since = "1.21.0")]
861 pub struct Discriminant<T>(u64, PhantomData<fn() -> T>);
862
863 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
864
865 #[stable(feature = "discriminant_value", since = "1.21.0")]
866 impl<T> Copy for Discriminant<T> {}
867
868 #[stable(feature = "discriminant_value", since = "1.21.0")]
869 impl<T> clone::Clone for Discriminant<T> {
870     fn clone(&self) -> Self {
871         *self
872     }
873 }
874
875 #[stable(feature = "discriminant_value", since = "1.21.0")]
876 impl<T> cmp::PartialEq for Discriminant<T> {
877     fn eq(&self, rhs: &Self) -> bool {
878         self.0 == rhs.0
879     }
880 }
881
882 #[stable(feature = "discriminant_value", since = "1.21.0")]
883 impl<T> cmp::Eq for Discriminant<T> {}
884
885 #[stable(feature = "discriminant_value", since = "1.21.0")]
886 impl<T> hash::Hash for Discriminant<T> {
887     fn hash<H: hash::Hasher>(&self, state: &mut H) {
888         self.0.hash(state);
889     }
890 }
891
892 #[stable(feature = "discriminant_value", since = "1.21.0")]
893 impl<T> fmt::Debug for Discriminant<T> {
894     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
895         fmt.debug_tuple("Discriminant")
896            .field(&self.0)
897            .finish()
898     }
899 }
900
901 /// Returns a value uniquely identifying the enum variant in `v`.
902 ///
903 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
904 /// return value is unspecified.
905 ///
906 /// # Stability
907 ///
908 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
909 /// of some variant will not change between compilations with the same compiler.
910 ///
911 /// # Examples
912 ///
913 /// This can be used to compare enums that carry data, while disregarding
914 /// the actual data:
915 ///
916 /// ```
917 /// use std::mem;
918 ///
919 /// enum Foo { A(&'static str), B(i32), C(i32) }
920 ///
921 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
922 /// assert!(mem::discriminant(&Foo::B(1))     == mem::discriminant(&Foo::B(2)));
923 /// assert!(mem::discriminant(&Foo::B(3))     != mem::discriminant(&Foo::C(3)));
924 /// ```
925 #[stable(feature = "discriminant_value", since = "1.21.0")]
926 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
927     unsafe {
928         Discriminant(intrinsics::discriminant_value(v), PhantomData)
929     }
930 }
931
932 /// A wrapper to inhibit compiler from automatically calling `T`’s destructor.
933 ///
934 /// This wrapper is 0-cost.
935 ///
936 /// # Examples
937 ///
938 /// This wrapper helps with explicitly documenting the drop order dependencies between fields of
939 /// the type:
940 ///
941 /// ```rust
942 /// use std::mem::ManuallyDrop;
943 /// struct Peach;
944 /// struct Banana;
945 /// struct Melon;
946 /// struct FruitBox {
947 ///     // Immediately clear there’s something non-trivial going on with these fields.
948 ///     peach: ManuallyDrop<Peach>,
949 ///     melon: Melon, // Field that’s independent of the other two.
950 ///     banana: ManuallyDrop<Banana>,
951 /// }
952 ///
953 /// impl Drop for FruitBox {
954 ///     fn drop(&mut self) {
955 ///         unsafe {
956 ///             // Explicit ordering in which field destructors are run specified in the intuitive
957 ///             // location – the destructor of the structure containing the fields.
958 ///             // Moreover, one can now reorder fields within the struct however much they want.
959 ///             ManuallyDrop::drop(&mut self.peach);
960 ///             ManuallyDrop::drop(&mut self.banana);
961 ///         }
962 ///         // After destructor for `FruitBox` runs (this function), the destructor for Melon gets
963 ///         // invoked in the usual manner, as it is not wrapped in `ManuallyDrop`.
964 ///     }
965 /// }
966 /// ```
967 #[stable(feature = "manually_drop", since = "1.20.0")]
968 #[lang = "manually_drop"]
969 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
970 #[repr(transparent)]
971 pub struct ManuallyDrop<T: ?Sized> {
972     value: T,
973 }
974
975 impl<T> ManuallyDrop<T> {
976     /// Wrap a value to be manually dropped.
977     ///
978     /// # Examples
979     ///
980     /// ```rust
981     /// use std::mem::ManuallyDrop;
982     /// ManuallyDrop::new(Box::new(()));
983     /// ```
984     #[stable(feature = "manually_drop", since = "1.20.0")]
985     #[inline(always)]
986     pub const fn new(value: T) -> ManuallyDrop<T> {
987         ManuallyDrop { value }
988     }
989
990     /// Extract the value from the `ManuallyDrop` container.
991     ///
992     /// This allows the value to be dropped again.
993     ///
994     /// # Examples
995     ///
996     /// ```rust
997     /// use std::mem::ManuallyDrop;
998     /// let x = ManuallyDrop::new(Box::new(()));
999     /// let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`.
1000     /// ```
1001     #[stable(feature = "manually_drop", since = "1.20.0")]
1002     #[inline(always)]
1003     pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
1004         slot.value
1005     }
1006
1007     /// Takes the contained value out.
1008     ///
1009     /// This method is primarily intended for moving out values in drop.
1010     /// Instead of using [`ManuallyDrop::drop`] to manually drop the value,
1011     /// you can use this method to take the value and use it however desired.
1012     /// `Drop` will be invoked on the returned value following normal end-of-scope rules.
1013     ///
1014     /// If you have ownership of the container, you can use [`ManuallyDrop::into_inner`] instead.
1015     ///
1016     /// # Safety
1017     ///
1018     /// This function semantically moves out the contained value without preventing further usage.
1019     /// It is up to the user of this method to ensure that this container is not used again.
1020     ///
1021     /// [`ManuallyDrop::drop`]: #method.drop
1022     /// [`ManuallyDrop::into_inner`]: #method.into_inner
1023     #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"]
1024     #[unstable(feature = "manually_drop_take", issue = "55422")]
1025     #[inline]
1026     pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T {
1027         ManuallyDrop::into_inner(ptr::read(slot))
1028     }
1029 }
1030
1031 impl<T: ?Sized> ManuallyDrop<T> {
1032     /// Manually drops the contained value.
1033     ///
1034     /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead.
1035     ///
1036     /// # Safety
1037     ///
1038     /// This function runs the destructor of the contained value and thus the wrapped value
1039     /// now represents uninitialized data. It is up to the user of this method to ensure the
1040     /// uninitialized data is not actually used.
1041     ///
1042     /// [`ManuallyDrop::into_inner`]: #method.into_inner
1043     #[stable(feature = "manually_drop", since = "1.20.0")]
1044     #[inline]
1045     pub unsafe fn drop(slot: &mut ManuallyDrop<T>) {
1046         ptr::drop_in_place(&mut slot.value)
1047     }
1048 }
1049
1050 #[stable(feature = "manually_drop", since = "1.20.0")]
1051 impl<T: ?Sized> Deref for ManuallyDrop<T> {
1052     type Target = T;
1053     #[inline(always)]
1054     fn deref(&self) -> &T {
1055         &self.value
1056     }
1057 }
1058
1059 #[stable(feature = "manually_drop", since = "1.20.0")]
1060 impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
1061     #[inline(always)]
1062     fn deref_mut(&mut self) -> &mut T {
1063         &mut self.value
1064     }
1065 }
1066
1067 /// A newtype to construct uninitialized instances of `T`
1068 #[allow(missing_debug_implementations)]
1069 #[unstable(feature = "maybe_uninit", issue = "53491")]
1070 // NOTE after stabilizing `MaybeUninit` proceed to deprecate `mem::{uninitialized,zeroed}`
1071 pub union MaybeUninit<T> {
1072     uninit: (),
1073     value: ManuallyDrop<T>,
1074 }
1075
1076 impl<T> MaybeUninit<T> {
1077     /// Create a new `MaybeUninit` initialized with the given value.
1078     ///
1079     /// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
1080     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1081     #[unstable(feature = "maybe_uninit", issue = "53491")]
1082     #[inline(always)]
1083     pub const fn new(val: T) -> MaybeUninit<T> {
1084         MaybeUninit { value: ManuallyDrop::new(val) }
1085     }
1086
1087     /// Create a new `MaybeUninit` in an uninitialized state.
1088     ///
1089     /// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
1090     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1091     #[unstable(feature = "maybe_uninit", issue = "53491")]
1092     #[inline(always)]
1093     pub const fn uninitialized() -> MaybeUninit<T> {
1094         MaybeUninit { uninit: () }
1095     }
1096
1097     /// Create a new `MaybeUninit` in an uninitialized state, with the memory being
1098     /// filled with `0` bytes.  It depends on `T` whether that already makes for
1099     /// proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized,
1100     /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not
1101     /// be null.
1102     ///
1103     /// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
1104     /// It is your responsibility to make sure `T` gets dropped if it got initialized.
1105     #[unstable(feature = "maybe_uninit", issue = "53491")]
1106     #[inline]
1107     pub fn zeroed() -> MaybeUninit<T> {
1108         let mut u = MaybeUninit::<T>::uninitialized();
1109         unsafe {
1110             u.as_mut_ptr().write_bytes(0u8, 1);
1111         }
1112         u
1113     }
1114
1115     /// Set the value of the `MaybeUninit`. This overwrites any previous value without dropping it.
1116     #[unstable(feature = "maybe_uninit", issue = "53491")]
1117     #[inline(always)]
1118     pub fn set(&mut self, val: T) {
1119         unsafe {
1120             self.value = ManuallyDrop::new(val);
1121         }
1122     }
1123
1124     /// Extract the value from the `MaybeUninit` container.  This is a great way
1125     /// to ensure that the data will get dropped, because the resulting `T` is
1126     /// subject to the usual drop handling.
1127     ///
1128     /// # Unsafety
1129     ///
1130     /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
1131     /// state, otherwise this will immediately cause undefined behavior.
1132     #[unstable(feature = "maybe_uninit", issue = "53491")]
1133     #[inline(always)]
1134     pub unsafe fn into_inner(self) -> T {
1135         #[cfg(not(stage0))]
1136         intrinsics::panic_if_uninhabited::<T>();
1137         ManuallyDrop::into_inner(self.value)
1138     }
1139
1140     /// Get a reference to the contained value.
1141     ///
1142     /// # Unsafety
1143     ///
1144     /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
1145     /// state, otherwise this will immediately cause undefined behavior.
1146     #[unstable(feature = "maybe_uninit", issue = "53491")]
1147     #[inline(always)]
1148     pub unsafe fn get_ref(&self) -> &T {
1149         &*self.value
1150     }
1151
1152     /// Get a mutable reference to the contained value.
1153     ///
1154     /// # Unsafety
1155     ///
1156     /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
1157     /// state, otherwise this will immediately cause undefined behavior.
1158     // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references
1159     // to uninitialized data (e.g., in `libcore/fmt/float.rs`).  We should make
1160     // a final decision about the rules before stabilization.
1161     #[unstable(feature = "maybe_uninit", issue = "53491")]
1162     #[inline(always)]
1163     pub unsafe fn get_mut(&mut self) -> &mut T {
1164         &mut *self.value
1165     }
1166
1167     /// Get a pointer to the contained value. Reading from this pointer will be undefined
1168     /// behavior unless the `MaybeUninit` is initialized.
1169     #[unstable(feature = "maybe_uninit", issue = "53491")]
1170     #[inline(always)]
1171     pub fn as_ptr(&self) -> *const T {
1172         unsafe { &*self.value as *const T }
1173     }
1174
1175     /// Get a mutable pointer to the contained value. Reading from this pointer will be undefined
1176     /// behavior unless the `MaybeUninit` is initialized.
1177     #[unstable(feature = "maybe_uninit", issue = "53491")]
1178     #[inline(always)]
1179     pub fn as_mut_ptr(&mut self) -> *mut T {
1180         unsafe { &mut *self.value as *mut T }
1181     }
1182 }