wot-td 0.6.2

Web of Things (WoT) Thing Description manipulation
Documentation
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Heterogeneous List
//!
//! It is used for the internals of the extension system.

use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize};

/// Empty type.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Nil;

/// List type.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cons<T, U = Nil> {
    /// The _head_ of the list.
    ///
    /// This generally consists of some content appended to the heterogeneous list.
    #[serde(flatten)]
    pub head: T,

    /// The _tail_ of the list.
    ///
    /// This generally consists of `Nil` or `Cons` containing the rest of the items.
    #[serde(flatten)]
    pub tail: U,
}

impl Nil {
    /// Prepend a new `head` the heterogeneous list.
    #[inline]
    pub fn cons<T>(value: T) -> Cons<T, Nil> {
        Cons {
            head: value,
            tail: Nil,
        }
    }
}

impl<T, U> Cons<T, U> {
    /// Prepend a new `head` the heterogeneous list.
    #[inline]
    pub fn cons<V>(self, value: V) -> Cons<V, Self> {
        Cons {
            head: value,
            tail: self,
        }
    }

    /// Split the head element of the heterogeneous list.
    pub fn split_head(self) -> (T, U) {
        let Cons { head, tail } = self;

        (head, tail)
    }
}

/// A conversion from an heterogenous list of values into an heterogenous list of references.
pub trait HListRef {
    /// The heterogenous list of references.
    type Target;

    /// Create a heterogeneous list of references.
    fn to_ref(self) -> Self::Target;
}

impl<'a, T, U> HListRef for &'a Cons<T, U>
where
    &'a U: HListRef,
{
    type Target = Cons<&'a T, <&'a U as HListRef>::Target>;

    #[inline]
    fn to_ref(self) -> Self::Target {
        let Cons { head, tail } = self;
        Cons {
            head,
            tail: tail.to_ref(),
        }
    }
}

impl<'a> HListRef for &'a Nil {
    type Target = Nil;

    #[inline]
    fn to_ref(self) -> Self::Target {
        Nil
    }
}

/// A conversion from an heterogenous list of values into an heterogenous list of mutable
/// references.
pub trait HListMut {
    /// The heterogenous list of mutable references.
    type Target;

    // This is ignored because `HListMut` must be implemented for mutable references only,
    // therefore `to_mut` must take `self`. The reason behind this design is because we don't have
    // GATs on stable in order to write something like this:
    // ```
    // trait HList {
    //     type ToRef<'a> where Self: 'a;
    //     type ToMut<'a> where Self: 'a;
    //
    //     fn to_ref(&self) -> Self::ToRef<'_>;
    //     fn to_mut(&mut self) -> Self::ToMut<'_>;
    // }
    // ```
    /// Create a heterogeneous list of mutable references
    #[allow(clippy::wrong_self_convention)]
    fn to_mut(self) -> Self::Target;
}

impl<'a, T, U> HListMut for &'a mut Cons<T, U>
where
    &'a mut U: HListMut,
{
    type Target = Cons<&'a mut T, <&'a mut U as HListMut>::Target>;

    #[inline]
    fn to_mut(self) -> Self::Target {
        let Cons { head, tail } = self;
        Cons {
            head,
            tail: tail.to_mut(),
        }
    }
}

impl<'a> HListMut for &'a mut Nil {
    type Target = Nil;

    #[inline]
    fn to_mut(self) -> Self::Target {
        Nil
    }
}

/// An interface for non-empty heterogenous lists.
pub trait NonEmptyHList {
    /// The _initial_ part of the list.
    ///
    /// This type consists of an heterogenous list containing all the elements of the list except
    /// for the last one.
    type Init;

    /// The last element of the list.
    type Last;

    /// An heterogenous list with all the elements placed in reverse order.
    type Reversed;

    /// Split the last element of an heterogeneous list
    ///
    /// Return a tuple with the last element and a list containing the remainder.
    fn split_last(self) -> (Self::Last, Self::Init);
    /// Create a heterogeneous list with the elements in reverse order
    fn reverse(self) -> Self::Reversed;
}

impl<T> NonEmptyHList for Cons<T, Nil> {
    type Last = T;
    type Init = Nil;
    type Reversed = Self;

    #[inline]
    fn split_last(self) -> (Self::Last, Self::Init) {
        let Self { head, tail } = self;

        (head, tail)
    }

    #[inline]
    fn reverse(self) -> Self::Reversed {
        self
    }
}

impl<T, U> NonEmptyHList for Cons<T, U>
where
    U: NonEmptyHList,
    Cons<T, U::Init>: NonEmptyHList,
{
    type Init = Cons<T, U::Init>;
    type Last = U::Last;
    type Reversed = Cons<Self::Last, <Self::Init as NonEmptyHList>::Reversed>;

    #[inline]
    fn split_last(self) -> (Self::Last, Self::Init) {
        let Self { head, tail } = self;
        let (last, tail) = tail.split_last();
        let init = Cons { head, tail };
        (last, init)
    }

    #[inline]
    fn reverse(self) -> Self::Reversed {
        let (last, init) = self.split_last();
        let tail = init.reverse();
        Cons { head: last, tail }
    }
}

impl Serialize for Nil {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_struct("Nil", 0)?.end()
    }
}

impl<'de> Deserialize<'de> for Nil {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct NilStruct {}

