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