rune/runtime/value/
data.rs

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