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

Overflow on absolute comparison of signed integers #52

Open
pcpthm opened this issue Sep 24, 2019 · 3 comments
Open

Overflow on absolute comparison of signed integers #52

pcpthm opened this issue Sep 24, 2019 · 3 comments

Comments

@pcpthm
Copy link

pcpthm commented Sep 24, 2019

fn main() {
    approx::abs_diff_ne!(std::i32::MAX, std::i32::MIN);
}

Expected behavior: Runs fine.
Actual behavior: thread 'main' panicked at 'attempt to subtract with overflow'.

@pcpthm pcpthm changed the title Overflow on signed integers Overflow on absolute comparison of signed integers Sep 24, 2019
@pcpthm
Copy link
Author

pcpthm commented Sep 24, 2019

More corner case:

approx::abs_diff_ne!(-1, std::i32::MAX)

won't overflow on subtraction but will be overflow on abs

@brendanzab
Copy link
Owner

Oh huh, that's interesting. We actually implement these comparisons for integers?

@brendanzab
Copy link
Owner

Right, seems like it's here:

macro_rules! impl_unsigned_abs_diff_eq {
($T:ident, $default_epsilon:expr) => {
impl AbsDiffEq for $T {
type Epsilon = $T;
#[inline]
fn default_epsilon() -> $T {
$default_epsilon
}
#[inline]
fn abs_diff_eq(&self, other: &$T, epsilon: $T) -> bool {
(if self > other {
self - other
} else {
other - self
}) <= epsilon
}
}
};
}
impl_unsigned_abs_diff_eq!(u8, 0);
impl_unsigned_abs_diff_eq!(u16, 0);
impl_unsigned_abs_diff_eq!(u32, 0);
impl_unsigned_abs_diff_eq!(u64, 0);
impl_unsigned_abs_diff_eq!(usize, 0);
macro_rules! impl_signed_abs_diff_eq {
($T:ident, $default_epsilon:expr) => {
impl AbsDiffEq for $T {
type Epsilon = $T;
#[inline]
fn default_epsilon() -> $T {
$default_epsilon
}
#[inline]
fn abs_diff_eq(&self, other: &$T, epsilon: $T) -> bool {
$T::abs(self - other) <= epsilon
}
}
};
}
impl_signed_abs_diff_eq!(i8, 0);
impl_signed_abs_diff_eq!(i16, 0);
impl_signed_abs_diff_eq!(i32, 0);
impl_signed_abs_diff_eq!(i64, 0);
impl_signed_abs_diff_eq!(isize, 0);
impl_signed_abs_diff_eq!(f32, f32::EPSILON);
impl_signed_abs_diff_eq!(f64, f64::EPSILON);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants