use crate::stdlib::common::arg;
use fusevm::Value;
fn c_alpha(b: u8) -> bool {
b.is_ascii_alphabetic()
}
fn c_digit(b: u8) -> bool {
b.is_ascii_digit()
}
fn c_alnum(b: u8) -> bool {
b.is_ascii_alphanumeric()
}
fn c_upper(b: u8) -> bool {
b.is_ascii_uppercase()
}
fn c_lower(b: u8) -> bool {
b.is_ascii_lowercase()
}
fn c_xdigit(b: u8) -> bool {
b.is_ascii_hexdigit()
}
fn c_space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
}
fn c_cntrl(b: u8) -> bool {
b.is_ascii_control()
}
fn c_graph(b: u8) -> bool {
b.is_ascii_graphic()
}
fn c_print(b: u8) -> bool {
b == b' ' || b.is_ascii_graphic()
}
fn c_punct(b: u8) -> bool {
b.is_ascii_punctuation()
}
fn classify(args: &[Value], pred: fn(u8) -> bool) -> Value {
let bytes: Vec<u8> = match arg(args, 0) {
Value::Int(n) => {
if (-128..=255).contains(&n) {
let code = if n < 0 { (n + 256) as u8 } else { n as u8 };
return Value::bool(pred(code));
}
n.to_string().into_bytes()
}
Value::Str(s) => s.as_bytes().to_vec(),
_ => return Value::bool(false),
};
if bytes.is_empty() {
return Value::bool(false);
}
Value::bool(bytes.iter().all(|&b| pred(b)))
}
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
let pred: fn(u8) -> bool = match name {
"ctype_alpha" => c_alpha,
"ctype_digit" => c_digit,
"ctype_alnum" => c_alnum,
"ctype_space" => c_space,
"ctype_upper" => c_upper,
"ctype_lower" => c_lower,
"ctype_punct" => c_punct,
"ctype_xdigit" => c_xdigit,
"ctype_cntrl" => c_cntrl,
"ctype_graph" => c_graph,
"ctype_print" => c_print,
_ => return None,
};
Some(Ok(classify(args, pred)))
}