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

Implement TryFrom for float to integer types #47857

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
58 changes: 58 additions & 0 deletions src/libcore/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2998,6 +2998,37 @@ impl From<Infallible> for TryFromIntError {
}
}

/// The error type returned when a checked float type conversion fails.
#[unstable(feature = "try_from", issue = "33417")]
#[derive(Debug, Copy, Clone)]
pub struct TryFromFloatError(());

impl TryFromFloatError {
#[unstable(feature = "float_error_internals",
reason = "available through Error trait and this method should \
not be exposed publicly",
issue = "0")]
#[doc(hidden)]
pub fn __description(&self) -> &str {
"out of range float type conversion attempted"
}
}

#[unstable(feature = "try_from", issue = "33417")]
impl fmt::Display for TryFromFloatError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.__description().fmt(fmt)
}
}

#[unstable(feature = "try_from", issue = "33417")]
impl From<Infallible> for TryFromFloatError {
fn from(infallible: Infallible) -> TryFromFloatError {
match infallible {
}
}
}

// no possible bounds violation
macro_rules! try_from_unbounded {
($source:ty, $($target:ty),*) => {$(
Expand Down Expand Up @@ -3072,6 +3103,28 @@ macro_rules! try_from_both_bounded {
)*}
}

// float to integer
macro_rules! try_from_float {
($source:ty, $($target:ty),*) => {$(
#[unstable(feature = "try_from", issue = "33417")]
impl TryFrom<$source> for $target {
type Error = TryFromFloatError;

#[inline]
fn try_from(u: $source) -> Result<$target, TryFromFloatError> {
let c = u as $target;

// is a conversion back identical to the original value?
if c as $source != u {
return Err(TryFromFloatError(()));
}

Ok(c)
}
}
)*}
}

macro_rules! rev {
($mac:ident, $source:ty, $($target:ty),*) => {$(
$mac!($target, $source);
Expand Down Expand Up @@ -3111,6 +3164,11 @@ try_from_both_bounded!(i128, u64, u32, u16, u8);
try_from_upper_bounded!(usize, isize);
try_from_lower_bounded!(isize, usize);

try_from_float!(f64, u8, u16, u32, u64, u128);
try_from_float!(f64, i8, i16, i32, i64, i128);
try_from_float!(f32, u8, u16, u32, u64, u128);
try_from_float!(f32, i8, i16, i32, i64, i128);

#[cfg(target_pointer_width = "16")]
mod ptr_try_from_impls {
use super::TryFromIntError;
Expand Down
2 changes: 1 addition & 1 deletion src/libcore/tests/num/i16.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

int_module!(i16, i16);
int_module!(i16, i16, 16);
2 changes: 1 addition & 1 deletion src/libcore/tests/num/i32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

int_module!(i32, i32);
int_module!(i32, i32, 32);
2 changes: 1 addition & 1 deletion src/libcore/tests/num/i64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

int_module!(i64, i64);
int_module!(i64, i64, 64);
2 changes: 1 addition & 1 deletion src/libcore/tests/num/i8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

int_module!(i8, i8);
int_module!(i8, i8, 8);
35 changes: 34 additions & 1 deletion src/libcore/tests/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

macro_rules! int_module { ($T:ident, $T_i:ident) => (
macro_rules! int_module { ($T:ident, $T_i:ident, $w:expr) => (
#[cfg(test)]
mod tests {
use core::$T_i::*;
use core::isize;
use core::ops::{Shl, Shr, Not, BitXor, BitAnd, BitOr};
use core::mem;
use core::convert::TryInto;

use num;

Expand Down Expand Up @@ -214,6 +215,38 @@ mod tests {
assert_eq!(r.pow(2), 4 as $T);
assert_eq!(r.pow(3), -8 as $T);
}

#[test]
fn test_f32_try_from() {
for n in &[1f32, 2f32, 3f32] {
let v = 2f32.powi(i32::min(24, $w - 1)) - n;
assert!((v.try_into() as Result<$T, _>).is_ok());
}

for n in &[0f32, 1f32, 2f32] {
let v = -2f32.powi(i32::min(24, $w - 1)) + n;
assert!((v.try_into() as Result<$T, _>).is_ok());
}

assert!((2f32.powi($w - 1).try_into() as Result<$T, _>).is_err());
assert!(((-2f32.powi($w)).try_into() as Result<$T, _>).is_err());
}

#[test]
fn test_f64_try_from() {
for n in &[1f64, 2f64, 3f64] {
let v = 2f64.powi(i32::min(53, $w - 1)) - n;
assert!((v.try_into() as Result<$T, _>).is_ok());
}

for n in &[0f64, 1f64, 2f64] {
let v = -2f64.powi(i32::min(53, $w - 1)) + n;
assert!((v.try_into() as Result<$T, _>).is_ok());
}

assert!((2f64.powi($w - 1).try_into() as Result<$T, _>).is_err());
assert!(((-2f64.powi($w)).try_into() as Result<$T, _>).is_err());
}
}

)}
2 changes: 1 addition & 1 deletion src/libcore/tests/num/u16.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

uint_module!(u16, u16);
uint_module!(u16, u16, 16);
2 changes: 1 addition & 1 deletion src/libcore/tests/num/u32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

uint_module!(u32, u32);
uint_module!(u32, u32, 32);
2 changes: 1 addition & 1 deletion src/libcore/tests/num/u64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

uint_module!(u64, u64);
uint_module!(u64, u64, 64);
2 changes: 1 addition & 1 deletion src/libcore/tests/num/u8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

uint_module!(u8, u8);
uint_module!(u8, u8, 8);
23 changes: 22 additions & 1 deletion src/libcore/tests/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

macro_rules! uint_module { ($T:ident, $T_i:ident) => (
macro_rules! uint_module { ($T:ident, $T_i:ident, $w:expr) => (
#[cfg(test)]
mod tests {
use core::$T_i::*;
use num;
use core::ops::{BitOr, BitAnd, BitXor, Shl, Shr, Not};
use std::str::FromStr;
use std::mem;
use core::convert::TryInto;

#[test]
fn test_overflows() {
Expand Down Expand Up @@ -154,5 +155,25 @@ mod tests {
assert_eq!($T::from_str_radix("Z", 10).ok(), None::<$T>);
assert_eq!($T::from_str_radix("_", 2).ok(), None::<$T>);
}

#[test]
fn test_f32_try_from() {
for n in &[1f32, 2f32, 3f32] {
let v = 2f32.powi(i32::min(24, $w)) - n;
assert!((v.try_into() as Result<$T, _>).is_ok());
}

assert!((2f32.powi($w).try_into() as Result<$T, _>).is_err());
}

#[test]
fn test_f64_try_from() {
for n in &[1f64, 2f64, 3f64] {
let v = 2f64.powi(i32::min(53, $w)) - n;
assert!((v.try_into() as Result<$T, _>).is_ok());
}

assert!((2f64.powi($w).try_into() as Result<$T, _>).is_err());
}
}
)}