]> git.lizzy.rs Git - rust.git/blob - src/libcore/nonzero.rs
Some docs for std::num
[rust.git] / src / libcore / nonzero.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 //! Exposes the NonZero lang item which provides optimization hints.
12 #![unstable(feature = "nonzero",
13             reason = "needs an RFC to flesh out the design",
14             issue = "27730")]
15
16 use marker::Sized;
17 use ops::{CoerceUnsized, Deref};
18
19 /// Unsafe trait to indicate what types are usable with the NonZero struct
20 pub unsafe trait Zeroable {}
21
22 unsafe impl<T:?Sized> Zeroable for *const T {}
23 unsafe impl<T:?Sized> Zeroable for *mut T {}
24 unsafe impl Zeroable for isize {}
25 unsafe impl Zeroable for usize {}
26 unsafe impl Zeroable for i8 {}
27 unsafe impl Zeroable for u8 {}
28 unsafe impl Zeroable for i16 {}
29 unsafe impl Zeroable for u16 {}
30 unsafe impl Zeroable for i32 {}
31 unsafe impl Zeroable for u32 {}
32 unsafe impl Zeroable for i64 {}
33 unsafe impl Zeroable for u64 {}
34
35 /// A wrapper type for raw pointers and integers that will never be
36 /// NULL or 0 that might allow certain optimizations.
37 #[lang = "non_zero"]
38 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
39 pub struct NonZero<T: Zeroable>(T);
40
41 impl<T: Zeroable> NonZero<T> {
42     /// Creates an instance of NonZero with the provided value.
43     /// You must indeed ensure that the value is actually "non-zero".
44     #[inline(always)]
45     pub const unsafe fn new(inner: T) -> NonZero<T> {
46         NonZero(inner)
47     }
48 }
49
50 impl<T: Zeroable> Deref for NonZero<T> {
51     type Target = T;
52
53     #[inline]
54     fn deref(&self) -> &T {
55         let NonZero(ref inner) = *self;
56         inner
57     }
58 }
59
60 impl<T: Zeroable+CoerceUnsized<U>, U: Zeroable> CoerceUnsized<NonZero<U>> for NonZero<T> {}