]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/small_str.rs
Rollup merge of #94145 - ssomers:binary_heap_tests, r=jyn514
[rust.git] / compiler / rustc_data_structures / src / small_str.rs
1 use smallvec::SmallVec;
2
3 #[cfg(test)]
4 mod tests;
5
6 /// Like SmallVec but for strings.
7 #[derive(Default)]
8 pub struct SmallStr<const N: usize>(SmallVec<[u8; N]>);
9
10 impl<const N: usize> SmallStr<N> {
11     #[inline]
12     pub fn new() -> Self {
13         SmallStr(SmallVec::default())
14     }
15
16     #[inline]
17     pub fn push_str(&mut self, s: &str) {
18         self.0.extend_from_slice(s.as_bytes());
19     }
20
21     #[inline]
22     pub fn empty(&self) -> bool {
23         self.0.is_empty()
24     }
25
26     #[inline]
27     pub fn spilled(&self) -> bool {
28         self.0.spilled()
29     }
30
31     #[inline]
32     pub fn as_str(&self) -> &str {
33         unsafe { std::str::from_utf8_unchecked(self.0.as_slice()) }
34     }
35 }
36
37 impl<const N: usize> std::ops::Deref for SmallStr<N> {
38     type Target = str;
39
40     #[inline]
41     fn deref(&self) -> &str {
42         self.as_str()
43     }
44 }
45
46 impl<const N: usize, A: AsRef<str>> FromIterator<A> for SmallStr<N> {
47     #[inline]
48     fn from_iter<T>(iter: T) -> Self
49     where
50         T: IntoIterator<Item = A>,
51     {
52         let mut s = SmallStr::default();
53         s.extend(iter);
54         s
55     }
56 }
57
58 impl<const N: usize, A: AsRef<str>> Extend<A> for SmallStr<N> {
59     #[inline]
60     fn extend<T>(&mut self, iter: T)
61     where
62         T: IntoIterator<Item = A>,
63     {
64         for a in iter.into_iter() {
65             self.push_str(a.as_ref());
66         }
67     }
68 }