rune/runtime/value/
data.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use core::borrow::Borrow;
use core::fmt;
use core::hash;

use rust_alloc::sync::Arc;

use crate::alloc::prelude::*;
use crate::runtime::{BorrowRef, TypeInfo};

use super::{Rtti, Value};

/// A empty with a well-defined type.
pub struct EmptyStruct<'a> {
    /// The type hash of the empty.
    pub(crate) rtti: &'a Arc<Rtti>,
}

impl<'a> EmptyStruct<'a> {
    /// Access runtime type information.
    pub fn rtti(&self) -> &'a Arc<Rtti> {
        self.rtti
    }

    /// Get type info for the typed tuple.
    pub fn type_info(&self) -> TypeInfo {
        TypeInfo::rtti(self.rtti.clone())
    }
}

impl fmt::Debug for EmptyStruct<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.rtti.item)
    }
}

/// A tuple with a well-defined type.
pub struct TupleStruct<'a> {
    /// The type hash of the tuple.
    pub(crate) rtti: &'a Arc<Rtti>,
    /// Content of the tuple.
    pub(crate) data: BorrowRef<'a, [Value]>,
}

impl<'a> TupleStruct<'a> {
    /// Access runtime type information.
    pub fn rtti(&self) -> &'a Rtti {
        self.rtti
    }

    /// Access underlying data.
    pub fn data(&self) -> &[Value] {
        &self.data
    }

    /// Get the value at the given index in the tuple.
    pub fn get(&self, index: usize) -> Option<&Value> {
        self.data.get(index)
    }

    /// Get type info for the typed tuple.
    pub fn type_info(&self) -> TypeInfo {
        TypeInfo::rtti(self.rtti.clone())
    }
}

impl fmt::Debug for TupleStruct<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.rtti.item)
    }
}

/// An object with a well-defined type.
pub struct Struct<'a> {
    /// The type hash of the object.
    pub(crate) rtti: &'a Arc<Rtti>,
    /// Contents of the object.
    pub(crate) data: BorrowRef<'a, [Value]>,
}

impl<'a> Struct<'a> {
    /// Access struct rtti.
    pub fn rtti(&self) -> &'a Arc<Rtti> {
        self.rtti
    }

    /// Access truct data.
    pub fn data(&self) -> &[Value] {
        &self.data
    }

    /// Get a field through the accessor.
    pub fn get<Q>(&self, key: &Q) -> Option<&Value>
    where
        Box<str>: Borrow<Q>,
        Q: hash::Hash + Eq + ?Sized,
    {
        self.data.get(*self.rtti.fields.get(key)?)
    }

    /// Get type info for the typed object.
    pub(crate) fn type_info(&self) -> TypeInfo {
        TypeInfo::rtti(self.rtti.clone())
    }
}

impl fmt::Debug for Struct<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.rtti.item)
    }
}