1use std::fmt;
5
6#[derive(Clone, Debug, PartialEq, Eq, Hash, mln_wire::Wire)]
9pub enum Type {
10 Null,
11 Number,
12 Boolean,
13 String,
14 Color,
15 Padding,
16 ProjectionDefinition,
17 VariableAnchorOffsetCollection,
18 Object,
19 Value,
20 Array(Box<Array>),
21 Collator,
22 Formatted,
23 Error,
24 Image,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq, Hash, mln_wire::Wire)]
28pub struct Array {
29 pub item_type: Type,
30 pub n: Option<usize>,
31}
32
33impl Array {
34 #[must_use]
35 pub(crate) fn new(item_type: Type) -> Self {
36 Array { item_type, n: None }
37 }
38
39 #[must_use]
40 pub(crate) fn with_n(item_type: Type, n: Option<usize>) -> Self {
41 Array { item_type, n }
42 }
43
44 #[must_use]
45 pub(crate) fn get_name(&self) -> String {
46 if let Some(n) = self.n {
47 format!("array<{}, {}>", to_string(&self.item_type), n)
48 } else if self.item_type == Type::Value {
49 "array".to_owned()
50 } else {
51 format!("array<{}>", to_string(&self.item_type))
52 }
53 }
54}
55
56impl From<Array> for Type {
57 fn from(a: Array) -> Self {
58 Type::Array(Box::new(a))
59 }
60}
61
62impl Type {
63 #[must_use]
64 pub fn array(item_type: Type) -> Type {
65 Array::new(item_type).into()
66 }
67
68 #[must_use]
69 pub fn array_n(item_type: Type, n: usize) -> Type {
70 Array::with_n(item_type, Some(n)).into()
71 }
72
73 #[must_use]
74 pub(crate) fn is_array(&self) -> bool {
75 matches!(self, Type::Array(_))
76 }
77
78 #[must_use]
79 pub(crate) fn as_array(&self) -> Option<&Array> {
80 match self {
81 Type::Array(a) => Some(a),
82 _ => None,
83 }
84 }
85
86 #[must_use]
87 pub(crate) fn get_name(&self) -> String {
88 match self {
89 Type::Null => "null".to_owned(),
90 Type::Number => "number".to_owned(),
91 Type::Boolean => "boolean".to_owned(),
92 Type::String => "string".to_owned(),
93 Type::Color => "color".to_owned(),
94 Type::Padding => "padding".to_owned(),
95 Type::ProjectionDefinition => "projectionDefinition".to_owned(),
96 Type::VariableAnchorOffsetCollection => "variableAnchorOffsetCollection".to_owned(),
97 Type::Object => "object".to_owned(),
98 Type::Value => "value".to_owned(),
99 Type::Array(a) => a.get_name(),
100 Type::Collator => "collator".to_owned(),
101 Type::Formatted => "formatted".to_owned(),
102 Type::Error => "error".to_owned(),
103 Type::Image => "resolvedImage".to_owned(),
104 }
105 }
106}
107
108#[must_use]
109pub fn to_string(t: &Type) -> String {
110 t.get_name()
111}
112
113impl fmt::Display for Type {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.write_str(&self.get_name())
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122
123 #[test]
124 fn names() {
125 assert_eq!(to_string(&Type::array(Type::Value)), "array");
126 assert_eq!(to_string(&Type::array(Type::Number)), "array<number>");
127 assert_eq!(to_string(&Type::array_n(Type::Value, 2)), "array<value, 2>");
128 assert_eq!(to_string(&Type::Image), "resolvedImage");
129 }
130}