Functional Weave
Code in TypeScript

charts.color@1.0.1

impl/rust/to_hex.rs

821 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

const HEX: &[u8; 16] = b"0123456789abcdef";

fn pair(value: i64) -> String {
    if !(0..=255).contains(&value) {
        panic!("rgb channels must be whole numbers from 0 to 255, received {}", value);
    }
    let mut s = String::new();
    s.push(HEX[(value / 16) as usize] as char);
    s.push(HEX[(value % 16) as usize] as char);
    s
}

/// Lowercase "#rrggbb", the form every renderer accepts.
///
/// # Panics
/// Panics if a channel is outside 0..=255.
pub fn to_hex(rgb: &Rgb) -> String {
    format!("#{}{}{}", pair(rgb.r), pair(rgb.g), pair(rgb.b))
}

pub fn rgb_from_value(v: &Value) -> Rgb {
    Rgb { r: v.get("r").as_i64(), g: v.get("g").as_i64(), b: v.get("b").as_i64() }
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&to_hex(&rgb_from_value(&args[0])))
}