]> git.proxmox.com Git - rustc.git/blob - src/libcore/mem.rs
New upstream version 1.17.0+dfsg1
[rustc.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
26 #[stable(feature = "rust1", since = "1.0.0")]
27 pub use intrinsics::transmute;
28
29 /// Leaks a value: takes ownership and "forgets" about the value **without running
30 /// 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.
34 ///
35 /// If you want to dispose of a value properly, running its destructor, see
36 /// [`mem::drop`][drop].
37 ///
38 /// # Safety
39 ///
40 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees
41 /// do not include a guarantee that destructors will always run. For example,
42 /// a program can create a reference cycle using [`Rc`][rc], or call
43 /// [`process:exit`][exit] to exit without running destructors. Thus, allowing
44 /// `mem::forget` from safe code does not fundamentally change Rust's safety
45 /// guarantees.
46 ///
47 /// That said, leaking resources such as memory or I/O objects is usually undesirable,
48 /// so `forget` is only recommended for specialized use cases like those shown below.
49 ///
50 /// Because forgetting a value is allowed, any `unsafe` code you write must
51 /// allow for this possibility. You cannot return a value and expect that the
52 /// caller will necessarily run the value's destructor.
53 ///
54 /// [rc]: ../../std/rc/struct.Rc.html
55 /// [exit]: ../../std/process/fn.exit.html
56 ///
57 /// # Examples
58 ///
59 /// Leak some heap memory by never deallocating it:
60 ///
61 /// ```
62 /// use std::mem;
63 ///
64 /// let heap_memory = Box::new(3);
65 /// mem::forget(heap_memory);
66 /// ```
67 ///
68 /// Leak an I/O object, never closing the file:
69 ///
70 /// ```no_run
71 /// use std::mem;
72 /// use std::fs::File;
73 ///
74 /// let file = File::open("foo.txt").unwrap();
75 /// mem::forget(file);
76 /// ```
77 ///
78 /// The practical use cases for `forget` are rather specialized and mainly come
79 /// up in unsafe or FFI code.
80 ///
81 /// ## Use case 1
82 ///
83 /// You have created an uninitialized value using [`mem::uninitialized`][uninit].
84 /// You must either initialize or `forget` it on every computation path before
85 /// Rust drops it automatically, like at the end of a scope or after a panic.
86 /// Running the destructor on an uninitialized value would be [undefined behavior][ub].
87 ///
88 /// ```
89 /// use std::mem;
90 /// use std::ptr;
91 ///
92 /// # let some_condition = false;
93 /// unsafe {
94 /// let mut uninit_vec: Vec<u32> = mem::uninitialized();
95 ///
96 /// if some_condition {
97 /// // Initialize the variable.
98 /// ptr::write(&mut uninit_vec, Vec::new());
99 /// } else {
100 /// // Forget the uninitialized value so its destructor doesn't run.
101 /// mem::forget(uninit_vec);
102 /// }
103 /// }
104 /// ```
105 ///
106 /// ## Use case 2
107 ///
108 /// You have duplicated the bytes making up a value, without doing a proper
109 /// [`Clone`][clone]. You need the value's destructor to run only once,
110 /// because a double `free` is undefined behavior.
111 ///
112 /// An example is the definition of [`mem::swap`][swap] in this module:
113 ///
114 /// ```
115 /// use std::mem;
116 /// use std::ptr;
117 ///
118 /// # #[allow(dead_code)]
119 /// fn swap<T>(x: &mut T, y: &mut T) {
120 /// unsafe {
121 /// // Give ourselves some scratch space to work with
122 /// let mut t: T = mem::uninitialized();
123 ///
124 /// // Perform the swap, `&mut` pointers never alias
125 /// ptr::copy_nonoverlapping(&*x, &mut t, 1);
126 /// ptr::copy_nonoverlapping(&*y, x, 1);
127 /// ptr::copy_nonoverlapping(&t, y, 1);
128 ///
129 /// // y and t now point to the same thing, but we need to completely
130 /// // forget `t` because we do not want to run the destructor for `T`
131 /// // on its value, which is still owned somewhere outside this function.
132 /// mem::forget(t);
133 /// }
134 /// }
135 /// ```
136 ///
137 /// ## Use case 3
138 ///
139 /// You are transferring ownership across a [FFI] boundary to code written in
140 /// another language. You need to `forget` the value on the Rust side because Rust
141 /// code is no longer responsible for it.
142 ///
143 /// ```no_run
144 /// use std::mem;
145 ///
146 /// extern "C" {
147 /// fn my_c_function(x: *const u32);
148 /// }
149 ///
150 /// let x: Box<u32> = Box::new(3);
151 ///
152 /// // Transfer ownership into C code.
153 /// unsafe {
154 /// my_c_function(&*x);
155 /// }
156 /// mem::forget(x);
157 /// ```
158 ///
159 /// In this case, C code must call back into Rust to free the object. Calling C's `free`
160 /// function on a [`Box`][box] is *not* safe! Also, `Box` provides an [`into_raw`][into_raw]
161 /// method which is the preferred way to do this in practice.
162 ///
163 /// [drop]: fn.drop.html
164 /// [uninit]: fn.uninitialized.html
165 /// [clone]: ../clone/trait.Clone.html
166 /// [swap]: fn.swap.html
167 /// [FFI]: ../../book/ffi.html
168 /// [box]: ../../std/boxed/struct.Box.html
169 /// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
170 /// [ub]: ../../reference/behavior-considered-undefined.html
171 #[inline]
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn forget<T>(t: T) {
174 unsafe { intrinsics::forget(t) }
175 }
176
177 /// Returns the size of a type in bytes.
178 ///
179 /// More specifically, this is the offset in bytes between successive
180 /// items of the same type, including alignment padding.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use std::mem;
186 ///
187 /// assert_eq!(4, mem::size_of::<i32>());
188 /// ```
189 #[inline]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn size_of<T>() -> usize {
192 unsafe { intrinsics::size_of::<T>() }
193 }
194
195 /// Returns the size of the pointed-to value in bytes.
196 ///
197 /// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
198 /// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
199 /// then `size_of_val` can be used to get the dynamically-known size.
200 ///
201 /// [slice]: ../../std/primitive.slice.html
202 /// [trait object]: ../../book/trait-objects.html
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use std::mem;
208 ///
209 /// assert_eq!(4, mem::size_of_val(&5i32));
210 ///
211 /// let x: [u8; 13] = [0; 13];
212 /// let y: &[u8] = &x;
213 /// assert_eq!(13, mem::size_of_val(y));
214 /// ```
215 #[inline]
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
218 unsafe { intrinsics::size_of_val(val) }
219 }
220
221 /// Returns the [ABI]-required minimum alignment of a type.
222 ///
223 /// Every valid address of a value of the type `T` must be a multiple of this number.
224 ///
225 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
226 ///
227 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// # #![allow(deprecated)]
233 /// use std::mem;
234 ///
235 /// assert_eq!(4, mem::min_align_of::<i32>());
236 /// ```
237 #[inline]
238 #[stable(feature = "rust1", since = "1.0.0")]
239 #[rustc_deprecated(reason = "use `align_of` instead", since = "1.2.0")]
240 pub fn min_align_of<T>() -> usize {
241 unsafe { intrinsics::min_align_of::<T>() }
242 }
243
244 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
245 ///
246 /// Every valid address of a value of the type `T` must be a multiple of this number.
247 ///
248 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// # #![allow(deprecated)]
254 /// use std::mem;
255 ///
256 /// assert_eq!(4, mem::min_align_of_val(&5i32));
257 /// ```
258 #[inline]
259 #[stable(feature = "rust1", since = "1.0.0")]
260 #[rustc_deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
261 pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
262 unsafe { intrinsics::min_align_of_val(val) }
263 }
264
265 /// Returns the [ABI]-required minimum alignment of a type.
266 ///
267 /// Every valid address of a value of the type `T` must be a multiple of this number.
268 ///
269 /// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
270 ///
271 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// use std::mem;
277 ///
278 /// assert_eq!(4, mem::align_of::<i32>());
279 /// ```
280 #[inline]
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn align_of<T>() -> usize {
283 unsafe { intrinsics::min_align_of::<T>() }
284 }
285
286 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
287 ///
288 /// Every valid address of a value of the type `T` must be a multiple of this number.
289 ///
290 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// use std::mem;
296 ///
297 /// assert_eq!(4, mem::align_of_val(&5i32));
298 /// ```
299 #[inline]
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
302 unsafe { intrinsics::min_align_of_val(val) }
303 }
304
305 /// Creates a value whose bytes are all zero.
306 ///
307 /// This has the same effect as allocating space with
308 /// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
309 /// [FFI] sometimes, but should generally be avoided.
310 ///
311 /// There is no guarantee that an all-zero byte-pattern represents a valid value of
312 /// some type `T`. If `T` has a destructor and the value is destroyed (due to
313 /// a panic or the end of a scope) before being initialized, then the destructor
314 /// will run on zeroed data, likely leading to [undefined behavior][ub].
315 ///
316 /// See also the documentation for [`mem::uninitialized`][uninit], which has
317 /// many of the same caveats.
318 ///
319 /// [uninit]: fn.uninitialized.html
320 /// [FFI]: ../../book/ffi.html
321 /// [ub]: ../../reference/behavior-considered-undefined.html
322 ///
323 /// # Examples
324 ///
325 /// ```
326 /// use std::mem;
327 ///
328 /// let x: i32 = unsafe { mem::zeroed() };
329 /// assert_eq!(0, x);
330 /// ```
331 #[inline]
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub unsafe fn zeroed<T>() -> T {
334 intrinsics::init()
335 }
336
337 /// Bypasses Rust's normal memory-initialization checks by pretending to
338 /// produce a value of type `T`, while doing nothing at all.
339 ///
340 /// **This is incredibly dangerous and should not be done lightly. Deeply
341 /// consider initializing your memory with a default value instead.**
342 ///
343 /// This is useful for [FFI] functions and initializing arrays sometimes,
344 /// but should generally be avoided.
345 ///
346 /// [FFI]: ../../book/ffi.html
347 ///
348 /// # Undefined behavior
349 ///
350 /// It is [undefined behavior][ub] to read uninitialized memory, even just an
351 /// uninitialized boolean. For instance, if you branch on the value of such
352 /// a boolean, your program may take one, both, or neither of the branches.
353 ///
354 /// Writing to the uninitialized value is similarly dangerous. Rust believes the
355 /// value is initialized, and will therefore try to [`Drop`] the uninitialized
356 /// value and its fields if you try to overwrite it in a normal manner. The only way
357 /// to safely initialize an uninitialized value is with [`ptr::write`][write],
358 /// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
359 ///
360 /// If the value does implement [`Drop`], it must be initialized before
361 /// it goes out of scope (and therefore would be dropped). Note that this
362 /// includes a `panic` occurring and unwinding the stack suddenly.
363 ///
364 /// # Examples
365 ///
366 /// Here's how to safely initialize an array of [`Vec`]s.
367 ///
368 /// ```
369 /// use std::mem;
370 /// use std::ptr;
371 ///
372 /// // Only declare the array. This safely leaves it
373 /// // uninitialized in a way that Rust will track for us.
374 /// // However we can't initialize it element-by-element
375 /// // safely, and we can't use the `[value; 1000]`
376 /// // constructor because it only works with `Copy` data.
377 /// let mut data: [Vec<u32>; 1000];
378 ///
379 /// unsafe {
380 /// // So we need to do this to initialize it.
381 /// data = mem::uninitialized();
382 ///
383 /// // DANGER ZONE: if anything panics or otherwise
384 /// // incorrectly reads the array here, we will have
385 /// // Undefined Behavior.
386 ///
387 /// // It's ok to mutably iterate the data, since this
388 /// // doesn't involve reading it at all.
389 /// // (ptr and len are statically known for arrays)
390 /// for elem in &mut data[..] {
391 /// // *elem = Vec::new() would try to drop the
392 /// // uninitialized memory at `elem` -- bad!
393 /// //
394 /// // Vec::new doesn't allocate or do really
395 /// // anything. It's only safe to call here
396 /// // because we know it won't panic.
397 /// ptr::write(elem, Vec::new());
398 /// }
399 ///
400 /// // SAFE ZONE: everything is initialized.
401 /// }
402 ///
403 /// println!("{:?}", &data[0]);
404 /// ```
405 ///
406 /// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
407 /// can be. Note that the [`vec!`] macro *does* let you initialize every element with a
408 /// value that is only [`Clone`], so the following is semantically equivalent and
409 /// vastly less dangerous, as long as you can live with an extra heap
410 /// allocation:
411 ///
412 /// ```
413 /// let data: Vec<Vec<u32>> = vec![Vec::new(); 1000];
414 /// println!("{:?}", &data[0]);
415 /// ```
416 ///
417 /// [`Vec`]: ../../std/vec/struct.Vec.html
418 /// [`vec!`]: ../../std/macro.vec.html
419 /// [`Clone`]: ../../std/clone/trait.Clone.html
420 /// [ub]: ../../reference/behavior-considered-undefined.html
421 /// [write]: ../ptr/fn.write.html
422 /// [copy]: ../intrinsics/fn.copy.html
423 /// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
424 /// [`Drop`]: ../ops/trait.Drop.html
425 #[inline]
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub unsafe fn uninitialized<T>() -> T {
428 intrinsics::uninit()
429 }
430
431 /// Swaps the values at two mutable locations, without deinitializing either one.
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// use std::mem;
437 ///
438 /// let mut x = 5;
439 /// let mut y = 42;
440 ///
441 /// mem::swap(&mut x, &mut y);
442 ///
443 /// assert_eq!(42, x);
444 /// assert_eq!(5, y);
445 /// ```
446 #[inline]
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn swap<T>(x: &mut T, y: &mut T) {
449 unsafe {
450 // Give ourselves some scratch space to work with
451 let mut t: T = uninitialized();
452
453 // Perform the swap, `&mut` pointers never alias
454 ptr::copy_nonoverlapping(&*x, &mut t, 1);
455 ptr::copy_nonoverlapping(&*y, x, 1);
456 ptr::copy_nonoverlapping(&t, y, 1);
457
458 // y and t now point to the same thing, but we need to completely
459 // forget `t` because we do not want to run the destructor for `T`
460 // on its value, which is still owned somewhere outside this function.
461 forget(t);
462 }
463 }
464
465 /// Replaces the value at a mutable location with a new one, returning the old value, without
466 /// deinitializing either one.
467 ///
468 /// # Examples
469 ///
470 /// A simple example:
471 ///
472 /// ```
473 /// use std::mem;
474 ///
475 /// let mut v: Vec<i32> = vec![1, 2];
476 ///
477 /// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
478 /// assert_eq!(2, old_v.len());
479 /// assert_eq!(3, v.len());
480 /// ```
481 ///
482 /// `replace` allows consumption of a struct field by replacing it with another value.
483 /// Without `replace` you can run into issues like these:
484 ///
485 /// ```ignore
486 /// struct Buffer<T> { buf: Vec<T> }
487 ///
488 /// impl<T> Buffer<T> {
489 /// fn get_and_reset(&mut self) -> Vec<T> {
490 /// // error: cannot move out of dereference of `&mut`-pointer
491 /// let buf = self.buf;
492 /// self.buf = Vec::new();
493 /// buf
494 /// }
495 /// }
496 /// ```
497 ///
498 /// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
499 /// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
500 /// `self`, allowing it to be returned:
501 ///
502 /// ```
503 /// # #![allow(dead_code)]
504 /// use std::mem;
505 ///
506 /// # struct Buffer<T> { buf: Vec<T> }
507 /// impl<T> Buffer<T> {
508 /// fn get_and_reset(&mut self) -> Vec<T> {
509 /// mem::replace(&mut self.buf, Vec::new())
510 /// }
511 /// }
512 /// ```
513 ///
514 /// [`Clone`]: ../../std/clone/trait.Clone.html
515 #[inline]
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn replace<T>(dest: &mut T, mut src: T) -> T {
518 swap(dest, &mut src);
519 src
520 }
521
522 /// Disposes of a value.
523 ///
524 /// While this does call the argument's implementation of [`Drop`][drop],
525 /// it will not release any borrows, as borrows are based on lexical scope.
526 ///
527 /// This effectively does nothing for
528 /// [types which implement `Copy`](../../book/ownership.html#copy-types),
529 /// e.g. integers. Such values are copied and _then_ moved into the function,
530 /// so the value persists after this function call.
531 ///
532 /// This function is not magic; it is literally defined as
533 ///
534 /// ```
535 /// pub fn drop<T>(_x: T) { }
536 /// ```
537 ///
538 /// Because `_x` is moved into the function, it is automatically dropped before
539 /// the function returns.
540 ///
541 /// [drop]: ../ops/trait.Drop.html
542 ///
543 /// # Examples
544 ///
545 /// Basic usage:
546 ///
547 /// ```
548 /// let v = vec![1, 2, 3];
549 ///
550 /// drop(v); // explicitly drop the vector
551 /// ```
552 ///
553 /// Borrows are based on lexical scope, so this produces an error:
554 ///
555 /// ```ignore
556 /// let mut v = vec![1, 2, 3];
557 /// let x = &v[0];
558 ///
559 /// drop(x); // explicitly drop the reference, but the borrow still exists
560 ///
561 /// v.push(4); // error: cannot borrow `v` as mutable because it is also
562 /// // borrowed as immutable
563 /// ```
564 ///
565 /// An inner scope is needed to fix this:
566 ///
567 /// ```
568 /// let mut v = vec![1, 2, 3];
569 ///
570 /// {
571 /// let x = &v[0];
572 ///
573 /// drop(x); // this is now redundant, as `x` is going out of scope anyway
574 /// }
575 ///
576 /// v.push(4); // no problems
577 /// ```
578 ///
579 /// Since [`RefCell`] enforces the borrow rules at runtime, `drop` can
580 /// release a [`RefCell`] borrow:
581 ///
582 /// ```
583 /// use std::cell::RefCell;
584 ///
585 /// let x = RefCell::new(1);
586 ///
587 /// let mut mutable_borrow = x.borrow_mut();
588 /// *mutable_borrow = 1;
589 ///
590 /// drop(mutable_borrow); // relinquish the mutable borrow on this slot
591 ///
592 /// let borrow = x.borrow();
593 /// println!("{}", *borrow);
594 /// ```
595 ///
596 /// Integers and other types implementing [`Copy`] are unaffected by `drop`.
597 ///
598 /// ```
599 /// #[derive(Copy, Clone)]
600 /// struct Foo(u8);
601 ///
602 /// let x = 1;
603 /// let y = Foo(2);
604 /// drop(x); // a copy of `x` is moved and dropped
605 /// drop(y); // a copy of `y` is moved and dropped
606 ///
607 /// println!("x: {}, y: {}", x, y.0); // still available
608 /// ```
609 ///
610 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
611 /// [`Copy`]: ../../std/marker/trait.Copy.html
612 #[inline]
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn drop<T>(_x: T) { }
615
616 /// Interprets `src` as having type `&U`, and then reads `src` without moving
617 /// the contained value.
618 ///
619 /// This function will unsafely assume the pointer `src` is valid for
620 /// [`size_of::<U>()`][size_of] bytes by transmuting `&T` to `&U` and then reading
621 /// the `&U`. It will also unsafely create a copy of the contained value instead of
622 /// moving out of `src`.
623 ///
624 /// It is not a compile-time error if `T` and `U` have different sizes, but it
625 /// is highly encouraged to only invoke this function where `T` and `U` have the
626 /// same size. This function triggers [undefined behavior][ub] if `U` is larger than
627 /// `T`.
628 ///
629 /// [ub]: ../../reference/behavior-considered-undefined.html
630 /// [size_of]: fn.size_of.html
631 ///
632 /// # Examples
633 ///
634 /// ```
635 /// use std::mem;
636 ///
637 /// #[repr(packed)]
638 /// struct Foo {
639 /// bar: u8,
640 /// }
641 ///
642 /// let foo_slice = [10u8];
643 ///
644 /// unsafe {
645 /// // Copy the data from 'foo_slice' and treat it as a 'Foo'
646 /// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
647 /// assert_eq!(foo_struct.bar, 10);
648 ///
649 /// // Modify the copied data
650 /// foo_struct.bar = 20;
651 /// assert_eq!(foo_struct.bar, 20);
652 /// }
653 ///
654 /// // The contents of 'foo_slice' should not have changed
655 /// assert_eq!(foo_slice, [10]);
656 /// ```
657 #[inline]
658 #[stable(feature = "rust1", since = "1.0.0")]
659 pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
660 ptr::read(src as *const T as *const U)
661 }
662
663 /// Opaque type representing the discriminant of an enum.
664 ///
665 /// See the `discriminant` function in this module for more information.
666 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
667 pub struct Discriminant<T>(u64, PhantomData<*const T>);
668
669 // N.B. These trait implementations cannot be derived because we don't want any bounds on T.
670
671 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
672 impl<T> Copy for Discriminant<T> {}
673
674 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
675 impl<T> clone::Clone for Discriminant<T> {
676 fn clone(&self) -> Self {
677 *self
678 }
679 }
680
681 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
682 impl<T> cmp::PartialEq for Discriminant<T> {
683 fn eq(&self, rhs: &Self) -> bool {
684 self.0 == rhs.0
685 }
686 }
687
688 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
689 impl<T> cmp::Eq for Discriminant<T> {}
690
691 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
692 impl<T> hash::Hash for Discriminant<T> {
693 fn hash<H: hash::Hasher>(&self, state: &mut H) {
694 self.0.hash(state);
695 }
696 }
697
698 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
699 impl<T> fmt::Debug for Discriminant<T> {
700 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
701 fmt.debug_tuple("Discriminant")
702 .field(&self.0)
703 .finish()
704 }
705 }
706
707 /// Returns a value uniquely identifying the enum variant in `v`.
708 ///
709 /// If `T` is not an enum, calling this function will not result in undefined behavior, but the
710 /// return value is unspecified.
711 ///
712 /// # Stability
713 ///
714 /// The discriminant of an enum variant may change if the enum definition changes. A discriminant
715 /// of some variant will not change between compilations with the same compiler.
716 ///
717 /// # Examples
718 ///
719 /// This can be used to compare enums that carry data, while disregarding
720 /// the actual data:
721 ///
722 /// ```
723 /// #![feature(discriminant_value)]
724 /// use std::mem;
725 ///
726 /// enum Foo { A(&'static str), B(i32), C(i32) }
727 ///
728 /// assert!(mem::discriminant(&Foo::A("bar")) == mem::discriminant(&Foo::A("baz")));
729 /// assert!(mem::discriminant(&Foo::B(1)) == mem::discriminant(&Foo::B(2)));
730 /// assert!(mem::discriminant(&Foo::B(3)) != mem::discriminant(&Foo::C(3)));
731 /// ```
732 #[unstable(feature = "discriminant_value", reason = "recently added, follows RFC", issue = "24263")]
733 pub fn discriminant<T>(v: &T) -> Discriminant<T> {
734 unsafe {
735 Discriminant(intrinsics::discriminant_value(v), PhantomData)
736 }
737 }
738