File size: 804 Bytes
63f41a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//! 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
}