Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a safe way to use NonZero #27573

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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