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
//! # *Resources* and *entities*
//!
//! Celcat often require a *resource* type (like [`Student`]) in the request to
//! know what it must send back, and sometimes a *resource* ID (like [`StudentId`])
//! which identifies a particular resource.
//! Calcat sends back *entities*, identified by an *entity* type and an *entity* ID.
//!
//! An *entity* can be a *resource*, in which case it has an associated ID.
//! If it isn't a *resource*, is doesn't have an ID (`null` in JSON),
//! and we represent its type with [`Unknown`], and its ID with [`UnknownId`].

use std::{concat, convert::TryFrom, fmt::Debug, stringify};

use paste::paste;
use serde::{Deserialize, Serialize};

/// A *resource* type.
///
/// This trait cannot be implemented outside of this crate.
pub trait ResourceType:
    Debug + Clone + PartialEq + Serialize + for<'de> Deserialize<'de> + private::Sealed
{
    type Id: ResourceId;
}

/// A *resource* ID.
///
/// This trait cannot be implemented outside of this crate.
pub trait ResourceId: EntityId {}

/// An *entity* type.
///
/// This trait cannot be implemented outside of this crate.
pub trait EntityType:
    Debug + Clone + PartialEq + Serialize + for<'de> Deserialize<'de> + private::Sealed
{
    type Id: EntityId;
}

/// An *entity* ID.
///
/// This trait cannot be implemented outside of this crate.
pub trait EntityId:
    Debug + Clone + PartialEq + Serialize + for<'de> Deserialize<'de> + private::Sealed
{
}

macro_rules! if_unknown {
    (
        if Unknown {
            $($i:item)*
        } else {
            $($_:item)*
        }
    ) => {
        $($i)*
    };
    (
        if $not_unknown:ident {
            $($_:item)*
        } else {
            $($i:item)*
        }
    ) => {
        $($i)*
    };
}

macro_rules! if_not_unknown {
    (
        if Unknown {
            $($_:item)*
        }
    ) => { };
    (
        if $not_unknown:ident {
            $($i:item)*
        }
    ) => {
        $($i)*
    };
}

macro_rules! entities {
    (
        $(
            $r:ident = $n:literal,
        )+
    ) => {
        $(
            paste! {
                // TODO: find a way to not write definitions 2 times
                if_unknown! {
                    if $r {
                        #[doc = "The unknown entity type."]
                        #[derive(Debug, Default, Clone, Copy, PartialEq)]
                        #[derive(Serialize, Deserialize)]
                        #[serde(try_from = "u8", into = "u8")]
                        pub struct $r;
                    } else {
                        #[doc = "The " $r:lower " resource type."]
                        #[derive(Debug, Default, Clone, Copy, PartialEq)]
                        #[derive(Serialize, Deserialize)]
                        #[serde(try_from = "u8", into = "u8")]
                        pub struct $r;
                    }
                }

                impl From<$r> for u8 {
                    fn from(_: $r) -> Self {
                        $n
                    }
                }

                impl TryFrom<u8> for $r {
                    type Error = &'static str;
                    fn try_from(n: u8) -> Result<Self, Self::Error> {
                        if n == $n {
                            Ok($r)
                        } else {
                            Err(concat!("expected ", $n, " (", stringify!($r), ")"))
                        }
                    }
                }

                impl private::Sealed for $r {}
                impl EntityType for $r {
                    type Id = [<$r Id>];
                }
                if_not_unknown! {
                    if $r {
                        impl ResourceType for $r {
                            type Id = [<$r Id>];
                        }
                    }
                }

                if_unknown! {
                    if $r {
                        #[derive(Debug, Default, Clone, PartialEq)]
                        #[derive(Serialize, Deserialize)]
                        #[serde(from = "()", into = "()")]
                        pub struct [<$r Id>];
                        impl From<[<$r Id>]> for () {
                            fn from(_: [<$r Id>]) -> Self {}
                        }
                        impl From<()> for [<$r Id>] {
                            fn from(_: ()) -> Self {
                                Self
                            }
                        }
                    } else {
                        #[derive(Debug, Default, Clone, PartialEq)]
                        #[derive(Serialize, Deserialize)]
                        #[repr(transparent)]
                        pub struct [<$r Id>](pub String);
                    }
                }

                impl private::Sealed for [<$r Id>] {}
                impl EntityId for [<$r Id>] {}
                if_not_unknown! {
                    if $r {
                        impl ResourceId for [<$r Id>] {}
                    }
                }
            }
        )+
    };
}

entities! {
    Unknown = 0,
    Module = 100,
    Staff = 101,
    Room = 102,
    Group = 103,
    Student = 104,
    Team = 105,
    Equipment = 106,
    Course = 107,
}

mod private {
    /// Empty trait that no struct/enum can implement outside of this crate.
    ///
    /// Used as a trait bound for traits that shouldn't be implemented outside of this crate.
    pub trait Sealed {}
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{from_value, json, to_value};

    #[test]
    fn serialize_entity_type() {
        assert_eq!(to_value(Unknown).unwrap(), json!(0));
        assert_eq!(to_value(Student).unwrap(), json!(104));
    }

    #[test]
    fn deserialize_entity_type() {
        from_value::<Unknown>(json!(0)).unwrap();
        from_value::<Group>(json!(103)).unwrap();
        from_value::<Unknown>(json!(100)).unwrap_err();
        from_value::<Staff>(json!(null)).unwrap_err();
    }

    #[test]
    fn serialize_unknown_id() {
        assert_eq!(to_value(UnknownId).unwrap(), json!(null));
    }

    #[test]
    fn deserialize_unknown_id() {
        from_value::<UnknownId>(json!(null)).unwrap();
        from_value::<UnknownId>(json!(100)).unwrap_err();
    }

    #[test]
    fn serialize_room_id() {
        assert_eq!(
            to_value(RoomId("1173077".to_owned())).unwrap(),
            json!("1173077")
        );
    }

    #[test]
    fn deserialize_room_id() {
        assert_eq!(
            from_value::<RoomId>(json!("1172947")).unwrap(),
            RoomId("1172947".to_owned())
        );
        from_value::<RoomId>(json!(1172976)).unwrap_err();
    }
}