Skip to content

Commit 458475b

Browse files
committed
libcore: Add NonZero lang item and implement some methods.
1 parent 5fb8576 commit 458475b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/libcore/ptr.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,13 @@ pub use intrinsics::copy_memory;
101101
pub use intrinsics::copy_nonoverlapping_memory;
102102
pub use intrinsics::set_memory;
103103

104+
105+
/// A wrapper type for raw pointers and integers that will never be
106+
/// NULL or 0 that might allow certain optimizations.
107+
#[lang="non_zero"]
108+
#[deriving(Clone, PartialEq, Eq, PartialOrd)]
109+
pub struct NonZero<T>(pub T);
110+
104111
/// Create a null pointer.
105112
///
106113
/// # Example
@@ -264,6 +271,32 @@ impl<T> RawPtr<T> for *const T {
264271
}
265272
}
266273

274+
impl<T> RawPtr<T> for NonZero<*const T> {
275+
#[inline]
276+
fn null() -> NonZero<*const T> { NonZero(null()) }
277+
278+
#[inline]
279+
fn is_null(&self) -> bool { false }
280+
281+
#[inline]
282+
fn to_uint(&self) -> uint {
283+
let NonZero(p) = *self;
284+
p as uint
285+
}
286+
287+
#[inline]
288+
unsafe fn offset(self, count: int) -> NonZero<*const T> {
289+
let NonZero(p) = self;
290+
NonZero(intrinsics::offset(p, count))
291+
}
292+
293+
#[inline]
294+
unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
295+
let NonZero(p) = *self;
296+
Some(&*p)
297+
}
298+
}
299+
267300
impl<T> RawPtr<T> for *mut T {
268301
#[inline]
269302
fn null() -> *mut T { null_mut() }
@@ -289,6 +322,32 @@ impl<T> RawPtr<T> for *mut T {
289322
}
290323
}
291324

325+
impl<T> RawPtr<T> for NonZero<*mut T> {
326+
#[inline]
327+
fn null() -> NonZero<*mut T> { NonZero(null_mut()) }
328+
329+
#[inline]
330+
fn is_null(&self) -> bool { false }
331+
332+
#[inline]
333+
fn to_uint(&self) -> uint {
334+
let NonZero(p) = *self;
335+
p as uint
336+
}
337+
338+
#[inline]
339+
unsafe fn offset(self, count: int) -> NonZero<*mut T> {
340+
let NonZero(p) = self;
341+
NonZero(intrinsics::offset(p as *const T, count) as *mut T)
342+
}
343+
344+
#[inline]
345+
unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
346+
let NonZero(p) = *self;
347+
Some(&*p)
348+
}
349+
}
350+
292351
impl<T> RawMutPtr<T> for *mut T {
293352
#[inline]
294353
unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
@@ -300,6 +359,14 @@ impl<T> RawMutPtr<T> for *mut T {
300359
}
301360
}
302361

362+
impl<T> RawMutPtr<T> for NonZero<*mut T> {
363+
#[inline]
364+
unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
365+
let NonZero(p) = *self;
366+
Some(&mut *p)
367+
}
368+
}
369+
303370
// Equality for pointers
304371
impl<T> PartialEq for *const T {
305372
#[inline]

0 commit comments

Comments
 (0)