xur_runtime/marshal/
dynamic.rs1use std::marker::PhantomData;
11
12use super::{FromValue, IntoXurValue, TypeDesc};
13use crate::convert::ConvertCx;
14use crate::{RunResult, Value};
15
16pub trait Describe {
18 fn type_desc() -> TypeDesc;
19}
20
21pub struct Dyn<D>(pub Value, PhantomData<fn() -> D>);
23
24impl<D> Dyn<D> {
25 pub fn new(value: Value) -> Self {
26 Self(value, PhantomData)
27 }
28}
29
30impl<D: Describe + 'static> FromValue for Dyn<D> {
31 fn type_desc() -> TypeDesc {
32 D::type_desc()
33 }
34 fn from_value(_cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
35 Ok(Self::new(value.clone()))
36 }
37}
38
39impl<D: Describe + 'static> IntoXurValue for Dyn<D> {
40 fn type_desc() -> TypeDesc {
41 D::type_desc()
42 }
43 fn into_xur_value(self, _cx: &dyn ConvertCx) -> RunResult<Value> {
44 Ok(self.0)
45 }
46}
47
48pub mod desc {
50 use std::marker::PhantomData;
51
52 use super::{Describe, TypeDesc};
53
54 macro_rules! params {
55 ($($name:ident: $doc:literal),*) => {$(
56 #[doc = $doc]
57 pub struct $name;
58 impl Describe for $name {
59 fn type_desc() -> TypeDesc {
60 TypeDesc::Name(stringify!($name))
61 }
62 }
63 )*};
64 }
65 params! {
66 T: "The receiver's element type: a list's items, a cell's value.",
67 U: "A second type parameter, chosen by the caller (what a closure returns).",
68 K: "A map's key type.",
69 V: "A map's value type."
70 }
71
72 pub struct Any;
74 impl Describe for Any {
75 fn type_desc() -> TypeDesc {
76 TypeDesc::ANY
77 }
78 }
79
80 pub struct Number;
82 impl Describe for Number {
83 fn type_desc() -> TypeDesc {
84 TypeDesc::Union(vec![TypeDesc::Name("int"), TypeDesc::Name("float")])
85 }
86 }
87
88 pub struct ListOf<D>(PhantomData<fn() -> D>);
90 impl<D: Describe> Describe for ListOf<D> {
91 fn type_desc() -> TypeDesc {
92 TypeDesc::Generic("list", vec![D::type_desc()])
93 }
94 }
95
96 pub struct MapOf<K, V>(PhantomData<fn() -> (K, V)>);
98 impl<K: Describe, V: Describe> Describe for MapOf<K, V> {
99 fn type_desc() -> TypeDesc {
100 TypeDesc::Generic("map", vec![K::type_desc(), V::type_desc()])
101 }
102 }
103
104 pub struct Tuple2<A, B>(PhantomData<fn() -> (A, B)>);
106 impl<A: Describe, B: Describe> Describe for Tuple2<A, B> {
107 fn type_desc() -> TypeDesc {
108 TypeDesc::Tuple(vec![A::type_desc(), B::type_desc()])
109 }
110 }
111
112 pub struct Str;
114 impl Describe for Str {
115 fn type_desc() -> TypeDesc {
116 TypeDesc::STR
117 }
118 }
119
120 pub struct Int;
122 impl Describe for Int {
123 fn type_desc() -> TypeDesc {
124 TypeDesc::Name("i64")
125 }
126 }
127}