sval/
data.rs

1mod binary;
2mod map;
3mod number;
4mod option;
5mod seq;
6mod text;
7
8pub mod tags;
9
10use crate::{
11    std::{
12        borrow::Borrow,
13        cmp::Ordering,
14        fmt,
15        hash::{Hash, Hasher},
16        marker::PhantomData,
17    },
18    Result, Stream, Value,
19};
20
21#[cfg(feature = "alloc")]
22use crate::std::boxed::Box;
23
24pub use self::{binary::*, map::*, number::*, option::*, text::*};
25
26/**
27A textual label for some value.
28*/
29pub struct Label<'computed> {
30    // This field may point to some external data borrowed for `'computed`
31    // or to the `_value_owned` field. It could be a `Cow<'computed, str>`,
32    // but this way is cheaper to access because it avoids checking the
33    // `Cow` variant
34    value_computed: *const str,
35    // Only one `backing_field_*` may be `Some`
36    backing_field_static: Option<&'static str>,
37    #[cfg(feature = "alloc")]
38    // Owned is a `Box<str>`
39    backing_field_owned: Option<*mut str>,
40    tag: Option<Tag>,
41    _marker: PhantomData<&'computed str>,
42}
43
44impl<'computed> Drop for Label<'computed> {
45    fn drop(&mut self) {
46        #[cfg(feature = "alloc")]
47        {
48            if let Some(owned) = self.backing_field_owned {
49                // SAFETY: We're dropping the value
50                drop(unsafe { Box::from_raw(owned) });
51            }
52        }
53    }
54}
55
56// SAFETY: Label doesn't mutate or synchronize: it acts just like a `&str`
57unsafe impl<'computed> Send for Label<'computed> {}
58// SAFETY: Label doesn't mutate or synchronize: it acts just like a `&str`
59unsafe impl<'computed> Sync for Label<'computed> {}
60
61#[cfg(not(feature = "alloc"))]
62impl<'computed> Clone for Label<'computed> {
63    fn clone(&self) -> Self {
64        Label {
65            value_computed: self.value_computed,
66            backing_field_static: self.backing_field_static,
67            tag: self.tag.clone(),
68            _marker: PhantomData,
69        }
70    }
71}
72
73impl<'computed> Label<'computed> {
74    /**
75    Create a new label from a static string value.
76
77    For labels that can't satisfy the `'static` lifetime, use [`Label::new_computed`].
78    For labels that need owned values, use [`Label::new_owned`].
79    */
80    #[inline(always)]
81    pub const fn new(label: &'static str) -> Self {
82        Label {
83            value_computed: label as *const str,
84            backing_field_static: Some(label),
85            #[cfg(feature = "alloc")]
86            backing_field_owned: None,
87            tag: None,
88            _marker: PhantomData,
89        }
90    }
91
92    /**
93    Create a new label from a string value borrowed for the `'computed` lifetime.
94    */
95    #[inline(always)]
96    pub const fn new_computed(label: &'computed str) -> Self {
97        Label {
98            value_computed: label as *const str,
99            backing_field_static: None,
100            #[cfg(feature = "alloc")]
101            backing_field_owned: None,
102            tag: None,
103            _marker: PhantomData,
104        }
105    }
106
107    /**
108    Get the value of the label as a string.
109    */
110    #[inline(always)]
111    pub const fn as_str(&self) -> &str {
112        // SAFETY: The borrow of the `value_computed` field can't outlive
113        // the label itself, so even if `value_computed` points to `_value_owned`
114        // it will never dangle.
115        unsafe { &*self.value_computed }
116    }
117
118    /**
119    Try get the value of the label as a static string.
120
121    For labels that were created over computed data this method will return `None`.
122    */
123    #[inline(always)]
124    pub const fn as_static_str(&self) -> Option<&'static str> {
125        self.backing_field_static
126    }
127
128    /**
129    Associate a tag as a hint with this label.
130
131    Tags don't contribute to equality or ordering of labels but streams may
132    use the them when interpreting the label value.
133     */
134    #[inline(always)]
135    pub const fn with_tag(mut self, tag: &Tag) -> Self {
136        self.tag = Some(tag.cloned());
137        self
138    }
139
140    /**
141    Get the tag hint associated with the label, if present.
142
143    Streams may use the tag when interpreting the label value.
144     */
145    #[inline(always)]
146    pub const fn tag(&self) -> Option<&Tag> {
147        self.tag.as_ref()
148    }
149
150    /**
151    Try create an owned label from this one.
152
153    This method will always return `Ok` if the `alloc` feature is enabled.
154    If the `alloc` feature is not enabled then this method will only return `Ok`
155    if the underlying value is already `'static`.
156    */
157    #[inline(always)]
158    pub fn try_to_owned(&self) -> Result<Label<'static>> {
159        #[cfg(feature = "alloc")]
160        {
161            Ok(self.to_owned())
162        }
163        #[cfg(not(feature = "alloc"))]
164        {
165            self.as_static_str()
166                .map(Label::new)
167                .ok_or_else(crate::Error::new)
168        }
169    }
170}
171
172impl<'a, 'b> PartialEq<Label<'b>> for Label<'a> {
173    #[inline(always)]
174    fn eq(&self, other: &Label<'b>) -> bool {
175        self.as_str() == other.as_str()
176    }
177}
178
179impl<'a> Eq for Label<'a> {}
180
181impl<'a> Hash for Label<'a> {
182    fn hash<H: Hasher>(&self, state: &mut H) {
183        self.as_str().hash(state)
184    }
185}
186
187impl<'a> Borrow<str> for Label<'a> {
188    #[inline(always)]
189    fn borrow(&self) -> &str {
190        self.as_str()
191    }
192}
193
194impl<'a> fmt::Debug for Label<'a> {
195    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196        f.debug_tuple("Label").field(&self.as_str()).finish()
197    }
198}
199
200/**
201A type tag for a value.
202
203Tags are additional hints that a stream may use to interpret a value differently,
204or to avoid some unnecessary work.
205
206The contents of a tag aren't considered public, only equality between two tag identifiers.
207*/
208#[derive(Clone, PartialEq, Eq)]
209pub struct Tag {
210    id: u64,
211    data: &'static str,
212}
213
214impl Tag {
215    /**
216    Create a new tag from a static string value.
217    */
218    pub const fn new(data: &'static str) -> Self {
219        // Fast, non-cryptographic hash used by rustc and Firefox.
220        // Adapted from: https://github.com/rust-lang/rustc-hash/blob/master/src/lib.rs to work in CTFE
221        //
222        // We use hashes for quick tag comparison, if they collide then we'll compare the full value
223        const fn compute_id(bytes: &[u8]) -> u64 {
224            // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
225            // file at the top-level directory of this distribution and at
226            // http://rust-lang.org/COPYRIGHT.
227            //
228            // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
229            // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
230            // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
231            // option. This file may not be copied, modified, or distributed
232            // except according to those terms.
233
234            const K: u64 = 0x517cc1b727220a95u64;
235
236            let mut hash = 0u64;
237            let mut b = 0;
238
239            while b + 8 <= bytes.len() {
240                let i = [
241                    bytes[b + 0],
242                    bytes[b + 1],
243                    bytes[b + 2],
244                    bytes[b + 3],
245                    bytes[b + 4],
246                    bytes[b + 5],
247                    bytes[b + 6],
248                    bytes[b + 7],
249                ];
250
251                let i = u64::from_ne_bytes(i);
252
253                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);
254
255                b += 8;
256            }
257
258            if b + 4 <= bytes.len() {
259                let i = [bytes[b + 0], bytes[b + 1], bytes[b + 2], bytes[b + 3]];
260
261                let i = u32::from_ne_bytes(i) as u64;
262
263                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);
264
265                b += 4;
266            }
267
268            if b + 2 <= bytes.len() {
269                let i = [bytes[b + 0], bytes[b + 1]];
270
271                let i = u16::from_ne_bytes(i) as u64;
272
273                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);
274
275                b += 2;
276            }
277
278            if b + 1 <= bytes.len() {
279                let i = bytes[b + 0] as u64;
280
281                hash = (hash.rotate_left(5) ^ i).wrapping_mul(K);
282            }
283
284            hash
285        }
286
287        Tag {
288            id: compute_id(data.as_bytes()),
289            data,
290        }
291    }
292
293    // NOTE: This method is only private to avoid exposing it prematurely
294    // There's no real reason we shouldn't
295    #[inline(always)]
296    const fn cloned(&self) -> Tag {
297        Tag {
298            id: self.id,
299            data: self.data,
300        }
301    }
302}
303
304impl fmt::Debug for Tag {
305    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
306        f.debug_tuple("Tag").field(&self.data).finish()
307    }
308}
309
310/**
311The index of a value in its parent context.
312*/
313#[derive(Clone)]
314pub struct Index(i128, Option<Tag>);
315
316impl From<i32> for Index {
317    #[inline(always)]
318    fn from(index: i32) -> Self {
319        Index::new_i32(index)
320    }
321}
322
323impl From<i64> for Index {
324    #[inline(always)]
325    fn from(index: i64) -> Self {
326        Index::new_i64(index)
327    }
328}
329
330impl From<isize> for Index {
331    #[inline(always)]
332    fn from(index: isize) -> Self {
333        Index::new_isize(index)
334    }
335}
336
337impl From<u32> for Index {
338    #[inline(always)]
339    fn from(index: u32) -> Self {
340        Index::new_u32(index)
341    }
342}
343
344impl From<u64> for Index {
345    #[inline(always)]
346    fn from(index: u64) -> Self {
347        Index::new_u64(index)
348    }
349}
350
351impl From<usize> for Index {
352    #[inline(always)]
353    fn from(index: usize) -> Self {
354        Index::new(index)
355    }
356}
357
358impl Index {
359    /**
360    Create a new index from a numeric value.
361    */
362    #[inline(always)]
363    pub const fn new(index: usize) -> Self {
364        Index(index as i128, None)
365    }
366
367    /**
368    Create a new None index from a 32bit numeric value.
369    */
370    #[inline(always)]
371    pub const fn new_u32(index: u32) -> Self {
372        Index(index as i128, None)
373    }
374
375    /**
376    Create a new None index from a 64bit numeric value.
377     */
378    #[inline(always)]
379    pub const fn new_u64(index: u64) -> Self {
380        Index(index as i128, None)
381    }
382
383    /**
384    Create a new None index from a signed 32bit numeric value.
385     */
386    #[inline(always)]
387    pub const fn new_i32(index: i32) -> Self {
388        Index(index as i128, None)
389    }
390
391    /**
392    Create a new None index from a signed 64bit numeric value.
393     */
394    #[inline(always)]
395    pub const fn new_i64(index: i64) -> Self {
396        Index(index as i128, None)
397    }
398
399    /**
400    Create a new None index from a signed numeric value.
401     */
402    #[inline(always)]
403    pub const fn new_isize(index: isize) -> Self {
404        Index(index as i128, None)
405    }
406
407    /**
408    Try get the index as a numeric value.
409    */
410    #[inline]
411    pub const fn to_usize(&self) -> Option<usize> {
412        if self.0 >= usize::MIN as i128 && self.0 <= usize::MAX as i128 {
413            Some(self.0 as usize)
414        } else {
415            None
416        }
417    }
418
419    /**
420    Try get the index as a 32-bit numeric value.
421    */
422    #[inline]
423    pub const fn to_u32(&self) -> Option<u32> {
424        if self.0 >= u32::MIN as i128 && self.0 <= u32::MAX as i128 {
425            Some(self.0 as u32)
426        } else {
427            None
428        }
429    }
430
431    /**
432    Try get the index as a 64-bit numeric value.
433    */
434    #[inline]
435    pub const fn to_u64(&self) -> Option<u64> {
436        if self.0 >= u64::MIN as i128 && self.0 <= u64::MAX as i128 {
437            Some(self.0 as u64)
438        } else {
439            None
440        }
441    }
442
443    /**
444    Try get the index as a signed numeric value.
445     */
446    #[inline]
447    pub const fn to_isize(&self) -> Option<isize> {
448        if self.0 >= isize::MIN as i128 && self.0 <= isize::MAX as i128 {
449            Some(self.0 as isize)
450        } else {
451            None
452        }
453    }
454
455    /**
456    Try get the index as a signed 32-bit numeric value.
457     */
458    #[inline]
459    pub const fn to_i32(&self) -> Option<i32> {
460        if self.0 >= i32::MIN as i128 && self.0 <= i32::MAX as i128 {
461            Some(self.0 as i32)
462        } else {
463            None
464        }
465    }
466
467    /**
468    Try get the index as a signed 64-bit numeric value.
469     */
470    #[inline]
471    pub const fn to_i64(&self) -> Option<i64> {
472        if self.0 >= i64::MIN as i128 && self.0 <= i64::MAX as i128 {
473            Some(self.0 as i64)
474        } else {
475            None
476        }
477    }
478
479    /**
480    Associate a tag as a hint with this index.
481
482    Tags don't contribute to equality or ordering of indexes but streams may
483    use the them when interpreting the index value.
484     */
485    #[inline(always)]
486    pub const fn with_tag(mut self, tag: &Tag) -> Self {
487        self.1 = Some(tag.cloned());
488        self
489    }
490
491    /**
492    Get the tag hint associated with the index, if present.
493
494    Streams may use the tag when interpreting the index value.
495    */
496    #[inline(always)]
497    pub const fn tag(&self) -> Option<&Tag> {
498        self.1.as_ref()
499    }
500}
501
502impl fmt::Debug for Index {
503    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
504        f.debug_struct("Index").field("value", &self.0).finish()
505    }
506}
507
508impl fmt::Display for Index {
509    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
510        fmt::Display::fmt(&self.0, f)
511    }
512}
513
514impl PartialEq for Index {
515    #[inline(always)]
516    fn eq(&self, other: &Self) -> bool {
517        self.0 == other.0
518    }
519}
520
521impl Eq for Index {}
522
523impl PartialOrd for Index {
524    #[inline(always)]
525    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
526        self.0.partial_cmp(&other.0)
527    }
528}
529
530impl Hash for Index {
531    fn hash<H: Hasher>(&self, state: &mut H) {
532        self.0.hash(state)
533    }
534}
535
536impl Ord for Index {
537    #[inline(always)]
538    fn cmp(&self, other: &Self) -> Ordering {
539        self.0.cmp(&other.0)
540    }
541}
542
543impl Value for () {
544    fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result {
545        stream.tag(Some(&tags::RUST_UNIT), None, None)
546    }
547}
548
549impl Value for bool {
550    fn stream<'sval, S: Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> Result {
551        stream.bool(*self)
552    }
553
554    fn tag(&self) -> Option<Tag> {
555        None
556    }
557
558    fn to_bool(&self) -> Option<bool> {
559        Some(*self)
560    }
561}
562
563#[cfg(feature = "alloc")]
564mod alloc_support {
565    use super::*;
566
567    use crate::std::{borrow::ToOwned, string::String};
568
569    impl<'computed> Clone for Label<'computed> {
570        fn clone(&self) -> Self {
571            if let Some(owned) = self.backing_field_owned {
572                // SAFETY: `owned` lives as long as `Label`
573                Label::new_owned(unsafe { &*owned }.to_owned())
574            } else {
575                Label {
576                    value_computed: self.value_computed,
577                    backing_field_static: self.backing_field_static,
578                    backing_field_owned: None,
579                    tag: self.tag.clone(),
580                    _marker: PhantomData,
581                }
582            }
583        }
584    }
585
586    impl<'computed> Label<'computed> {
587        /**
588        Create an owned label from this one.
589
590        This method will allocate if the label isn't based on a static string.
591        */
592        pub fn to_owned(&self) -> Label<'static> {
593            if let Some(backing_field_static) = self.backing_field_static {
594                Label::new(backing_field_static)
595            } else {
596                Label::new_owned(self.as_str().into())
597            }
598        }
599    }
600
601    impl Label<'static> {
602        /**
603        Create a new label from an owned string value.
604        */
605        pub fn new_owned(label: String) -> Self {
606            let owned = Box::into_raw(label.into_boxed_str());
607
608            Label {
609                value_computed: owned as *const str,
610                backing_field_static: None,
611                backing_field_owned: Some(owned),
612                tag: None,
613                _marker: PhantomData,
614            }
615        }
616    }
617}
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622
623    #[test]
624    fn unit_tag() {
625        assert_eq!(Some(tags::RUST_UNIT), ().tag());
626    }
627
628    #[test]
629    fn label_send_sync() {
630        fn assert<T: Send + Sync>() {}
631
632        assert::<Label>();
633    }
634
635    #[test]
636    fn label_static() {
637        let label = Label::new("a");
638
639        assert_eq!("a", label.as_static_str().unwrap());
640        assert_eq!("a", label.as_str());
641    }
642
643    #[test]
644    fn label_computed() {
645        let label = Label::new_computed("a");
646
647        assert!(label.as_static_str().is_none());
648        assert_eq!("a", label.as_str());
649    }
650
651    #[test]
652    fn label_tag() {
653        let label = Label::new("a").with_tag(&tags::VALUE_IDENT);
654
655        assert_eq!(Some(&tags::VALUE_IDENT), label.tag());
656    }
657
658    #[test]
659    fn label_eq() {
660        let a = Label::new("a");
661        let b = Label::new_computed("a");
662        let c = Label::new("b");
663
664        assert_eq!(a, b);
665        assert_ne!(a, c);
666    }
667
668    #[test]
669    fn label_clone() {
670        let a = Label::new("a");
671        let b = a.clone();
672
673        assert_eq!(a.value_computed, b.value_computed);
674        assert_eq!(a.backing_field_static, b.backing_field_static);
675    }
676
677    #[test]
678    fn index_convert() {
679        for (index, to_i32, to_i64, to_u32, to_u64) in [
680            (
681                Index::from(0),
682                Some(0i32),
683                Some(0i64),
684                Some(0u32),
685                Some(0u64),
686            ),
687            (
688                Index::from(i32::MIN),
689                Some(i32::MIN),
690                Some(i32::MIN as i64),
691                None,
692                None,
693            ),
694            (Index::from(i64::MIN), None, Some(i64::MIN), None, None),
695            (
696                Index::from(u32::MAX),
697                None,
698                Some(u32::MAX as i64),
699                Some(u32::MAX),
700                Some(u32::MAX as u64),
701            ),
702            (Index::from(u64::MAX), None, None, None, Some(u64::MAX)),
703        ] {
704            assert_eq!(to_i32, index.to_i32(), "{:?}", index);
705            assert_eq!(to_i64, index.to_i64(), "{:?}", index);
706
707            assert_eq!(to_u32, index.to_u32(), "{:?}", index);
708            assert_eq!(to_u64, index.to_u64(), "{:?}", index);
709        }
710    }
711
712    #[test]
713    fn index_tag() {
714        let index = Index::new(1).with_tag(&tags::VALUE_OFFSET);
715
716        assert_eq!(Some(&tags::VALUE_OFFSET), index.tag());
717    }
718
719    #[test]
720    fn index_eq() {
721        let a = Index::new(1);
722        let b = Index::new_u32(1);
723        let c = Index::new(2);
724
725        assert_eq!(a, b);
726        assert_ne!(a, c);
727    }
728
729    #[test]
730    fn tag_eq() {
731        let a = Tag::new("a");
732        let b = Tag::new("a");
733        let c = Tag::new("b");
734
735        assert_eq!(a.id, b.id);
736        assert_ne!(a.id, c.id);
737
738        assert_eq!(a, b);
739        assert_ne!(a, c);
740    }
741
742    #[test]
743    fn tag_match() {
744        const A: Tag = Tag::new("a");
745
746        let a = Tag::new("a");
747
748        match a {
749            A => (),
750            _ => panic!("unexpected tag `{:?}`", a),
751        }
752    }
753
754    #[cfg(feature = "alloc")]
755    mod alloc_support {
756        use crate::data::*;
757        use crate::std::string::String;
758
759        #[test]
760        fn label_owned() {
761            let label = Label::new_owned(String::from("a"));
762
763            assert!(label.as_static_str().is_none());
764            assert_eq!("a", label.as_str());
765        }
766
767        #[test]
768        fn label_owned_clone() {
769            let a = Label::new_owned(String::from("a"));
770            let b = a.clone();
771
772            assert_ne!(
773                a.backing_field_owned.as_ref().unwrap(),
774                b.backing_field_owned.as_ref().unwrap(),
775            );
776        }
777    }
778}