How to efficiently check if two unsigned integers are close enough

My current implement is

fn check(a:u8, b:u8, limit:u8) -> bool {
  ((a as i16) - (b as i16)).abs() as u8 < limit 
}

Can this be more efficient

a.abs_diff(b) < limit will compile to almost the same machine code, so it won't be more efficient (the optimizer is very good at recognizing patterns in arithmetic), but it is more concise and clear.

abs_diff() documentation

Comparing the two results with Compiler Explorer

8 Likes

What is the larger context of your question? Are you doing many of these tests at once? Are any of the arguments constant?

I'm not sure this is more efficient, but it sticks to u8:

fn check(a: u8, b: u8, limit: u8) -> bool {
  if limit == 0 {
    false
  } else {
    let limit2 = limit - 1;
    a <= b.saturating_add(limit2) && b <= a.saturating_add(limit2)
  }
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.