summaryrefslogtreecommitdiff
path: root/src/types.rs
blob: d2713daa2db87173caee1da058c2ed463a427e9e (plain)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use jiff::Timestamp;
use jiff::civil::DateTime;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Number, Value};
use std::collections::BTreeMap;
use std::hash::Hash;
use std::str::FromStr;

use crate::request::JMAPError;

// Types
// *, unknown value
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(untagged)]
pub enum JUnknown {
    Object(BTreeMap<String, JUnknown>),
    Array(Vec<JUnknown>),
    Uint(JUint),
    Int(JInt),
    Number(JNumber),
    JDate(JDate),
    JUTCDate(JUTCDate),
    String(String),
    Id(JMAPId),
    Bool(bool),
    Null,
}

/// Implement from for serde_json::Value so that we can use serde to covert unknown to actual types
/// :3
impl From<JUnknown> for Value {
    fn from(value: JUnknown) -> Self {
        match value {
            JUnknown::Number(n) => {
                Value::Number(serde_json::Number::from_f64(n).unwrap_or(Number::from(999)))
            }
            JUnknown::Int(n) => Value::Number(serde_json::Number::from(n)),
            JUnknown::Uint(n) => Value::Number(serde_json::Number::from(n)),
            JUnknown::JDate(jdate) => Value::String(jdate.0.to_string()),
            JUnknown::JUTCDate(jdate) => Value::String(jdate.0.to_string()),
            JUnknown::Object(btree_map) => {
                let mut map = serde_json::map::Map::with_capacity(btree_map.len());
                for (k, v) in btree_map.into_iter() {
                    let val = v.into();
                    map.insert(k, val);
                }
                Value::Object(map)
            }
            JUnknown::Array(junknowns) => {
                Value::Array(junknowns.into_iter().map(|x| x.into()).collect())
            }
            JUnknown::String(x) => Value::String(x),
            JUnknown::Id(jmapid) => Value::String(jmapid.0),
            JUnknown::Bool(bool) => Value::Bool(bool),
            JUnknown::Null => Value::Null,
        }
    }
}

impl<T: Into<JUnknown>> From<JArr<T>> for JUnknown {
    fn from(value: JArr<T>) -> Self {
        Self::Array(value.into_iter().map(|x| x.into()).collect())
    }
}

impl<K: Into<String>, V: Into<JUnknown>> From<JObj<K, V>> for JUnknown {
    fn from(value: JObj<K, V>) -> Self {
        Self::Object(
            value
                .into_iter()
                .map(|x| (x.0.into(), x.1.into()))
                .collect(),
        )
    }
}

impl From<JUint> for JUnknown {
    fn from(value: JUint) -> Self {
        Self::Uint(value)
    }
}
impl From<JInt> for JUnknown {
    fn from(value: JInt) -> Self {
        Self::Int(value)
    }
}

impl From<JDate> for JUnknown {
    fn from(value: JDate) -> Self {
        Self::JDate(value)
    }
}
impl From<JUTCDate> for JUnknown {
    fn from(value: JUTCDate) -> Self {
        Self::JUTCDate(value)
    }
}

