summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 5bda0186f404f835e2568c8c7ebfaab7d899ca61 (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
use jiff::civil::DateTime;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Number, Value};
use std::any::Any;
use std::collections::BTreeMap;
use std::collections::btree_map::{Iter, Keys};
use std::hash::Hash;

// 1.1 Notational Conventions {{{
// Types

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

/// 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::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,
        }
    }
}

// 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(String);
//}}}
// 1.3 Int and UnsignedInt {{{
type JInt = i64;
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)]
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)]
pub struct JUTCDate(DateTime);
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().datetime())
    }

    /// 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)
                .datetime(),
        ))
    }

    /// 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 {
        // FIXME: unwrap
        Self(
            datetime
                .to_zoned(jiff::tz::TimeZone::UTC)
                .unwrap()
                .datetime(),
        )
    }
}
//}}}

pub mod capabilities;
/// 2 JMAP Session resource
pub mod session;