From ef5da14edb09d6425b1b6576d418e12c268ddf17 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Wed, 3 Dec 2014 17:21:51 -0500 Subject: [PATCH] libcore: Add NonZero lang item and implement some methods. --- src/libcore/ptr.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 8c9d77a0e9c..910204edf70 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -90,6 +90,7 @@ use mem; use clone::Clone; use intrinsics; +use kinds::Copy; use option::Option; use option::Option::{Some, None}; use kinds::{Send, Sync}; @@ -109,6 +110,15 @@ pub use intrinsics::copy_memory; #[experimental = "uncertain about naming and semantics"] pub use intrinsics::set_memory; + +/// A wrapper type for raw pointers and integers that will never be +/// NULL or 0 that might allow certain optimizations. +#[lang="non_zero"] +#[deriving(Clone, PartialEq, Eq, PartialOrd)] +pub struct NonZero(pub T); + +impl Copy for NonZero {} + /// Creates a null raw pointer. /// /// # Examples @@ -313,6 +323,32 @@ impl RawPtr for *const T { } } +impl RawPtr for NonZero<*const T> { + #[inline] + fn null() -> NonZero<*const T> { NonZero(null()) } + + #[inline] + fn is_null(&self) -> bool { false } + + #[inline] + fn to_uint(&self) -> uint { + let NonZero(p) = *self; + p as uint + } + + #[inline] + unsafe fn offset(self, count: int) -> NonZero<*const T> { + let NonZero(p) = self; + NonZero(intrinsics::offset(p, count)) + } + + #[inline] + unsafe fn as_ref<'a>(&self) -> Option<&'a T> { + let NonZero(p) = *self; + Some(&*p) + } +} + impl RawPtr for *mut T { #[inline] fn null() -> *mut T { null_mut() } @@ -338,6 +374,32 @@ impl RawPtr for *mut T { } } +impl RawPtr for NonZero<*mut T> { + #[inline] + fn null() -> NonZero<*mut T> { NonZero(null_mut()) } + + #[inline] + fn is_null(&self) -> bool { false } + + #[inline] + fn to_uint(&self) -> uint { + let NonZero(p) = *self; + p as uint + } + + #[inline] + unsafe fn offset(self, count: int) -> NonZero<*mut T> { + let NonZero(p) = self; + NonZero(intrinsics::offset(p as *const T, count) as *mut T) + } + + #[inline] + unsafe fn as_ref<'a>(&self) -> Option<&'a T> { + let NonZero(p) = *self; + Some(&*p) + } +} + impl RawMutPtr for *mut T { #[inline] unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> { @@ -349,6 +411,14 @@ impl RawMutPtr for *mut T { } } +impl RawMutPtr for NonZero<*mut T> { + #[inline] + unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> { + let NonZero(p) = *self; + Some(&mut *p) + } +} + // Equality for pointers impl PartialEq for *const T { #[inline]