Debian Codegraph @

src/repr/iter.rs

raw
1 //! Implementations of the [`FromIterator`] trait to make building [`Repr`]s more ergonomic
2
3 use alloc::borrow::Cow;
4 use alloc::boxed::Box;
5 use alloc::string::String;
6
7 use super::{InlineBuffer, Repr, EMPTY, MAX_SIZE};
8 use crate::{CompactString, UnwrapWithMsg};
9
10 impl FromIterator<char> for Repr {
11 #[inline]
12 fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
13 let iter = iter.into_iter();
14
15 let (lower_bound, _) = iter.size_hint();
16 let mut this = match Repr::with_capacity(lower_bound) {
17 Ok(this) => this,
18 Err(_) => EMPTY, // Ignore the error and hope that the lower_bound is incorrect.
19 };
20
21 for c in iter {
22 this.push_str(c.encode_utf8(&mut [0; 4]));
23 }
24 this
25 }
26 }
27
28 impl<'a> FromIterator<&'a char> for Repr {
29 fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
30 iter.into_iter().copied().collect()
31 }
32 }
33
34 fn from_as_ref_str_iterator<S, I>(mut iter: I) -> Repr
35 where
36 S: AsRef<str>,
37 I: Iterator<Item = S>,
38 String: core::iter::Extend<S>,
39 String: FromIterator<S>,
40 {
41 // Note: We don't check the lower bound here like we do in the character iterator because it's
42 // possible for the iterator to be full of empty strings! In which case checking the lower bound
43 // could cause us to heap allocate when there's no need.
44
45 // Continuously pull strings from the iterator
46 let mut curr_len = 0;
47 let mut inline_buf = InlineBuffer::new_const("");
48 while let Some(s) = iter.next() {
49 let str_slice = s.as_ref();
50 let bytes_len = str_slice.len();
51
52 // this new string is too large to fit into our inline buffer, so heap allocate the rest
53 if bytes_len + curr_len > MAX_SIZE {
54 let (min_remaining, _) = iter.size_hint();
55 let mut string = String::with_capacity(bytes_len + curr_len + min_remaining);
56
57 // push existing strings onto the heap
58 // SAFETY: `inline_buf` has been filled with `&str`s which are valid UTF-8
59 string.push_str(unsafe { core::str::from_utf8_unchecked(&inline_buf.0[..curr_len]) });
60 // push current string onto the heap
61 string.push_str(str_slice);
62 // extend heap with remaining strings
63 string.extend(iter);
64
65 return Repr::from_string(string, true).unwrap_with_msg();
66 }
67
68 // write the current string into a slice of the unoccupied space
69 inline_buf.0[curr_len..][..bytes_len].copy_from_slice(str_slice.as_bytes());
70 curr_len += bytes_len;
71 }
72
73 // SAFETY: Everything we just pushed onto the buffer is a `str` which is valid UTF-8
74 unsafe { inline_buf.set_len(curr_len) }
75
76 Repr::from_inline(inline_buf)
77 }
78
79 impl<'a> FromIterator<&'a str> for Repr {
80 fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
81 from_as_ref_str_iterator(iter.into_iter())
82 }
83 }
84
85 impl FromIterator<Box<str>> for Repr {
86 fn from_iter<T: IntoIterator<Item = Box<str>>>(iter: T) -> Self {
87 from_as_ref_str_iterator(iter.into_iter())
88 }
89 }
90
91 impl FromIterator<String> for Repr {
92 fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
93 from_as_ref_str_iterator(iter.into_iter())
94 }
95 }
96
97 impl FromIterator<CompactString> for Repr {
98 fn from_iter<T: IntoIterator<Item = CompactString>>(iter: T) -> Self {
99 from_as_ref_str_iterator(iter.into_iter())
100 }
101 }
102
103 impl<'a> FromIterator<Cow<'a, str>> for Repr {
104 fn from_iter<T: IntoIterator<Item = Cow<'a, str>>>(iter: T) -> Self {
105 from_as_ref_str_iterator(iter.into_iter())
106 }
107 }
108
109 #[cfg(test)]
110 mod tests {
111 use alloc::string::String;
112
113 use super::Repr;
114
115 #[test]
116 fn short_char_iter() {
117 let chars = ['a', 'b', 'c'];
118 let repr: Repr = chars.iter().collect();
119
120 assert_eq!(repr.as_str(), "abc");
121 assert!(!repr.is_heap_allocated());
122 }
123
124 #[test]
125 fn short_char_ref_iter() {
126 let chars = ['a', 'b', 'c'];
127 let repr: Repr = chars.iter().collect();
128
129 assert_eq!(repr.as_str(), "abc");
130 assert!(!repr.is_heap_allocated());
131 }
132
133 #[test]
134 #[cfg_attr(target_pointer_width = "32", ignore)]
135 fn packed_char_iter() {
136 let chars = [
137 '\u{92f01}',
138 '\u{81515}',
139 '\u{81515}',
140 '\u{81515}',
141 '\u{81515}',
142 '\u{41515}',
143 ];
144
145 let repr: Repr = chars.iter().collect();
146 let s: String = chars.iter().collect();
147
148 assert_eq!(repr.as_str(), s.as_str());
149 assert!(!repr.is_heap_allocated());
150 }
151
152 #[test]
153 fn long_char_iter() {
154 let long = "This is supposed to be a really long string";
155 let repr: Repr = long.chars().collect();
156
157 assert_eq!(repr.as_str(), "This is supposed to be a really long string");
158 assert!(repr.is_heap_allocated());
159 }
160
161 #[test]
162 fn short_string_iter() {
163 let strings = vec!["hello", "world"];
164 let repr: Repr = strings.into_iter().collect();
165
166 assert_eq!(repr.as_str(), "helloworld");
167 assert!(!repr.is_heap_allocated());
168 }
169
170 #[test]
171 fn long_short_string_iter() {
172 let strings = vec![
173 "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
174 "17", "18", "19", "20",
175 ];
176 let repr: Repr = strings.into_iter().collect();
177
178 assert_eq!(repr.as_str(), "1234567891011121314151617181920");
179 assert!(repr.is_heap_allocated());
180 }
181 }