use std::sync::Arc;
use facet::Facet;
use xur_runtime::{Context, RunResult, RuntimeError, Value};
use crate::{error_text, result};
pub(super) fn open_bytes<T, E>(
cx: &mut dyn Context,
args: &[Value],
parse: impl FnOnce(&'static [u8]) -> Result<T, E>,
) -> RunResult<Value>
where
T: Facet<'static> + Send + 'static,
E: std::fmt::Display,
{
let [Value::Bytes(bytes)] = args else {
return Err(RuntimeError::new("expected bytes"));
};
let data = xur_runtime::lock(bytes).clone();
parse_object(cx, data, parse)
}
pub(super) fn open_path<T, E>(
cx: &mut dyn Context,
args: &[Value],
parse: impl FnOnce(&'static [u8]) -> Result<T, E>,
) -> RunResult<Value>
where
T: Facet<'static> + Send + 'static,
E: std::fmt::Display,
{
let [Value::Str(path)] = args else {
return Err(RuntimeError::new("expected a path string"));
};
match std::fs::read(&**path) {
Ok(data) => parse_object(cx, data, parse),
Err(error) => Ok(result(cx, Err(error_text(error)))),
}
}
pub(super) fn parse_object<T, E>(
cx: &dyn Context,
data: Vec<u8>,
parse: impl FnOnce(&'static [u8]) -> Result<T, E>,
) -> RunResult<Value>
where
T: Facet<'static> + Send + 'static,
E: std::fmt::Display,
{
let data: Arc<Vec<u8>> = Arc::new(data);
let bytes: &'static [u8] = unsafe { &*(data.as_slice() as *const [u8]) };
let parsed = match parse(bytes) {
Ok(value) => cx.registry().borrowing_object(value, data)?,
Err(error) => return Ok(result(cx, Err(error_text(error)))),
};
Ok(result(cx, Ok(parsed)))
}
pub(super) fn borrow_from<T>(
cx: &dyn Context,
value: T,
keep_alive: Arc<dyn std::any::Any + Send + Sync>,
) -> RunResult<Value>
where
T: Facet<'static> + Send + 'static,
{
cx.registry().borrowing_object(value, keep_alive)
}
pub(super) fn keep_alive_of(value: &Value) -> RunResult<Arc<dyn std::any::Any + Send + Sync>> {
match value {
Value::Native(object) => object
.keep_alive()
.ok_or_else(|| RuntimeError::new("this value does not own any bytes")),
_ => Err(RuntimeError::new("expected a parsed file")),
}
}