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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
mod binary;
mod map;
mod number;
mod option;
mod seq;
mod text;

pub mod tags;

use crate::{
    std::{
        borrow::Borrow,
        fmt,
        hash::{Hash, Hasher},
        marker::PhantomData,
    },
    Result, Stream, Value,
};

#[cfg(feature = "alloc")]
use crate::std::string::String;

pub(crate) use self::number::*;

pub use self::{binary::*, text::*};

/**
A textual label for some value.
*/
pub struct Label<'computed> {
    // This field may point to some external data borrowed for `'computed`
    // or to the `_value_owned` field. It could be a `Cow<'computed, str>`,
    // but this way is cheaper to access because it avoids checking the
    // `Cow` variant
    value_computed: *const str,
    // Only one `backing_field_*` may be `Some`
    backing_field_static: Option<&'static str>,
    #[cfg(feature = "alloc")]
    backing_field_owned: Option<String>,
    _marker: PhantomData<&'computed str>,
}

#[cfg(not(feature = "alloc"))]
impl<'computed> Clone for Label<'computed> {
    fn clone(&self) -> Self {
        Label {
            value_computed: self.value_computed,
            backing_field_static: self.backing_field_static,
            _marker: PhantomData,
        }
    }
}

impl<'computed> Label<'computed> {
    /**
    Create a new label from a static string value.

    For labels that can't satisfy the `'static` lifetime, use [`Label::new_computed`].
    For labels that need owned values, use [`Label::new_owned`].
    */
    pub const fn new(label: &'static str) -> Self {
        Label {
            value_computed: label as *const str,
            backing_field_static: Some(label),
            #[cfg(feature = "alloc")]
            backing_field_owned: None,
            _marker: PhantomData,
        }
    }

    /**
    Create a new label from a string value borrowed for the `'computed` lifetime.
    */
    pub const fn new_computed(label: &'computed str) -> Self {
        Label {
            value_computed: label as *const str,
            backing_field_static: None,
            #[cfg(feature = "alloc")]
            backing_field_owned: None,
            _marker: PhantomData,
        }
    }

    /**
    Get the value of the label as a string.
    */
    pub const fn as_str(&self) -> &str {
        // SAFETY: The borrow of the `value_computed` field can't outlive
        // the label itself, so even if `value_computed` points to `_value_owned`
        // it will never dangle.
        unsafe { &*self.value_computed }
    }

    /**
    Try get the value of the label as a static string.

    For labels that were created over computed data this method will return `None`.
    */
    pub const fn as_static_str(&self) -> Option<&'static str> {
        self.backing_field_static
    }
}

impl<'a, 'b> PartialEq<Label<'b>> for Label<'a> {
    fn eq(&self, other: &Label<'b>) -> bool {
        self.as_str() == other.as_str()
    }
}

impl<'a> Eq for Label<'a> {}

impl<'a> Hash for Label<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_str().hash(state)
    }
}

impl<'a> Borrow<str> for Label<'a> {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<'a> fmt::Debug for Label<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Label").field(&self.as_str()).finish()
    }
}

/**
A type tag for a value.

Tags are additional hints that a stream may use to interpret a value differently,
or to avoid some unnecessary work.

The contents of a tag aren't considered public, only equality between two tag identifiers.
*/
#[derive(Clone, PartialEq, Eq)]
pub struct Tag {
    id: u64,
    data: &'static str,
}

impl Tag {
    /**
    Create a new tag from a static string value.
    */
    pub const fn new(data: &'static str) -> Self {
        // Fast, non-cryptographic hash used by rustc and Firefox.
        // Adapted from: https://github.com/rust-lang/rustc-hash/blob/master/src/lib.rs to work in CTFE
        //
        // We use hashes for quick tag comparison, if they collide then we'll compare the full value
        const fn compute_id(bytes: &[u8]) -> u64 {
            // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
            // file at the top-level directory of this distribution and at
            // http://rust-lang.org/COPYRIGHT.
            //
            // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
            // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
            // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
            // option. This file may not be copied, modified, or distributed
            // except according to those terms.

            const K: u64 = 0x517cc1b727220a95u64;

            let mut hash = 0u64;
            let mut b = 0;

            while b + 8 <= bytes.len() {
                let i = [
                    bytes[b + 0],
                    bytes[b + 1],
                    bytes[b + 2],
                    bytes[b + 3],
                    bytes[b + 4],
                    bytes[b + 5],
                    bytes[b + 6],
                    bytes[b + 7],
                ];

                let i = u64::from_ne_bytes(i);

                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);

                b += 8;
            }

            if b + 4 <= bytes.len() {
                let i = [bytes[b + 0], bytes[b + 1], bytes[b + 2], bytes[b + 3]];

                let i = u32::from_ne_bytes(i) as u64;

                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);

                b += 4;
            }

