use facet::Facet;
use xur_runtime::{
BuiltinType, FloatValue, IntValue, OneOf, Raise, Registry, RunResult, RuntimeError, Value,
XurBytes, XurStr, lock, one_of, with_pair,
};
#[derive(Clone, Copy, Facet)]
#[repr(C)]
pub enum Error {
OutOfRange,
Utf8,
BadHex,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Error::OutOfRange => "offset or range out of bounds",
Error::Utf8 => "not valid UTF-8",
Error::BadHex => "invalid hex string",
})
}
}
one_of! {
enum ByteNumber {
Int(i128),
Float(f64),
}
}
fn to_num<T: TryFrom<Number>>(n: ByteNumber, name: &str) -> RunResult<T> {
let (number, shown) = match n {
ByteNumber::Int(i) => (Number::Int(i), i.to_string()),
ByteNumber::Float(f) => (Number::Float(f), f.to_string()),
};
T::try_from(number).map_err(|_| RuntimeError::new(format!("{shown} does not fit in `{name}`")))
}
fn read_at<const N: usize>(bytes: &[u8], offset: usize) -> RunResult<[u8; N]> {
bytes
.get(offset..offset + N)
.and_then(|slice| slice.try_into().ok())
.ok_or_else(|| out_of_range(offset, N, bytes.len()))
}
fn write_at(bytes: &mut [u8], offset: usize, raw: &[u8]) -> RunResult<()> {
let len = bytes.len();
let target = bytes
.get_mut(offset..offset + raw.len())
.ok_or_else(|| out_of_range(offset, raw.len(), len))?;
target.copy_from_slice(raw);
Ok(())
}
pub(crate) fn register(registry: &Registry) {
registry.module("std::bytes").ty::<Error>("Error");
registry
.module("std::bytes")
.named_function("zeroed", &["len"], |len: usize| vec![0u8; len])
.named_function("from_list", &["bytes"], |bytes: Vec<u8>| bytes)
.named_function("from_hex", &["hex"], |hex: XurStr| from_hex(&hex));
registry
.builtin(BuiltinType::Str)
.method("to_bytes", |s: &str| s.as_bytes().to_vec())
.method("from_hex", |s: &str| from_hex(s));
let mut methods = registry.builtin(BuiltinType::Bytes);
methods
.method("len", |bytes: &[u8]| -> i64 { bytes.len() as i64 })
.method("is_empty", |bytes: &[u8]| -> bool { bytes.is_empty() })
.named_method_mut("push", &["byte"], |bytes: &mut Vec<u8>, byte: i64| {
bytes.push(byte as u8);
})
.named_method("extend", &["other"], |bytes: &XurBytes, other: XurBytes| {
let other = lock(&other.0).clone();
lock(&bytes.0).extend(other);
})
.named_method(
"find",
&["needle"],
|bytes: &XurBytes, needle: XurBytes| -> Option<i64> {
with_pair(&bytes.0, &needle.0, |hay, needle| {
find(hay, needle).map(|at| at as i64)
})
},
)
.named_method(
"starts_with",
&["prefix"],
|bytes: &XurBytes, prefix: XurBytes| -> bool {
with_pair(&bytes.0, &prefix.0, |bytes, prefix| {
bytes.starts_with(&prefix[..])
})
},
)
.method("to_hex", |bytes: &[u8]| -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
})
.method("decode", |bytes: &[u8]| -> Result<String, Error> {
String::from_utf8(bytes.to_vec()).map_err(|_| Error::Utf8)
})
.method("to_list", |bytes: &[u8]| -> Vec<i64> {
bytes.iter().map(|&b| b as i64).collect()
})
.named_method(
"get",
&["index"],
|bytes: &[u8], index: i64| -> Option<i64> {
usize::try_from(index)
.ok()
.and_then(|i| bytes.get(i).copied())
.map(|b| b as i64)
},
)
.named_method(
"slice",
&["start", "end"],
|bytes: &[u8], start: i64, end: i64| -> Result<Vec<u8>, Error> {
let s = usize::try_from(start).map_err(|_| Error::OutOfRange)?;
let e = usize::try_from(end).map_err(|_| Error::OutOfRange)?;
if s > e || e > bytes.len() {
return Err(Error::OutOfRange);
}
Ok(bytes[s..e].to_vec())
},
);
macro_rules! numbers {
($($ty:ty: $read:literal, $write:literal, $from:ident, $to:ident;)*) => {$(
methods
.method($read, |bytes: &XurBytes, offset: usize| -> Raise<Value> {
Raise((|| {
let raw = read_at::<{ size_of::<$ty>() }>(&lock(&bytes.0), offset)?;
Ok(<$ty>::$from(raw).into_xur())
})())
})
.method(
$write,
|bytes: &XurBytes, offset: usize, value: OneOf<ByteNumber>| -> Raise<()> {
Raise((|| {
let value: $ty = to_num(value.0, stringify!($ty))?;
write_at(&mut lock(&bytes.0), offset, &value.$to())
})())
},
);
)*};
}
numbers! {
u8: "read_u8", "write_u8", from_le_bytes, to_le_bytes;
i8: "read_i8", "write_i8", from_le_bytes, to_le_bytes;
u16: "read_u16_le", "write_u16_le", from_le_bytes, to_le_bytes;
u16: "read_u16_be", "write_u16_be", from_be_bytes, to_be_bytes;
i16: "read_i16_le", "write_i16_le", from_le_bytes, to_le_bytes;
i16: "read_i16_be", "write_i16_be", from_be_bytes, to_be_bytes;
u32: "read_u32_le", "write_u32_le", from_le_bytes, to_le_bytes;
u32: "read_u32_be", "write_u32_be", from_be_bytes, to_be_bytes;
i32: "read_i32_le", "write_i32_le", from_le_bytes, to_le_bytes;
i32: "read_i32_be", "write_i32_be", from_be_bytes, to_be_bytes;
u64: "read_u64_le", "write_u64_le", from_le_bytes, to_le_bytes;
u64: "read_u64_be", "write_u64_be", from_be_bytes, to_be_bytes;
i64: "read_i64_le", "write_i64_le", from_le_bytes, to_le_bytes;
i64: "read_i64_be", "write_i64_be", from_be_bytes, to_be_bytes;
f32: "read_f32_le", "write_f32_le", from_le_bytes, to_le_bytes;
f32: "read_f32_be", "write_f32_be", from_be_bytes, to_be_bytes;
f64: "read_f64_le", "write_f64_le", from_le_bytes, to_le_bytes;
f64: "read_f64_be", "write_f64_be", from_be_bytes, to_be_bytes;
}
}
pub(crate) fn from_hex(hex: &str) -> Result<Vec<u8>, Error> {
let digits: Vec<char> = hex.chars().filter(|c| !c.is_whitespace()).collect();
if !digits.len().is_multiple_of(2) {
return Err(Error::BadHex);
}
digits
.chunks(2)
.map(|pair| {
let pair: String = pair.iter().collect();
u8::from_str_radix(&pair, 16).map_err(|_| Error::BadHex)
})
.collect()
}
fn out_of_range(start: usize, len: usize, total: usize) -> RuntimeError {
RuntimeError::new(format!(
"{len} byte(s) at offset {start} are out of range for {total} byte(s)"
))
}
trait NumberValue {
fn into_xur(self) -> Value;
}
macro_rules! int_number_value {
($($t:ty),*) => {$(
impl NumberValue for $t {
fn into_xur(self) -> Value { Value::Int(IntValue::from(self)) }
}
)*};
}
int_number_value!(u8, i8, u16, i16, u32, i32, u64, i64);
impl NumberValue for f32 {
fn into_xur(self) -> Value {
Value::Float(FloatValue::F32(self))
}
}
impl NumberValue for f64 {
fn into_xur(self) -> Value {
Value::Float(FloatValue::F64(self))
}
}
enum Number {
Int(i128),
Float(f64),
}
macro_rules! number_conversions {
(ints: $($int:ty),*; floats: $($float:ty),*) => {
$(
impl From<$int> for Number {
fn from(value: $int) -> Self {
Self::Int(value.into())
}
}
impl TryFrom<Number> for $int {
type Error = ();
fn try_from(number: Number) -> Result<Self, ()> {
match number {
Number::Int(i) => i.try_into().map_err(|_| ()),
Number::Float(_) => Err(()),
}
}
}
)*
$(
impl From<$float> for Number {
fn from(value: $float) -> Self {
Self::Float(value.into())
}
}
impl TryFrom<Number> for $float {
type Error = ();
fn try_from(number: Number) -> Result<Self, ()> {
match number {
Number::Float(f) => Ok(f as $float),
Number::Int(_) => Err(()),
}
}
}
)*
};
}
number_conversions!(ints: u8, i8, u16, i16, u32, i32, u64, i64; floats: f32, f64);
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() {
return Some(0);
}
haystack
.windows(needle.len())
.position(|window| window == needle)
}