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