Skip to main content

yomi_core/value/
str.rs

1//! The `str` value (`StrValue`). Holds a shared string with one thin pointer.
2
3use super::*;
4
5/// A `str` value. The contents are shared (cloning only copies the `Arc`; strings are never modified).
6///
7/// Held as one thin pointer (8 bytes) to keep `Value` small. As a string, it derefs to `&str` via [`std::ops::Deref`].
8#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct StrValue(Arc<String>);
10
11impl StrValue {
12    /// A reference to the string.
13    pub fn as_str(&self) -> &str {
14        &self.0
15    }
16}
17
18impl std::ops::Deref for StrValue {
19    type Target = str;
20    fn deref(&self) -> &str {
21        &self.0
22    }
23}
24
25impl AsRef<str> for StrValue {
26    fn as_ref(&self) -> &str {
27        &self.0
28    }
29}
30
31impl std::borrow::Borrow<str> for StrValue {
32    fn borrow(&self) -> &str {
33        &self.0
34    }
35}
36
37impl std::fmt::Debug for StrValue {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        self.as_str().fmt(f)
40    }
41}
42
43impl std::fmt::Display for StrValue {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        self.as_str().fmt(f)
46    }
47}
48
49impl From<String> for StrValue {
50    fn from(s: String) -> Self {
51        Self(Arc::new(s))
52    }
53}
54
55impl From<&str> for StrValue {
56    fn from(s: &str) -> Self {
57        Self(Arc::new(s.to_owned()))
58    }
59}
60
61impl From<&String> for StrValue {
62    fn from(s: &String) -> Self {
63        Self(Arc::new(s.clone()))
64    }
65}
66
67impl From<Arc<str>> for StrValue {
68    fn from(s: Arc<str>) -> Self {
69        Self(Arc::new(s.to_string()))
70    }
71}
72
73impl From<Box<str>> for StrValue {
74    fn from(s: Box<str>) -> Self {
75        Self(Arc::new(s.into_string()))
76    }
77}
78
79impl From<std::borrow::Cow<'_, str>> for StrValue {
80    fn from(s: std::borrow::Cow<'_, str>) -> Self {
81        Self(Arc::new(s.into_owned()))
82    }
83}
84
85impl PartialEq<str> for StrValue {
86    fn eq(&self, other: &str) -> bool {
87        self.as_str() == other
88    }
89}
90
91impl PartialEq<&str> for StrValue {
92    fn eq(&self, other: &&str) -> bool {
93        self.as_str() == *other
94    }
95}
96
97impl Serialize for StrValue {
98    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
99        ser.serialize_str(self)
100    }
101}
102
103impl<'de> Deserialize<'de> for StrValue {
104    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
105        Ok(String::deserialize(de)?.into())
106    }
107}