diff options
| author | Brendan Zabarauskas <bjzaba@yahoo.com.au> | 2013-05-19 14:08:27 +1000 |
|---|---|---|
| committer | Brendan Zabarauskas <bjzaba@yahoo.com.au> | 2013-05-19 14:08:27 +1000 |
| commit | d1e091a27a6ee0d32fcda0830ec5f9a7ad585d9e (patch) | |
| tree | aa6ad05ef95dc042aacc327d3ee3e643622384c7 /src | |
| parent | 3a323c1b2d755b86b1987bba3454bb2f0f92b1c8 (diff) | |
| download | rust-d1e091a27a6ee0d32fcda0830ec5f9a7ad585d9e.tar.gz rust-d1e091a27a6ee0d32fcda0830ec5f9a7ad585d9e.zip | |
Add Ptr::to_option method
Diffstat (limited to 'src')
| -rw-r--r-- | src/libcore/ptr.rs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index e116dc01943..6254d3349d3 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -13,6 +13,7 @@ use cast; use libc; use libc::{c_void, size_t}; +use option::{Option, Some, None}; use sys; #[cfg(not(test))] use cmp::{Eq, Ord}; @@ -209,6 +210,7 @@ pub unsafe fn array_each<T>(arr: **T, cb: &fn(*T)) { pub trait Ptr<T> { fn is_null(&const self) -> bool; fn is_not_null(&const self) -> bool; + fn to_option(&const self) -> Option<T>; fn offset(&self, count: uint) -> Self; } @@ -222,6 +224,14 @@ impl<T> Ptr<T> for *T { #[inline(always)] fn is_not_null(&const self) -> bool { is_not_null(*self) } + /// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`. + #[inline(always)] + fn to_option(&const self) -> Option<T> { + if self.is_null() { None } else { + Some(unsafe { **self }) + } + } + /// Calculates the offset from a pointer. #[inline(always)] fn offset(&self, count: uint) -> *T { offset(*self, count) } @@ -237,6 +247,14 @@ impl<T> Ptr<T> for *mut T { #[inline(always)] fn is_not_null(&const self) -> bool { is_not_null(*self) } + /// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`. + #[inline(always)] + fn to_option(&const self) -> Option<T> { + if self.is_null() { None } else { + Some(unsafe { **self }) + } + } + /// Calculates the offset from a mutable pointer. #[inline(always)] fn offset(&self, count: uint) -> *mut T { mut_offset(*self, count) } @@ -423,6 +441,21 @@ pub mod ptr_tests { assert!(mq.is_not_null()); } + #[test] + #[allow(unused_mut)] + fn test_to_option() { + let p: *int = null(); + assert_eq!(p.to_option(), None); + + let q: *int = &2; + assert_eq!(q.to_option(), Some(2)); + + let p: *mut int = mut_null(); + assert_eq!(p.to_option(), None); + + let q: *mut int = &mut 2; + assert_eq!(q.to_option(), Some(2)); + } #[test] fn test_ptr_array_each_with_len() { |
