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
use std::borrow::Borrow;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::sync::Arc;

// U meaning micro
// a micro-string is either a reference-counted string or a static string
// this guarantees these are cheap to clone everywhere
#[derive(Clone, Eq)]
pub enum UStr {
    Static(&'static str),
    Shared(Arc<str>),
}

impl UStr {
    pub fn new(s: &str) -> Self {
        UStr::Shared(Arc::from(s.to_owned()))
    }
}

impl Deref for UStr {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        match self {
            UStr::Static(s) => s,
            UStr::Shared(s) => s,
        }
    }
}

impl Hash for UStr {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Forward the hash to the string representation of this
        // A derive(Hash) encodes the enum discriminant
        (&**self).hash(state);
    }
}

impl Borrow<str> for UStr {
    #[inline]
    fn borrow(&self) -> &str {
        &**self
    }
}

impl PartialEq<UStr> for UStr {
    fn eq(&self, other: &UStr) -> bool {
        (**self).eq(&**other)
    }
}

impl From<&'static str> for UStr {
    #[inline]
    fn from(s: &'static str) -> Self {
        UStr::Static(s)
    }
}

impl From<String> for UStr {
    #[inline]
    fn from(s: String) -> Self {
        UStr::Shared(s.into())
    }
}

impl Debug for UStr {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.pad(self)
    }
}

impl Display for UStr {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.pad(self)
    }
}

// manual impls because otherwise things get a little screwy with lifetimes

#[cfg(feature = "offline")]
impl<'de> serde::Deserialize<'de> for UStr {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(String::deserialize(deserializer)?.into())
    }
}

#[cfg(feature = "offline")]
impl serde::Serialize for UStr {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self)
    }
}