Skip to content

Commit d1e091a

Browse files
committed
Add Ptr::to_option method
1 parent 3a323c1 commit d1e091a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/libcore/ptr.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use cast;
1414
use libc;
1515
use libc::{c_void, size_t};
16+
use option::{Option, Some, None};
1617
use sys;
1718

1819
#[cfg(not(test))] use cmp::{Eq, Ord};
@@ -209,6 +210,7 @@ pub unsafe fn array_each<T>(arr: **T, cb: &fn(*T)) {
209210
pub trait Ptr<T> {
210211
fn is_null(&const self) -> bool;
211212
fn is_not_null(&const self) -> bool;
213+
fn to_option(&const self) -> Option<T>;
212214
fn offset(&self, count: uint) -> Self;
213215
}
214216

@@ -222,6 +224,14 @@ impl<T> Ptr<T> for *T {
222224
#[inline(always)]
223225
fn is_not_null(&const self) -> bool { is_not_null(*self) }
224226

227+
/// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`.
228+
#[inline(always)]
229+
fn to_option(&const self) -> Option<T> {
230+
if self.is_null() { None } else {
231+
Some(unsafe { **self })
232+
}
233+
}
234+
225235
/// Calculates the offset from a pointer.
226236
#[inline(always)]
227237
fn offset(&self, count: uint) -> *T { offset(*self, count) }
@@ -237,6 +247,14 @@ impl<T> Ptr<T> for *mut T {
237247
#[inline(always)]
238248
fn is_not_null(&const self) -> bool { is_not_null(*self) }
239249

250+
/// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`.
251+
#[inline(always)]
252+
fn to_option(&const self) -> Option<T> {
253+
if self.is_null() { None } else {
254+
Some(unsafe { **self })
255+
}
256+
}
257+
240258
/// Calculates the offset from a mutable pointer.
241259
#[inline(always)]
242260
fn offset(&self, count: uint) -> *mut T { mut_offset(*self, count) }
@@ -423,6 +441,21 @@ pub mod ptr_tests {
423441
assert!(mq.is_not_null());
424442
}
425443

444+
#[test]
445+
#[allow(unused_mut)]
446+
fn test_to_option() {
447+
let p: *int = null();
448+
assert_eq!(p.to_option(), None);
449+
450+
let q: *int = &2;
451+
assert_eq!(q.to_option(), Some(2));
452+
453+
let p: *mut int = mut_null();
454+
assert_eq!(p.to_option(), None);
455+
456+
let q: *mut int = &mut 2;
457+
assert_eq!(q.to_option(), Some(2));
458+
}
426459

427460
#[test]
428461
fn test_ptr_array_each_with_len() {

0 commit comments

Comments
 (0)