Skip to main content

rustia/
live_value.rs

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/// The Luau type of a live [`Value`].
9#[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    /// Returns the Luau runtime type name.
25    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/// A script value kept alive in its original Rustia VM.
41///
42/// Unlike [`OwnedValue`], this is a handle rather than a copy. Tables, functions,
43/// and userdata keep their identity; strings can contain arbitrary bytes; tables
44/// can share values or refer to themselves. Cloning a handle keeps the same
45/// value alive and does not copy its contents.
46///
47/// Every operation requires the VM that created the handle. A
48/// [`Rustia::reset_decision`] invalidates all earlier handles; using one after
49/// reset or with another VM returns an error. To keep ordinary data across a
50/// reset, copy it with [`to_owned`](Self::to_owned) or
51/// [`deserialize`](Self::deserialize).
52#[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    /// Returns the decision epoch in which this value was retained.
86    pub const fn decision_epoch(&self) -> u64 {
87        self.decision_epoch
88    }
89
90    /// Returns this value's runtime kind.
91    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    /// Returns this value's Luau runtime type name.
100    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    /// Returns whether this is the nil value.
108    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    /// Tests Luau truthiness: only `nil` and `false` are false.
116    /// This does not invoke guest code.
117    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    /// Returns a boolean, or `None` for another value kind. No coercion is applied.
125    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    /// Returns a number, or `None` for another value kind. No coercion is applied.
133    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    /// Copies the exact binary string bytes, or returns `None` for another kind.
142    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    /// Copies the current buffer bytes, or returns `None` for another kind.
154    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    /// Returns the three vector components, or `None` for another value kind.
166    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    /// Copies this value and any nested tables into Rust-owned data.
178    ///
179    /// Non-UTF-8 strings, buffers, vectors, userdata, functions, keys unsupported
180    /// by [`crate::OwnedKey`], and cyclic graphs return conversion errors.
181    /// Shared tables are copied independently; table identity is not preserved.
182    /// Deeply nested tables also return an error once the snapshot depth limit
183    /// is reached.
184    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    /// Deserializes this value without first building an [`OwnedValue`] copy.
193    ///
194    /// The returned type must own its data; it cannot borrow strings or other
195    /// contents from the VM.
196    ///
197    /// ```compile_fail
198    /// use rustia::{Rustia, Value};
199    ///
200    /// fn cannot_borrow(value: &Value, rustia: &mut Rustia) {
201    ///     let _: &str = value.deserialize(rustia).unwrap();
202    /// }
203    /// ```
204    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    /// Returns a table handle, or `None` if this is another value kind.
213    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    /// Returns a function handle, or `None` if this is another value kind.
221    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    /// Compares values using raw Luau equality without invoking `__eq`.
229    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/// A live table that Rust and Luau can both read and change.
258///
259/// Clones refer to the same table. All lookups and writes are raw: they bypass
260/// `__index` and `__newindex`. Like [`Value`], a table belongs to one VM and
261/// becomes invalid after [`Rustia::reset_decision`].
262///
263/// ```
264/// use rustia::Rustia;
265///
266/// let mut lua = Rustia::builder().build()?;
267/// let scores = lua.create_table()?;
268/// scores.set(&mut lua, "Ada", 42)?;
269/// assert_eq!(scores.get(&mut lua, "Ada")?.as_number(&lua)?, Some(42.0));
270/// # Ok::<(), rustia::Error>(())
271/// ```
272#[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    /// Clones this table's underlying live value handle.
287    pub fn as_value(&self) -> Value {
288        self.value.clone()
289    }
290
291    /// Deserializes this table without first building an [`OwnedValue`] copy.
292    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    /// Returns the decision epoch in which this handle was retained.
300    pub const fn decision_epoch(&self) -> u64 {
301        self.value.decision_epoch()
302    }
303
304    /// Looks up a live key without invoking `__index`. Missing keys return `nil`.
305    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    /// Looks up a Rust key without invoking `__index`. Missing keys return `nil`.
319    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    /// Performs a raw write with live key/value handles, bypassing `__newindex`.
335    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    /// Stores a live value under a Rust key without invoking `__newindex`.
349    ///
350    /// The stored value keeps its identity; it is not copied into a new object.
351    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        // Validate both live handles before key conversion can allocate or
357        // mutate VM-owned storage. The retained handles keep these compact raw
358        // values rooted if loading the owned key triggers quota collection.
359        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    /// Converts and stores a Rust key and value without invoking `__newindex`.
370    ///
371    /// Use [`set_live`](Self::set_live) to store an existing script object.
372    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    /// Returns the current entries in insertion order as live key/value handles.
389    ///
390    /// Mutating the table later does not change which key/value handles this
391    /// returned vector contains, though those handles still refer to their
392    /// original live objects.
393    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}