            if b + 2 <= bytes.len() {
                let i = [bytes[b + 0], bytes[b + 1]];

                let i = u16::from_ne_bytes(i) as u64;

                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);

                b += 2;
            }

            if b + 1 <= bytes.len() {
                let i = bytes[b + 0] as u64;

                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);
            }

            hash
        }

        Tag {
            id: compute_id(data.as_bytes()),
            data,
        }
    }
}

impl fmt::Debug for Tag {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Tag").field(&self.data).finish()
    }
}

/**
The index of a value in its parent context.
*/
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Index(usize);

impl Index {
    /**
    Create a new index from a numeric value.
    */
    pub const fn new(index: usize) -> Self {
        Index(index)
    }

    /**
    Create a new index from a 32bit numeric value.
    */
    pub const fn new_u32(index: u32) -> Self {
        Index(index as usize)
    }

    /**
    Try get the index as a numeric value.
    */
    pub const fn to_usize(&self) -> Option<usize> {
        Some(self.0)
    }

    /**
    Try get the index as a 32-bit numeric value.
    */
    pub const fn to_u32(&self) -> Option<u32> {
        if self.0 <= u32::MAX as usize {
            Some(self.0 as u32)
        } else {
            None
        }
    }
}

impl fmt::Debug for Index {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Index").field(&self.0).finish()
    }
}

impl Value for () {
    fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result {
        stream.tag(Some(&tags::RUST_UNIT), None, None)
    }
}

impl Value for bool {
    fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result {
        stream.bool(*self)
    }

    fn to_bool(&self) -> Option<bool> {
        Some(*self)
    }
}

#[cfg(feature = "alloc")]
mod alloc_support {
    use super::*;

    use crate::std::string::String;

    impl<'computed> Clone for Label<'computed> {
        fn clone(&self) -> Self {
            if let Some(ref owned) = self.backing_field_owned {
                Label::new_owned(owned.clone())
            } else {
                Label {
                    value_computed: self.value_computed,
                    backing_field_static: self.backing_field_static,
                    backing_field_owned: None,
                    _marker: PhantomData,
                }
            }
        }
    }

    impl<'computed> Label<'computed> {
        /**
        Create an owned label from this one.

        This method will allocate if the label isn't based on a static string.
        */
        pub fn to_owned(&self) -> Label<'static> {
            if let Some(backing_field_static) = self.backing_field_static {
                Label::new(backing_field_static)
            } else {
                Label::new_owned(self.as_str().into())
            }
        }
    }

    impl Label<'static> {
        /**
        Create a new label from an owned string value.
        */
        pub fn new_owned(label: String) -> Self {
            Label {
                value_computed: label.as_str() as *const str,
                backing_field_static: None,
                backing_field_owned: Some(label),
                _marker: PhantomData,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn label_static() {
        let label = Label::new("a");

        assert_eq!("a", label.as_static_str().unwrap());
        assert_eq!("a", label.as_str());
    }

    #[test]
    fn label_computed() {
        let label = Label::new_computed("a");

        assert!(label.as_static_str().is_none());
        assert_eq!("a", label.as_str());
    }

    #[test]
    fn label_eq() {
        let a = Label::new("a");
        let b = Label::new_computed("a");
        let c = Label::new("b");

        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn label_clone() {
        let a = Label::new("a");
        let b = a.clone();

        assert_eq!(a.value_computed, b.value_computed);
        assert_eq!(a.backing_field_static, b.backing_field_static);
    }

    #[test]
    fn index() {
        let small = Index::new(1);
        let large = Index::new(usize::MAX);

        if usize::MAX > (u32::MAX as usize) {
            assert!(large.to_u32().is_none());
        }

        assert_eq!(1, small.to_u32().unwrap());
    }

    #[test]
    fn index_eq() {
        let a = Index::new(1);
        let b = Index::new_u32(1);
        let c = Index::new(2);

        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn tag_eq() {
        let a = Tag::new("a");
        let b = Tag::new("a");
        let c = Tag::new("b");

        assert_eq!(a.id, b.id);
        assert_ne!(a.id, c.id);

        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn tag_match() {
        const A: Tag = Tag::new("a");

        let a = Tag::new("a");

        match a {
            A => (),
            _ => panic!("unexpected tag `{:?}`", a),
        }
    }

    #[cfg(feature = "alloc")]
    mod alloc_support {
        use crate::data::*;

        #[test]
        fn label_owned() {
            let label = Label::new_owned(String::from("a"));

            assert!(label.as_static_str().is_none());
            assert_eq!("a", label.as_str());
        }

        #[test]
        fn label_owned_clone() {
            let a = Label::new_owned(String::from("a"));
            let b = a.clone();

            assert_ne!(
                a.backing_field_owned.as_ref().unwrap().as_ptr(),
                b.backing_field_owned.as_ref().unwrap().as_ptr()
            );
        }
    }
}