mir/
ty.rs

1use openapiv3 as oa;
2
3#[derive(Debug, Clone, Copy, PartialEq)]
4pub enum DateSerialization {
5    Iso8601,
6    Integer,
7}
8
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum DecimalSerialization {
11    String,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub enum IntegerSerialization {
16    Simple,
17    String,
18    NullAsZero,
19}
20
21#[derive(Debug, Clone)]
22pub enum Ty {
23    String,
24    Integer { ser: IntegerSerialization },
25    Float,
26    Boolean,
27    Array(Box<Ty>),
28    HashMap(Box<Ty>),
29    // OpenAPI name for the model. Hasn't been converted to a language type (e.g. cased, sanitized)
30    Model(String),
31    Unit,
32    Date { ser: DateSerialization },
33    DateTime,
34    Currency { ser: DecimalSerialization },
35    Any(Option<oa::Schema>),
36}
37
38impl Default for Ty {
39    fn default() -> Self {
40        Ty::Any(None)
41    }
42}
43
44impl Ty {
45    pub fn integer() -> Self {
46        Ty::Integer {
47            ser: IntegerSerialization::Simple,
48        }
49    }
50
51    pub fn inner_model(&self) -> Option<&String> {
52        match self {
53            Ty::Model(name) => Some(name),
54            Ty::Array(ty) => ty.inner_model(),
55            Ty::HashMap(ty) => ty.inner_model(),
56            _ => None,
57        }
58    }
59
60    pub fn is_iterable(&self) -> bool {
61        self.inner_iterable().is_some()
62    }
63
64    pub fn inner_iterable(&self) -> Option<&Ty> {
65        match self {
66            Ty::Array(ty) => Some(ty.as_ref()),
67            _ => None,
68        }
69    }
70
71    pub fn is_primitive(&self) -> bool {
72        match self {
73            Ty::String => true,
74            Ty::Integer { .. } => true,
75            Ty::Float => true,
76            Ty::Boolean => true,
77            Ty::Array(_) => false,
78            Ty::HashMap(_) => false,
79            Ty::Model(_) => false,
80            Ty::Any(_) => false,
81            Ty::Unit => true,
82            Ty::Date { .. } => true,
83            Ty::Currency { .. } => true,
84            Ty::DateTime => true,
85        }
86    }
87
88    pub fn model(s: &str) -> Self {
89        if s.contains('(') {
90            panic!("Model names should not contain parens: {}", s);
91        }
92        Ty::Model(s.to_string())
93    }
94}