1use crate::function::Function;
2use crate::serde_value::from_live;
3use crate::value::{load_owned_arguments, load_owned_value, snapshot_value};
4use crate::{Error, HostSchema, IntoRustia, OwnedValue, Result, Rustia};
5use rustia_vm::{RetainedValue, Value as RawValue, ValueKind, Vm};
6use std::fmt;
7
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum ValueType {
12 Nil,
13 Boolean,
14 Number,
15 String,
16 Table,
17 Function,
18 Userdata,
19 Buffer,
20 Vector,
21}
22
23impl ValueType {
24 pub const fn name(self) -> &'static str {
26 match self {
27 Self::Nil => "nil",
28 Self::Boolean => "boolean",
29 Self::Number => "number",
30 Self::String => "string",
31 Self::Table => "table",
32 Self::Function => "function",
33 Self::Userdata => "userdata",
34 Self::Buffer => "buffer",
35 Self::Vector => "vector",
36 }
37 }
38}
39
40#[derive(Clone)]
53pub struct Value {
54 value: RetainedValue,
55 decision_epoch: u64,
56}
57
58impl Value {
59 pub(crate) fn new(value: RetainedValue, decision_epoch: u64) -> Self {
60 Self {
61 value,
62 decision_epoch,
63 }
64 }
65
66 pub(crate) fn retain(vm: &mut Vm, value: RawValue) -> Result<Self> {
67 let decision_epoch = vm.decision_epoch();
68 vm.retain_value(value)
69 .map(|value| Self::new(value, decision_epoch))
70 .map_err(Error::from_engine)
71 }
72
73 pub(crate) fn retain_many(vm: &mut Vm, values: &[RawValue]) -> Result<Vec<Self>> {
74 let decision_epoch = vm.decision_epoch();
75 vm.retain_values(values)
76 .map(|values| {
77 values
78 .into_iter()
79 .map(|value| Self::new(value, decision_epoch))
80 .collect()
81 })
82 .map_err(Error::from_engine)
83 }
84
85 pub const fn decision_epoch(&self) -> u64 {
87 self.decision_epoch
88 }
89
90 pub fn kind<C>(&self, rustia: &Rustia<C>) -> Result<ValueType>
92 where
93 C: HostSchema,
94 {
95 let value = self.raw(rustia.vm(), "value handle")?;
96 raw_value_type(value)
97 }
98
99 pub fn type_name<C>(&self, rustia: &Rustia<C>) -> Result<&'static str>
101 where
102 C: HostSchema,
103 {
104 self.kind(rustia).map(ValueType::name)
105 }
106
107 pub fn is_nil<C>(&self, rustia: &Rustia<C>) -> Result<bool>
109 where
110 C: HostSchema,
111 {
112 self.kind(rustia).map(|kind| kind == ValueType::Nil)
113 }
114
115 pub fn truthy<C>(&self, rustia: &Rustia<C>) -> Result<bool>
118 where
119 C: HostSchema,
120 {
121 self.raw(rustia.vm(), "value handle").map(RawValue::truthy)
122 }
123
124 pub fn as_boolean<C>(&self, rustia: &Rustia<C>) -> Result<Option<bool>>
126 where
127 C: HostSchema,
128 {
129 self.raw(rustia.vm(), "value handle").map(RawValue::as_bool)
130 }
131
132 pub fn as_number<C>(&self, rustia: &Rustia<C>) -> Result<Option<f64>>
134 where
135 C: HostSchema,
136 {
137 self.raw(rustia.vm(), "value handle")
138 .map(RawValue::as_number)
139 }
140
141 pub fn string_bytes<C>(&self, rustia: &mut Rustia<C>) -> Result<Option<Vec<u8>>>
143 where
144 C: HostSchema,
145 {
146 let value = self.raw(rustia.vm(), "value handle")?;
147 rustia
148 .vm_mut()
149 .string_value_bytes(value)
150 .map_err(Error::from_engine)
151 }
152
153 pub fn buffer_bytes<C>(&self, rustia: &mut Rustia<C>) -> Result<Option<Vec<u8>>>
155 where
156 C: HostSchema,
157 {
158 let value = self.raw(rustia.vm(), "value handle")?;
159 rustia
160 .vm_mut()
161 .buffer_value_bytes(value)
162 .map_err(Error::from_engine)
163 }
164
165 pub fn vector_components<C>(&self, rustia: &mut Rustia<C>) -> Result<Option<[f32; 3]>>
167 where
168 C: HostSchema,
169 {
170 let value = self.raw(rustia.vm(), "value handle")?;
171 rustia
172 .vm_mut()
173 .vector_value_components(value)
174 .map_err(Error::from_engine)
175 }
176
177 pub fn to_owned<C>(&self, rustia: &mut Rustia<C>) -> Result<OwnedValue>
185 where
186 C: HostSchema,
187 {
188 let value = self.raw(rustia.vm(), "value handle")?;
189 snapshot_value(rustia.vm_mut(), value)
190 }
191
192 pub fn deserialize<T>(&self, rustia: &mut Rustia<impl HostSchema>) -> Result<T>
205 where
206 T: serde::de::DeserializeOwned,
207 {
208 let value = self.raw(rustia.vm(), "value handle")?;
209 from_live(rustia.vm_mut(), value)
210 }
211
212 pub fn as_table<C>(&self, rustia: &Rustia<C>) -> Result<Option<Table>>
214 where
215 C: HostSchema,
216 {
217 Ok((self.kind(rustia)? == ValueType::Table).then(|| Table::new(self.clone())))
218 }
219
220 pub fn as_function<C>(&self, rustia: &Rustia<C>) -> Result<Option<Function>>
222 where
223 C: HostSchema,
224 {
225 Ok((self.kind(rustia)? == ValueType::Function).then(|| Function::from_value(self.clone())))
226 }
227
228 pub fn raw_equal<C>(&self, rustia: &mut Rustia<C>, other: &Self) -> Result<bool>
230 where
231 C: HostSchema,
232 {
233 let lhs = self.raw(rustia.vm(), "left value handle")?;
234 let rhs = other.raw(rustia.vm(), "right value handle")?;
235 rustia
236 .vm_mut()
237 .raw_equal_values(lhs, rhs)
238 .map_err(Error::from_engine)
239 }
240
241 pub(crate) fn raw(&self, vm: &Vm, label: &str) -> Result<RawValue> {
242 self.value
243 .value(vm)
244 .map_err(|error| Error::from_engine(error).with_context(label))
245 }
246}
247
248impl fmt::Debug for Value {
249 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
250 formatter
251 .debug_struct("Value")
252 .field("decision_epoch", &self.decision_epoch)
253 .finish_non_exhaustive()
254 }
255}
256
257#[derive(Clone, Debug)]
273pub struct Table {
274 value: Value,
275}
276
277impl Table {
278 pub(crate) const fn new(value: Value) -> Self {
279 Self { value }
280 }
281
282 pub(crate) fn raw(&self, vm: &Vm, label: &str) -> Result<RawValue> {
283 self.value.raw(vm, label)
284 }
285
286 pub fn as_value(&self) -> Value {
288 self.value.clone()
289 }
290
291 pub fn deserialize<T>(&self, rustia: &mut Rustia<impl HostSchema>) -> Result<T>
293 where
294 T: serde::de::DeserializeOwned,
295 {
296 self.value.deserialize(rustia)
297 }
298
299 pub const fn decision_epoch(&self) -> u64 {
301 self.value.decision_epoch()
302 }
303
304 pub fn get_value<C>(&self, rustia: &mut Rustia<C>, key: &Value) -> Result<Value>
306 where
307 C: HostSchema,
308 {
309 let table = self.value.raw(rustia.vm(), "table handle")?;
310 let key = key.raw(rustia.vm(), "table key handle")?;
311 let value = rustia
312 .vm_mut()
313 .raw_table_get_value(table, key)
314 .map_err(Error::from_engine)?;
315 Value::retain(rustia.vm_mut(), value)
316 }
317
318 pub fn get<K, C>(&self, rustia: &mut Rustia<C>, key: K) -> Result<Value>
320 where
321 K: IntoRustia,
322 C: HostSchema,
323 {
324 let table = self.value.raw(rustia.vm(), "table handle")?;
325 let key = key.into_rustia()?;
326 let key = load_owned_value(rustia.vm_mut(), &key)?;
327 let value = rustia
328 .vm_mut()
329 .raw_table_get_value(table, key)
330 .map_err(Error::from_engine)?;
331 Value::retain(rustia.vm_mut(), value)
332 }
333
334 pub fn set_value<C>(&self, rustia: &mut Rustia<C>, key: &Value, value: &Value) -> Result<()>
336 where
337 C: HostSchema,
338 {
339 let table = self.value.raw(rustia.vm(), "table handle")?;
340 let key = key.raw(rustia.vm(), "table key handle")?;
341 let value = value.raw(rustia.vm(), "table value handle")?;
342 rustia
343 .vm_mut()
344 .raw_table_set_value(table, key, value)
345 .map_err(Error::from_engine)
346 }
347
348 pub fn set_live<K, C>(&self, rustia: &mut Rustia<C>, key: K, value: &Value) -> Result<()>
352 where
353 K: IntoRustia,
354 C: HostSchema,
355 {
356 let table = self.value.raw(rustia.vm(), "table handle")?;
360 let value = value.raw(rustia.vm(), "table value handle")?;
361 let key = key.into_rustia()?;
362 let key = load_owned_value(rustia.vm_mut(), &key)?;
363 rustia
364 .vm_mut()
365 .raw_table_set_value(table, key, value)
366 .map_err(Error::from_engine)
367 }
368
369 pub fn set<K, V, C>(&self, rustia: &mut Rustia<C>, key: K, value: V) -> Result<()>
373 where
374 K: IntoRustia,
375 V: IntoRustia,
376 C: HostSchema,
377 {
378 let table = self.value.raw(rustia.vm(), "table handle")?;
379 let key = key.into_rustia()?;
380 let value = value.into_rustia()?;
381 let (values, _argument_roots) = load_owned_arguments(rustia.vm_mut(), &[key, value])?;
382 rustia
383 .vm_mut()
384 .raw_table_set_value(table, values[0], values[1])
385 .map_err(Error::from_engine)
386 }
387
388 pub fn entries<C>(&self, rustia: &mut Rustia<C>) -> Result<Vec<(Value, Value)>>
394 where
395 C: HostSchema,
396 {
397 let table = self.value.raw(rustia.vm(), "table handle")?;
398 let entries = rustia
399 .vm_mut()
400 .raw_table_entries_value(table)
401 .map_err(Error::from_engine)?;
402 let raw_values = entries
403 .into_iter()
404 .flat_map(|(key, value)| [key, value])
405 .collect::<Vec<_>>();
406 let values = Value::retain_many(rustia.vm_mut(), &raw_values)?;
407 Ok(values
408 .chunks_exact(2)
409 .map(|pair| (pair[0].clone(), pair[1].clone()))
410 .collect())
411 }
412}
413
414fn raw_value_type(value: RawValue) -> Result<ValueType> {
415 Ok(match value.kind() {
416 ValueKind::Nil => ValueType::Nil,
417 ValueKind::Boolean => ValueType::Boolean,
418 ValueKind::Number => ValueType::Number,
419 ValueKind::String => ValueType::String,
420 ValueKind::Table => ValueType::Table,
421 ValueKind::Function => ValueType::Function,
422 ValueKind::Userdata => ValueType::Userdata,
423 ValueKind::Buffer => ValueType::Buffer,
424 ValueKind::Vector => ValueType::Vector,
425 _ => {
426 return Err(Error::embed(
427 "unknown VM value kind cannot be represented as a live value".to_owned(),
428 ));
429 }
430 })
431}