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