impl From<String> for JUnknown {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<JMAPId> for JUnknown {
    fn from(value: JMAPId) -> Self {
        Self::Id(value)
    }
}

pub fn from_junknown<T: DeserializeOwned, J: Into<JUnknown>>(
    ju: J,
) -> Result<T, serde_json::Error> {
    let junk: JUnknown = ju.into();
    serde_json::from_value(junk.into())
}

pub fn to_junknown<T: Serialize>(value: T) -> Result<JUnknown, serde_json::Error> {
    serde_json::to_value(value).and_then(serde_json::from_value)
}

// JSON String type
// pub type JString  = String;
// JSON Number type
pub type JNumber = f64;
// JSON Boolean type
// pub type JBool    = bool;
// A[B] is a JSON object where keys are all of type A and values type B;
pub type JObj<A, B>
where
    A: Serialize,
    B: Serialize,
    A: DeserializeOwned,
    B: DeserializeOwned,
= BTreeMap<A, B>;

pub type JObject = JObj<String, JUnknown>;
/// A[] is an array of type A
pub type JArr<A>
where
    A: Serialize,
    A: DeserializeOwned,
= Vec<A>;

//}}}
// 1.2 The ID data type {{{

/// The ID data type
/// Where Id is given as a data type, it means a String of at least 1 and a maximum of 255 octets in size,
/// and it MUST only contain characters from the "URL and Filename Safe" base64 alphabet, as defined in Section 5 of [RFC4648],
/// excluding the pad character (=). This means the allowed characters are the ASCII alphanumeric characters (A-Za-z0-9), hyphen (-), and underscore (_).
/// TODO: Add the restrictions above
#[derive(Serialize, Deserialize, Clone, Hash, Eq, PartialEq, PartialOrd, Ord, Debug)]
pub struct JMAPId(pub String);

impl FromStr for JMAPId {
    type Err = JMAPError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() > 255 || s.len() < 1 {
            return Err(JMAPError::ParseError("Invalid ID size".to_string()));
        }

        let mut out = String::with_capacity(s.len());
        for c in s.chars() {
            if !(c.is_ascii_alphanumeric() || c == '-' || c == '_') {
                return Err(JMAPError::ParseError(format!(
                    "ID {} contains invalid character {}",
                    s, c
                )));
            }

            out.push(c);
        }

        Ok(Self(out))
    }
}

impl AsRef<str> for JMAPId {
    fn as_ref(&self) -> &str {
        return &self.0;
    }
}

//}}}
// 1.3 Int and UnsignedInt {{{
pub type JInt = i64;
pub type JUint = u64;

// }}}
// 1.4 Date and UTCDate data Types {{{

/// Where date is given a type, it meanse a string in date-time format [RFC3339].
/// TODO: To ensure a normalized form, the time-setfrac MUST always be ommitted if zero, and any
/// letters in the string (eg. "T" and "Z") must be uppercase.

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, PartialOrd)]
pub struct JDate(DateTime);
impl JDate {
    /// Convert from a JUTCDate type to system time
    pub fn from_utcdate(date: JDate) -> Self {
        // FIXME: unwrap
        Self(
            date.0
                .to_zoned(jiff::tz::TimeZone::system())
                .unwrap()
                .datetime(),
        )
    }
    /// Parse from a string
    pub fn from_string(str: &str) -> Result<Self, jiff::Error> {
        Ok(Self(str.parse()?))
    }
    /// Get the inner date for reading purposes
    pub fn get_date(&self) -> &DateTime {
        &self.0
    }

    /// Convert from jiff datetime
    pub fn from_datetime(datetime: DateTime) -> Self {
        Self(datetime)
    }
}

/// Where UTCDate is given as a type, it means a Date where the time-offset component MUST be Z (i.e., it must be in UTC time). For example, 2014-10-30T06:12:00Z
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, PartialOrd)]
pub struct JUTCDate(Timestamp);
impl JUTCDate {
    /// Convert from a JDate type
    pub fn from_date(date: JDate) -> Self {
        // FIXME: unwrap
        Self(
            date.0
                .to_zoned(jiff::tz::TimeZone::UTC)
                .unwrap()
                .timestamp(),
        )
    }

    /// Parse from a string
    pub fn from_string(str: &str) -> Result<Self, jiff::Error> {
        Ok(Self(
            str.parse::<jiff::Timestamp>()?
                .to_zoned(jiff::tz::TimeZone::UTC)
                .timestamp(),
        ))
    }

    /// Get the date (converted)
    pub fn get_date(&self) -> DateTime {
        self.0.to_zoned(jiff::tz::TimeZone::UTC).datetime()
    }

    /// Convert from jiff datetime
    pub fn from_datetime(datetime: DateTime) -> Self {
        // FIXME: unwrap
        Self(
            datetime
                .to_zoned(jiff::tz::TimeZone::UTC)
                .unwrap()
                .timestamp(),
        )
    }
}
//}}}