use crate::function::Function;
use crate::serde_value::from_live;
use crate::value::{load_owned_arguments, load_owned_value, snapshot_value};
use crate::{Error, HostSchema, IntoRustia, OwnedValue, Result, Rustia};
use rustia_vm::{RetainedValue, Value as RawValue, ValueKind, Vm};
use std::fmt;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ValueType {
Nil,
Boolean,
Number,
String,
Table,
Function,
Userdata,
Buffer,
Vector,
}
impl ValueType {
pub const fn name(self) -> &'static str {
match self {
Self::Nil => "nil",
Self::Boolean => "boolean",
Self::Number => "number",
Self::String => "string",
Self::Table => "table",
Self::Function => "function",
Self::Userdata => "userdata",
Self::Buffer => "buffer",
Self::Vector => "vector",
}
}
}
#[derive(Clone)]
pub struct Value {
value: RetainedValue,
decision_epoch: u64,
}
impl Value {
pub(crate) fn new(value: RetainedValue, decision_epoch: u64) -> Self {
Self {
value,
decision_epoch,
}
}
pub(crate) fn retain(vm: &mut Vm, value: RawValue) -> Result<Self> {
let decision_epoch = vm.decision_epoch();
vm.retain_value(value)
.map(|value| Self::new(value, decision_epoch))
.map_err(Error::from_engine)
}
pub(crate) fn retain_many(vm: &mut Vm, values: &[RawValue]) -> Result<Vec<Self>> {
let decision_epoch = vm.decision_epoch();
vm.retain_values(values)
.map(|values| {
values
.into_iter()
.map(|value| Self::new(value, decision_epoch))
.collect()
})
.map_err(Error::from_engine)
}
pub const fn decision_epoch(&self) -> u64 {
self.decision_epoch
}
pub fn kind<C>(&self, rustia: &Rustia<C>) -> Result<ValueType>
where
C: HostSchema,
{
let value = self.raw(rustia.vm(), "value handle")?;
raw_value_type(value)
}
pub fn type_name<C>(&self, rustia: &Rustia<C>) -> Result<&'static str>
where
C: HostSchema,
{
self.kind(rustia).map(ValueType::name)
}
pub fn is_nil<C>(&self, rustia: &Rustia<C>) -> Result<bool>
where
C: HostSchema,
{
self.kind(rustia).map(|kind| kind == ValueType::Nil)
}
pub fn truthy<C>(&self, rustia: &Rustia<C>) -> Result<bool>
where
C: HostSchema,
{
self.raw(rustia.vm(), "value handle").map(RawValue::truthy)
}
pub fn as_boolean<C>(&self, rustia: &Rustia<C>) -> Result<Option<bool>>
where
C: HostSchema,
{
self.raw(rustia.vm(), "value handle").map(RawValue::as_bool)
}
pub fn as_number<C>(&self, rustia: &Rustia<C>) -> Result<Option<f64>>
where
C: HostSchema,
{
self.raw(rustia.vm(), "value handle")
.map(RawValue::as_number)
}
pub fn string_bytes<C>(&self, rustia: &mut Rustia<C>) -> Result<Option<Vec<u8>>>
where
C: HostSchema,
{
let value = self.raw(rustia.vm(), "value handle")?;
rustia
.vm_mut()
.string_value_bytes(value)
.map_err(Error::from_engine)
}
pub fn buffer_bytes<C>(&self, rustia: &mut Rustia<C>) -> Result<Option<Vec<u8>>>
where
C: HostSchema,
{
let value = self.raw(rustia.vm(), "value handle")?;
rustia
.vm_mut()
.buffer_value_bytes(value)
.map_err(Error::from_engine)
}
pub fn vector_components<C>(&self, rustia: &mut Rustia<C>) -> Result<Option<[f32; 3]>>
where
C: HostSchema,
{
let value = self.raw(rustia.vm(), "value handle")?;
rustia
.vm_mut()
.vector_value_components(value)
.map_err(Error::from_engine)
}
pub fn to_owned<C>(&self, rustia: &mut Rustia<C>) -> Result<OwnedValue>
where
C: HostSchema,
{
let value = self.raw(rustia.vm(), "value handle")?;
snapshot_value(rustia.vm_mut(), value)
}
pub fn deserialize<T>(&self, rustia: &mut Rustia<impl HostSchema>) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
let value = self.raw(rustia.vm(), "value handle")?;
from_live(rustia.vm_mut(), value)
}
pub fn as_table<C>(&self, rustia: &Rustia<C>) -> Result<Option<Table>>
where
C: HostSchema,
{
Ok((self.kind(rustia)? == ValueType::Table).then(|| Table::new(self.clone())))
}
pub fn as_function<C>(&self, rustia: &Rustia<C>) -> Result<Option<Function>>
where
C: HostSchema,
{
Ok((self.kind(rustia)? == ValueType::Function).then(|| Function::from_value(self.clone())))
}
pub fn raw_equal<C>(&self, rustia: &mut Rustia<C>, other: &Self) -> Result<bool>
where
C: HostSchema,
{
let lhs = self.raw(rustia.vm(), "left value handle")?;
let rhs = other.raw(rustia.vm(), "right value handle")?;
rustia
.vm_mut()
.raw_equal_values(lhs, rhs)
.map_err(Error::from_engine)
}
pub(crate) fn raw(&self, vm: &Vm, label: &str) -> Result<RawValue> {
self.value
.value(vm)
.map_err(|error| Error::from_engine(error).with_context(label))
}
}
impl fmt::Debug for Value {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Value")
.field("decision_epoch", &self.decision_epoch)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub struct Table {
value: Value,
}
impl Table {
pub(crate) const fn new(value: Value) -> Self {
Self { value }
}
pub(crate) fn raw(&self, vm: &Vm, label: &str) -> Result<RawValue> {
self.value.raw(vm, label)
}
pub fn as_value(&self) -> Value {
self.value.clone()
}
pub fn deserialize<T>(&self, rustia: &mut Rustia<impl HostSchema>) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
self.value.deserialize(rustia)
}
pub const fn decision_epoch(&self) -> u64 {
self.value.decision_epoch()
}
pub fn get_value<C>(&self, rustia: &mut Rustia<C>, key: &Value) -> Result<Value>
where
C: HostSchema,
{
let table = self.value.raw(rustia.vm(), "table handle")?;
let key = key.raw(rustia.vm(), "table key handle")?;
let value = rustia
.vm_mut()
.raw_table_get_value(table, key)
.map_err(Error::from_engine)?;
Value::retain(rustia.vm_mut(), value)
}
pub fn get<K, C>(&self, rustia: &mut Rustia<C>, key: K) -> Result<Value>
where
K: IntoRustia,
C: HostSchema,
{
let table = self.value.raw(rustia.vm(), "table handle")?;
let key = key.into_rustia()?;
let key = load_owned_value(rustia.vm_mut(), &key)?;
let value = rustia
.vm_mut()
.raw_table_get_value(table, key)
.map_err(Error::from_engine)?;
Value::retain(rustia.vm_mut(), value)
}
pub fn set_value<C>(&self, rustia: &mut Rustia<C>, key: &Value, value: &Value) -> Result<()>
where
C: HostSchema,
{
let table = self.value.raw(rustia.vm(), "table handle")?;
let key = key.raw(rustia.vm(), "table key handle")?;
let value = value.raw(rustia.vm(), "table value handle")?;
rustia
.vm_mut()
.raw_table_set_value(table, key, value)
.map_err(Error::from_engine)
}
pub fn set_live<K, C>(&self, rustia: &mut Rustia<C>, key: K, value: &Value) -> Result<()>
where
K: IntoRustia,
C: HostSchema,
{
let table = self.value.raw(rustia.vm(), "table handle")?;
let value = value.raw(rustia.vm(), "table value handle")?;
let key = key.into_rustia()?;
let key = load_owned_value(rustia.vm_mut(), &key)?;
rustia
.vm_mut()
.raw_table_set_value(table, key, value)
.map_err(Error::from_engine)
}
pub fn set<K, V, C>(&self, rustia: &mut Rustia<C>, key: K, value: V) -> Result<()>
where
K: IntoRustia,
V: IntoRustia,
C: HostSchema,
{
let table = self.value.raw(rustia.vm(), "table handle")?;
let key = key.into_rustia()?;
let value = value.into_rustia()?;
let (values, _argument_roots) = load_owned_arguments(rustia.vm_mut(), &[key, value])?;
rustia
.vm_mut()
.raw_table_set_value(table, values[0], values[1])
.map_err(Error::from_engine)
}
pub fn entries<C>(&self, rustia: &mut Rustia<C>) -> Result<Vec<(Value, Value)>>
where
C: HostSchema,
{
let table = self.value.raw(rustia.vm(), "table handle")?;
let entries = rustia
.vm_mut()
.raw_table_entries_value(table)
.map_err(Error::from_engine)?;
let raw_values = entries
.into_iter()
.flat_map(|(key, value)| [key, value])
.collect::<Vec<_>>();
let values = Value::retain_many(rustia.vm_mut(), &raw_values)?;
Ok(values
.chunks_exact(2)
.map(|pair| (pair[0].clone(), pair[1].clone()))
.collect())
}
}
fn raw_value_type(value: RawValue) -> Result<ValueType> {
Ok(match value.kind() {
ValueKind::Nil => ValueType::Nil,
ValueKind::Boolean => ValueType::Boolean,
ValueKind::Number => ValueType::Number,
ValueKind::String => ValueType::String,
ValueKind::Table => ValueType::Table,
ValueKind::Function => ValueType::Function,
ValueKind::Userdata => ValueType::Userdata,
ValueKind::Buffer => ValueType::Buffer,
ValueKind::Vector => ValueType::Vector,
_ => {
return Err(Error::embed(
"unknown VM value kind cannot be represented as a live value".to_owned(),
));
}
})
}