align / code /bugfind /smoke /tiny /src /lib.rs
viai957's picture
Add files using upload-large-folder tool
63f41a6 verified
Raw History Blame Contribute Delete
804 Bytes
//! Smoke-test crate: pure integer functions, one with a seeded overflow bug.
/// Correct: |a - b| without overflow.
pub fn abs_diff(a: u32, b: u32) -> u32 {
if a >= b { a - b } else { b - a }
}
/// Correct: saturating add via a wider type.
pub fn sat_add_u8(a: u8, b: u8) -> u8 {
let s = (a as u16) + (b as u16);
if s > 255 { 255 } else { s as u8 }
}
/// Greatest common divisor (Euclid).
pub fn gcd(a: u32, b: u32) -> u32 {
let mut x = a;
let mut y = b;
while y != 0 {
let t = x % y;
x = y;
y = t;
}
x
}
/// BUG (seeded): intended `floor((a + b) / 2)`, but `a + b` overflows u32 for large inputs
/// (panics in debug, wraps in release). Correct form: `a / 2 + b / 2 + (a & b & 1)`.
pub fn avg_buggy(a: u32, b: u32) -> u32 {
(a + b) / 2
}