use rune::alloc::fmt::TryWrite;
use rune::alloc::{String, Vec};
use rune::runtime::{Bytes, Formatter, Value, VmResult};
use rune::{vm_write, Any, ContextError, Module};
#[rune::module(::json)]
pub fn module(_stdio: bool) -> Result<Module, ContextError> {
let mut module = Module::from_meta(self::module_meta)?;
module.ty::<Error>()?;
module.function_meta(Error::display)?;
module.function_meta(Error::debug)?;
module.function_meta(from_bytes)?;
module.function_meta(from_string)?;
module.function_meta(to_string)?;
module.function_meta(to_bytes)?;
Ok(module)
}
#[derive(Any)]
#[rune(item = ::json)]
struct Error {
error: serde_json::Error,
}
impl Error {
#[rune::function(protocol = DISPLAY_FMT)]
pub(crate) fn display(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{}", self.error)
}
#[rune::function(protocol = DEBUG_FMT)]
pub(crate) fn debug(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{:?}", self.error)
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self { error }
}
}
#[rune::function]
fn from_bytes(bytes: &[u8]) -> Result<Value, Error> {
Ok(serde_json::from_slice(bytes)?)
}
#[rune::function]
fn from_string(string: &str) -> Result<Value, Error> {
Ok(serde_json::from_str(string)?)
}
#[rune::function(vm_result)]
fn to_string(value: Value) -> Result<String, Error> {
Ok(String::try_from(serde_json::to_string(&value)?).vm?)
}
#[rune::function(vm_result)]
fn to_bytes(value: Value) -> Result<Bytes, Error> {
Ok(Bytes::from_vec(
Vec::try_from(serde_json::to_vec(&value)?).vm?,
))
}