Functional Weave
Code in Rust

math.clamp@1.0.0

impl/rust.rs

965 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

/// Clamp `value` to the inclusive range `min..=max`.
///
/// Swapped bounds panic rather than answering `min` for everything, which is
/// what `value.max(min).min(max)` would quietly do.
///
/// # Panics
/// Panics if `min` is greater than `max`.
pub fn clamp(value: i64, min: i64, max: i64) -> i64 {
    if min > max {
        panic!("min must not be greater than max (min {}, max {})", min, max);
    }
    if value < min {
        min
    } else if value > max {
        max
    } else {
        value
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    // Refuse what the typed signature cannot hold, with the wording TypeScript
    // and Python use, rather than let the conversion below quietly change it.
    if (0..3).any(|i| matches!(args[i], Value::Float(f) if f.fract() != 0.0)) {
        panic!("clamp operates on integers only");
    }
    Value::Int(clamp(args[0].as_i64(), args[1].as_i64(), args[2].as_i64()))
}