13
13
use cast;
14
14
use libc;
15
15
use libc:: { c_void, size_t} ;
16
+ use option:: { Option , Some , None } ;
16
17
use sys;
17
18
18
19
#[ cfg( not( test) ) ] use cmp:: { Eq , Ord } ;
@@ -209,6 +210,7 @@ pub unsafe fn array_each<T>(arr: **T, cb: &fn(*T)) {
209
210
pub trait Ptr < T > {
210
211
fn is_null ( & const self ) -> bool ;
211
212
fn is_not_null ( & const self ) -> bool ;
213
+ fn to_option ( & const self ) -> Option < T > ;
212
214
fn offset ( & self , count : uint ) -> Self ;
213
215
}
214
216
@@ -222,6 +224,14 @@ impl<T> Ptr<T> for *T {
222
224
#[ inline( always) ]
223
225
fn is_not_null ( & const self ) -> bool { is_not_null ( * self ) }
224
226
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
+
225
235
/// Calculates the offset from a pointer.
226
236
#[ inline( always) ]
227
237
fn offset ( & self , count : uint ) -> * T { offset ( * self , count) }
@@ -237,6 +247,14 @@ impl<T> Ptr<T> for *mut T {
237
247
#[ inline( always) ]
238
248
fn is_not_null ( & const self ) -> bool { is_not_null ( * self ) }
239
249
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
+
240
258
/// Calculates the offset from a mutable pointer.
241
259
#[ inline( always) ]
242
260
fn offset ( & self , count : uint ) -> * mut T { mut_offset ( * self , count) }
@@ -423,6 +441,21 @@ pub mod ptr_tests {
423
441
assert ! ( mq. is_not_null( ) ) ;
424
442
}
425
443
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
+ }
426
459
427
460
#[ test]
428
461
fn test_ptr_array_each_with_len ( ) {
0 commit comments