xur-std 0.1.9

The standard library of the Xur language
Documentation
//! Methods of integers and floats.

use xur_runtime::{BuiltinType, Raise, Registry, RuntimeError};

pub(crate) fn register(registry: &Registry) {
    registry
        .builtin(BuiltinType::Int)
        // Overflow is an error, not a wrap (release) or a panic (debug).
        .named_function("abs", &["x"], |x: i64| -> Raise<i64> {
            Raise(
                x.checked_abs()
                    .ok_or_else(|| overflow(format!("{x}.abs()"))),
            )
        })
        .named_function("pow", &["x", "exp"], |x: i64, exp: u32| -> Raise<i64> {
            Raise(
                x.checked_pow(exp)
                    .ok_or_else(|| overflow(format!("{x}.pow({exp})"))),
            )
        })
        .named_function("min", &["x", "y"], |x: i64, y: i64| x.min(y))
        .named_function("max", &["x", "y"], |x: i64, y: i64| x.max(y))
        .named_function("to_float", &["x"], |x: i64| x as f64)
        .named_function("to_string", &["x"], |x: i64| x.to_string())
        .named_function("to_hex", &["x"], |x: i64| format!("{x:x}"));
    registry
        .builtin(BuiltinType::Float)
        .named_function("abs", &["x"], |x: f64| x.abs())
        .named_function("sqrt", &["x"], |x: f64| x.sqrt())
        .named_function("floor", &["x"], |x: f64| x.floor())
        .named_function("ceil", &["x"], |x: f64| x.ceil())
        .named_function("round", &["x"], |x: f64| x.round())
        .named_function("to_int", &["x"], |x: f64| x as i64)
        .named_function("to_string", &["x"], |x: f64| x.to_string());
}

fn overflow(what: String) -> RuntimeError {
    RuntimeError::new(format!("{what} overflows i64"))
}