        NilStruct::deserialize(deserializer)?;
        Ok(Nil)
    }
}

impl From<()> for Nil {
    fn from(_: ()) -> Self {
        Nil
    }
}

impl From<Nil> for () {
    fn from(_: Nil) -> Self {}
}

#[cfg(test)]
mod tests {
    use alloc::string::*;
    use serde_json::{json, Value};

    use super::*;

    #[test]
    fn split_head() {
        #[derive(Debug, PartialEq)]
        struct A(i32);

        #[derive(Debug, PartialEq)]
        struct B(f32);

        #[derive(Debug, PartialEq)]
        struct C(String);

        let list = Nil::cons(A(42)).cons(B(1.234)).cons(C("C".to_string()));

        assert_eq!(
            list.split_head(),
            (C("C".to_string()), Nil::cons(A(42)).cons(B(1.234))),
        )
    }

    #[test]
    fn chain() {
        let list = Nil::cons("A").cons(2).cons("C".to_string());

        assert_eq!(
            list,
            Cons {
                head: "C".to_string(),
                tail: Cons {
                    head: 2,
                    tail: Cons {
                        head: "A",
                        tail: Nil,
                    },
                }
            }
        );
    }

    #[test]
    fn serialize_flatten_nil() {
        #[derive(Debug, Serialize)]
        struct A {
            a: i32,
            #[serde(flatten)]
            b: Nil,
        }

        let value = serde_json::to_value(A { a: 42, b: Nil {} }).unwrap();
        assert_eq!(value.get("a").unwrap(), &Value::Number(42.into()));
        assert!(value.get("b").is_none());
    }

    #[test]
    fn serialize_cons() {
        #[derive(Debug, Serialize)]
        struct C {
            bar: &'static str,
        }
        #[derive(Debug, Serialize)]
        struct B {
            foo: usize,
        }
        #[derive(Debug, Serialize)]
        struct A {
            a: i32,
            #[serde(flatten)]
            b: Cons<C, Cons<B, Nil>>,
        }

        let value = serde_json::to_value(A {
            a: 42,
            b: Nil::cons(B { foo: 42 }).cons(C { bar: "42" }),
        })
        .unwrap();
        assert_eq!(value.get("a").unwrap(), &Value::Number(42.into()));
        assert_eq!(value.get("foo").unwrap(), &Value::Number(42.into()));
    }

    #[test]
    fn deserialize_cons() {
        #[derive(Debug, Deserialize)]
        struct C {
            bar: String,
        }
        #[derive(Debug, Deserialize)]
        struct B {
            foo: usize,
        }
        #[derive(Debug, Deserialize)]
        struct A {
            a: i32,
            #[serde(flatten)]
            b: Cons<Cons<B, C>, Nil>,
        }

        let v = json!({
            "a": 42,
            "foo": 42,
            "bar": "42",
        });

        let a: A = serde_json::from_value(v).unwrap();

        assert_eq!(a.a, 42);
        assert_eq!(a.b.head.head.foo, 42);
        assert_eq!(a.b.head.tail.bar, String::from("42"));
    }

    #[test]
    fn to_ref() {
        #[derive(Debug, PartialEq)]
        struct A(i32);

        #[derive(Debug, PartialEq)]
        struct B(f32);

        #[derive(Debug, PartialEq)]
        struct C(String);

        let list = Nil::cons(A(42)).cons(B(1.234)).cons(C("hello".to_string()));

        assert_eq!(
            list.to_ref(),
            Nil::cons(&A(42))
                .cons(&B(1.234))
                .cons(&C("hello".to_string())),
        )
    }

    #[test]
    fn to_mut() {
        #[derive(Debug, PartialEq)]
        struct A(i32);

        #[derive(Debug, PartialEq)]
        struct B(f32);

        #[derive(Debug, PartialEq)]
        struct C(String);

        let mut list = Nil::cons(A(42)).cons(B(1.234)).cons(C("hello".to_string()));

        assert_eq!(
            list.to_mut(),
            Nil::cons(&mut A(42))
                .cons(&mut B(1.234))
                .cons(&mut C("hello".to_string())),
        )
    }

    #[test]
    fn split_last() {
        #[derive(Debug, PartialEq)]
        struct A(i32);

        #[derive(Debug, PartialEq)]
        struct B(f32);

        #[derive(Debug, PartialEq)]
        struct C(String);

        let list = Nil::cons(A(42)).cons(B(1.234)).cons(C("hello".to_string()));

        let (last, init) = list.split_last();
        assert_eq!(last, A(42));
        assert_eq!(init, Nil::cons(B(1.234)).cons(C("hello".to_string())));

        let (last, init) = init.split_last();
        assert_eq!(last, B(1.234));
        assert_eq!(init, Nil::cons(C("hello".to_string())));

        let (last, init) = init.split_last();
        assert_eq!(last, C("hello".to_string()));
        assert_eq!(init, Nil);
    }

    #[test]
    fn reverse() {
        #[derive(Debug, PartialEq)]
        struct A(i32);

        #[derive(Debug, PartialEq)]
        struct B(f32);

        #[derive(Debug, PartialEq)]
        struct C(String);

        let list = Nil::cons(A(42)).cons(B(1.234)).cons(C("hello".to_string()));

        assert_eq!(
            list.reverse(),
            Nil::cons(C("hello".to_string())).cons(B(1.234)).cons(A(42)),
        )
    }
}