rune/runtime/value/
data.rs

1use core::borrow::Borrow;
2use core::fmt;
3use core::hash;
4
5use rust_alloc::sync::Arc;
6
7use crate::alloc::prelude::*;
8use crate::runtime::{BorrowRef, TypeInfo};
9
10use super::{Rtti, Value};
11
12/// A empty with a well-defined type.
13pub struct EmptyStruct<'a> {
14    /// The type hash of the empty.
15    pub(crate) rtti: &'a Arc<Rtti>,
16}
17
18impl<'a> EmptyStruct<'a> {
19    /// Access runtime type information.
20    pub fn rtti(&self) -> &'a Arc<Rtti> {
21        self.rtti
22    }
23
24    /// Get type info for the typed tuple.
25    pub fn type_info(&self) -> TypeInfo {
26        TypeInfo::rtti(self.rtti.clone())
27    }
28}
29
30impl fmt::Debug for EmptyStruct<'_> {
31    #[inline]
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(f, "{}", self.rtti.item)
34    }
35}
36
37/// A tuple with a well-defined type.
38pub struct TupleStruct<'a> {
39    /// The type hash of the tuple.
40    pub(crate) rtti: &'a Arc<Rtti>,
41    /// Content of the tuple.
42    pub(crate) data: BorrowRef<'a, [Value]>,
43}
44
45impl<'a> TupleStruct<'a> {
46    /// Access runtime type information.
47    pub fn rtti(&self) -> &'a Rtti {
48        self.rtti
49    }
50
51    /// Access underlying data.
52    pub fn data(&self) -> &[Value] {
53        &self.data
54    }
55
56    /// Get the value at the given index in the tuple.
57    pub fn get(&self, index: usize) -> Option<&Value> {
58        self.data.get(index)
59    }
60
61    /// Get type info for the typed tuple.
62    pub fn type_info(&self) -> TypeInfo {
63        TypeInfo::rtti(self.rtti.clone())
64    }
65}
66
67impl fmt::Debug for TupleStruct<'_> {
68    #[inline]
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "{}", self.rtti.item)
71    }
72}
73
74/// An object with a well-defined type.
75pub struct Struct<'a> {
76    /// The type hash of the object.
77    pub(crate) rtti: &'a Arc<Rtti>,
78    /// Contents of the object.
79    pub(crate) data: BorrowRef<'a, [Value]>,
80}
81
82impl<'a> Struct<'a> {
83    /// Access struct rtti.
84    pub fn rtti(&self) -> &'a Arc<Rtti> {
85        self.rtti
86    }
87
88    /// Access truct data.
89    pub fn data(&self) -> &[Value] {
90        &self.data
91    }
92
93    /// Get a field through the accessor.
94    pub fn get<Q>(&self, key: &Q) -> Option<&Value>
95    where
96        Box<str>: Borrow<Q>,
97        Q: hash::Hash + Eq + ?Sized,
98    {
99        self.data.get(*self.rtti.fields.get(key)?)
100    }
101
102    /// Get type info for the typed object.
103    pub(crate) fn type_info(&self) -> TypeInfo {
104        TypeInfo::rtti(self.rtti.clone())
105    }
106}
107
108impl fmt::Debug for Struct<'_> {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "{}", self.rtti.item)
111    }
112}