looking_glass/
typed.rs

1use crate::*;
2pub use bytes::Bytes;
3pub use smol_str::SmolStr;
4
5/// Any type that can be contained in a [`Value`]
6///
7/// [`Typed`] needs to be implemented for any primatives including in a relected instance, and
8/// any reflected struct or enum.
9pub trait Typed<'ty>: Send + Sync {
10    fn ty() -> ValueTy;
11
12    fn as_value<'val>(&'val self) -> Value<'val, 'ty>
13    where
14        'ty: 'val;
15}
16
17impl<'ty> Typed<'ty> for str {
18    fn ty() -> ValueTy {
19        ValueTy::Str
20    }
21
22    fn as_value<'val>(&'val self) -> Value<'val, 'ty>
23    where
24        'ty: 'val,
25    {
26        Value(ValueInner::Str(self))
27    }
28}
29
30impl<'ty> Typed<'ty> for String {
31    fn ty() -> ValueTy {
32        ValueTy::String
33    }
34
35    fn as_value<'val>(&'val self) -> Value<'val, 'ty>
36    where
37        'ty: 'val,
38    {
39        Value(ValueInner::String(self))
40    }
41}
42
43impl<'ty> Typed<'ty> for Bytes {
44    fn ty() -> ValueTy {
45        ValueTy::Bytes
46    }
47
48    fn as_value<'val>(&'val self) -> Value<'val, 'ty>
49    where
50        'ty: 'val,
51    {
52        Value(ValueInner::Bytes(self))
53    }
54}
55
56impl<'ty> Typed<'ty> for Box<dyn VecInstance<'ty>> {
57    fn ty() -> ValueTy {
58        ValueTy::VecInstance
59    }
60
61    fn as_value<'val>(&'val self) -> Value<'val, 'ty>
62    where
63        'ty: 'val,
64    {
65        Value::from_vec(self.as_ref())
66    }
67}
68
69impl<'ty> Typed<'ty> for Box<dyn StructInstance<'ty> + 'ty> {
70    fn ty() -> ValueTy {
71        ValueTy::StructInstance
72    }
73
74    fn as_value<'val>(&'val self) -> Value<'val, 'ty>
75    where
76        'ty: 'val,
77    {
78        Value::from_struct(self.as_ref())
79    }
80}
81
82/// Provides `inst_ty` for any [`Typed`] type
83pub trait TypedObj {
84    fn inst_ty(&self) -> ValueTy;
85}
86
87impl<'ty, T> TypedObj for T
88where
89    T: Typed<'ty> + ?Sized,
90{
91    fn inst_ty(&self) -> ValueTy {
92        T::ty()
93    }
94}