use xur_runtime::registry::XurType;
use xur_runtime::{BuiltinType, Registry, RunResult, RuntimeError, Value};
pub(crate) fn register(registry: &Registry) {
registry
.module("std::ptr")
.raw_function_returns_xur("null", XurType::PTR, |_cx, _args| Ok(Value::Ptr(0)))
.named_raw_function_returns_xur("from_int", &["addr"], XurType::PTR, |_cx, args| {
let [Value::Int(addr)] = args else {
return Err(RuntimeError::new("`from_int` takes an integer"));
};
Ok(Value::Ptr(addr.to_u64().ok_or_else(|| {
RuntimeError::new(format!("`from_int`: {} does not fit in u64", addr))
})?))
});
registry
.builtin(BuiltinType::Ptr)
.raw_function_returns::<i64>("to_int", |_cx, args| {
let [Value::Ptr(addr)] = args else {
return Err(RuntimeError::new("`to_int` takes a pointer"));
};
Ok(Value::Int((*addr).into()))
})
.raw_function_returns::<bool>("is_null", |_cx, args| {
let [Value::Ptr(addr)] = args else {
return Err(RuntimeError::new("`is_null` takes a pointer"));
};
Ok(Value::Bool(*addr == 0))
})
.raw_function_returns_xur("offset", XurType::PTR, |_cx, args| {
let [Value::Ptr(addr), Value::Int(n)] = args else {
return Err(RuntimeError::new("`offset` takes an integer"));
};
Ok(Value::Ptr(addr.wrapping_add(n.to_i128() as u64)))
})
.raw_function_returns::<String>("to_hex", |_cx, args| -> RunResult<Value> {
let [Value::Ptr(addr)] = args else {
return Err(RuntimeError::new("`to_hex` takes a pointer"));
};
Ok(Value::str(&format!("0x{addr:x}")))
});
}