Clamp Keeps Values In Bounds

Keep numbers inside safe bounds with f64::clamp and Ord::clamp so sensor readings and queue depths never escape their configured ranges.

RustData Integrity

Code

rustsnippet
19 lines
fn clamp_reading(raw: f64) -> f64 {
    // 传感器漂移产生的越界值统一压回 [0.0, 100.0] bounds
    raw.clamp(0.0, 100.0)
}

fn clamp_queue_depth(want: i32, cap: i32) -> i32 {
    // 整数侧用 Ord::clamp,同样要求 min <= max,否则 panic
    want.clamp(0, cap)
}

fn main() {
    for raw in [-3.5, 42.0, 128.9] {
        println!("raw {raw} -> {}", clamp_reading(raw));
    }

    println!("depth 17 cap 8 -> {}", clamp_queue_depth(17, 8));
    println!("depth -1 cap 8 -> {}", clamp_queue_depth(-1, 8));
    println!("depth 5 cap 8  -> {}", clamp_queue_depth(5, 8));
}

What the snippet does

All of the logic lives in the functions clamp_reading, clamp_queue_depth and main.

for raw in [-3.5, 42.0, 128.9] is the loop doing the per-item work.

What to watch for

  • No package installation, no environment variables, no setup steps.

Using it

The main signature is fn clamp_reading(raw: f64) -> f64

The demo output is labeled (raw, depth 17 cap 8 ->, depth -1 cap 8 ->), so every printed line has a specific operation behind it.

The entry point wires clamp_reading and clamp_queue_depth together — run it once and the whole demo flows.

Key statements

fn clamp_queue_depth(want: i32, cap: i32) -> i32 {
    // 整数侧用 Ord::clamp,同样要求 min <= max,否则 panic
    want.clamp(0, cap)
}
fn clamp_reading(raw: f64) -> f64 {
    // 传感器漂移产生的越界值统一压回 [0.0, 100.0] bounds
    raw.clamp(0.0, 100.0)
}

Interactive Tools for This Topic

FAQ

What does Clamp Keeps Values In Bounds print when run?
The script runs standalone; its 4 labeled outputs include `raw`, `depth 17 cap 8 ->`, `depth -1 cap 8 ->`.