Skip to content

Commit

Permalink
Add missing function to NonZero
Browse files Browse the repository at this point in the history
Add tests
Add back comments.
  • Loading branch information
Diggsey committed Aug 7, 2015
1 parent d034561 commit 32bcb0f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/libcore/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

use marker::Sized;
use ops::{CoerceUnsized, Deref};
use mem;
use option::Option;
use ptr;

/// Unsafe trait to indicate what types are usable with the NonZero struct
pub unsafe trait Zeroable {}
Expand Down Expand Up @@ -44,6 +47,20 @@ impl<T: Zeroable> NonZero<T> {
pub unsafe fn new(inner: T) -> NonZero<T> {
NonZero(inner)
}
/// Tries to create an instance of NonZero with the provided value.
/// If the value is actually "non-zero", the function will succeed,
/// returning `Some(NonZero(value))`. Otherwise, `None` will be
/// returned.
#[inline(always)]
pub fn new_option(inner: T) -> Option<NonZero<T>> {
unsafe {
// Work around the fact that `mem::transmute` will
// complain about generic types:
let result = ptr::read(&inner as *const T as *const Option<NonZero<T>>);
mem::forget(inner);
result
}
}
}

impl<T: Zeroable> Deref for NonZero<T> {
Expand Down
25 changes: 25 additions & 0 deletions src/libcoretest/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,31 @@ fn test_match_on_nonzero_option() {
}
}

#[test]
fn test_nonzero_new_option() {
let a = NonZero::new_option(42);
match a {
Some(val) => assert_eq!(*val, 42),
None => panic!("unexpected None while matching on NonZero::new_option(42)")
}

match NonZero::new_option(43) {
Some(val) => assert_eq!(*val, 43),
None => panic!("unexpected None while matching on NonZero::new_option(43)")
}

let b = NonZero::new_option(0);
match b {
Some(_) => panic!("unexpected Some(_) while matching on NonZero::new_option(0)"),
None => ()
}

match NonZero::new_option(0) {
Some(_) => panic!("unexpected Some(_) while matching on NonZero::new_option(0)"),
None => ()
}
}

#[test]
fn test_match_option_empty_vec() {
let a: Option<Vec<isize>> = Some(vec![]);
Expand Down

0 comments on commit 32bcb0f

Please sign in to comment.