]> git.lizzy.rs Git - rust.git/commitdiff
Add Ptr::to_option method
authorBrendan Zabarauskas <bjzaba@yahoo.com.au>
Sun, 19 May 2013 04:08:27 +0000 (14:08 +1000)
committerBrendan Zabarauskas <bjzaba@yahoo.com.au>
Sun, 19 May 2013 04:08:27 +0000 (14:08 +1000)
src/libcore/ptr.rs

index e116dc01943109ce9d8185ab21d6987fa14973b9..6254d3349d3d9df6b96d17aaa149f95b630cc93e 100644 (file)
@@ -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 @@ fn is_null(&const self) -> bool { is_null(*self) }
     #[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 @@ fn is_null(&const self) -> bool { is_null(*self) }
     #[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 @@ fn test_is_null() {
         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() {