abs_sub() for integral values too?


#1

To solve a little problem I wrote this function:

fn distance((r0, c0): (usize, usize), (r1, c1): (usize, usize)) -> f64 {
    ((c0 - c1) as f64).hypot((r0 - r1) as f64)
}

But I can’t subtract those usize values directly because sometimes it causes underflow, so I am using:

fn distance((r0, c0): (usize, usize), (r1, c1): (usize, usize)) -> f64 {
    (c0 as f64 - c1 as f64).hypot(r0 as f64 - r1 as f64)
}

But I think I’d prefer to write (I am not sure but I think this could be faster):

fn distance((r0, c0): (usize, usize), (r1, c1): (usize, usize)) -> f64 {
    (c0.abs_sub(c1) as f64).hypot(r0.abs_sub(r1) as f64)
}

Is it a good idea to have abs_sub() for integral values too?


#2

{f32,f64}::abs_sub doesn’t do what you expect.


#3

Oh, I see, and sorry, bad naming indeed.

So what’s the reasonable way to write that little function? I can use max/min:

fn distance((r0, c0): (usize, usize), (r1, c1): (usize, usize)) -> f64 {
    let dc = (max(c0, c1) - min(c0, c1)).pow(2);
    let dr = (max(r0, r1) - min(r0, r1)).pow(2);
    ((dc + dr) as f64).sqrt()
}

Is a function that performs abs(x-y) safely still be handy for unsigned integrals?