Skip to main content

suiteki/
impls.rs

1use core::fmt;
2use core::{
3    cmp::Ordering,
4    convert::Infallible,
5    fmt::Display,
6    hash::{Hash, Hasher},
7    ops::{Add, AddAssign, Deref, Index},
8    slice::SliceIndex,
9    str::FromStr,
10};
11
12use alloc::string::String;
13
14use crate::Str;
15
16impl Hash for Str {
17    fn hash<H: Hasher>(&self, state: &mut H) {
18        self.deref().hash(state);
19    }
20}
21
22impl PartialEq for Str {
23    #[inline]
24    fn eq(&self, other: &Self) -> bool {
25        let left = self.as_str();
26        let right = other.as_str();
27        left.len() == right.len() && (core::ptr::eq(left.as_ptr(), right.as_ptr()) || left == right)
28    }
29}
30
31impl PartialEq<&str> for Str {
32    fn eq(&self, other: &&str) -> bool {
33        self.deref().eq(*other)
34    }
35}
36
37impl PartialEq<str> for Str {
38    fn eq(&self, other: &str) -> bool {
39        self.deref().eq(other)
40    }
41}
42
43impl PartialEq<String> for Str {
44    fn eq(&self, other: &String) -> bool {
45        self.deref().eq(other)
46    }
47}
48
49impl PartialEq<Str> for &str {
50    fn eq(&self, other: &Str) -> bool {
51        (*self).eq(&**other)
52    }
53}
54
55impl PartialEq<Str> for str {
56    fn eq(&self, other: &Str) -> bool {
57        self.eq(&**other)
58    }
59}
60
61impl PartialEq<Str> for String {
62    fn eq(&self, other: &Str) -> bool {
63        self.eq(&**other)
64    }
65}
66
67impl<I: SliceIndex<str>> Index<I> for Str {
68    type Output = <I as SliceIndex<str>>::Output;
69    fn index(&self, index: I) -> &Self::Output {
70        self.deref().index(index)
71    }
72}
73
74impl FromStr for Str {
75    type Err = Infallible;
76
77    /// Copies the string, inline when it fits.
78    #[inline]
79    fn from_str(s: &str) -> Result<Self, Self::Err> {
80        Ok(Self::from_borrowed(s))
81    }
82}
83
84impl<S: AsRef<str>> FromIterator<S> for Str {
85    fn from_iter<T: IntoIterator<Item = S>>(iter: T) -> Self {
86        let mut value = Self::new();
87        value.extend_parts(iter);
88        value
89    }
90}
91
92impl Eq for Str {}
93
94impl PartialOrd for Str {
95    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
96        Some(self.cmp(other))
97    }
98}
99
100impl Ord for Str {
101    fn cmp(&self, other: &Self) -> Ordering {
102        self.deref().cmp(&**other)
103    }
104}
105
106impl Display for Str {
107    #[inline]
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        let text = self.as_str();
110        if f.width().is_none() && f.precision().is_none() {
111            f.write_str(text)
112        } else {
113            f.pad(text)
114        }
115    }
116}
117
118/// Prints the string, the way every other string type does.
119///
120/// The derived implementation exposed the tagged representation instead — a
121/// raw pointer and a length that is negative whenever the string is owned — so
122/// `{:?}` on a `Str` produced `Str { ptr: .., len: -9 }`. That is unreadable
123/// where `Debug` matters most: assertion failures, tracing fields, and the
124/// `{:?}` of any type holding one.
125impl fmt::Debug for Str {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        fmt::Debug::fmt(&**self, f)
128    }
129}
130
131impl<'a> Extend<&'a str> for Str {
132    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
133        self.extend_parts(iter);
134    }
135}
136
137impl Extend<String> for Str {
138    fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
139        self.extend_parts(iter);
140    }
141}
142
143impl Extend<Self> for Str {
144    fn extend<T: IntoIterator<Item = Self>>(&mut self, iter: T) {
145        self.extend_parts(iter);
146    }
147}
148
149impl<T> Add<T> for &Str
150where
151    T: AsRef<str>,
152{
153    type Output = Str;
154    fn add(self, rhs: T) -> Self::Output {
155        self.clone().add(rhs)
156    }
157}
158
159impl<T> Add<T> for Str
160where
161    T: AsRef<str>,
162{
163    type Output = Self;
164    fn add(mut self, rhs: T) -> Self::Output {
165        self.append(rhs);
166        self
167    }
168}
169
170impl<T> AddAssign<T> for Str
171where
172    T: AsRef<str>,
173{
174    fn add_assign(&mut self, rhs: T) {
175        self.append(rhs);
176    }
177}
178
179#[cfg(feature = "serde")]
180mod serde {
181    use core::fmt;
182    use core::ops::Deref;
183
184    use super::Str;
185    use alloc::string::String;
186    use serde::{Deserialize, Deserializer, Serialize, de::Visitor};
187    struct StrVisitor;
188
189    impl Serialize for Str {
190        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
191        where
192            S: serde::Serializer,
193        {
194            self.deref().serialize(serializer)
195        }
196    }
197
198    impl Visitor<'_> for StrVisitor {
199        type Value = Str;
200
201        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
202            formatter.write_str("a string")
203        }
204
205        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
206            Ok(Str::from_borrowed(v))
207        }
208
209        fn visit_string<E>(self, v: String) -> Result<Self::Value, E> {
210            Ok(v.into())
211        }
212    }
213
214    impl<'de> Deserialize<'de> for Str {
215        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
216        where
217            D: Deserializer<'de>,
218        {
219            deserializer.deserialize_string(StrVisitor)
220        }
221    }
222}