string_reader/
lib.rs

1//! Readers for `&str`s and `String`s instead of `u8`s.
2//!
3//! See [`RealStrRead`] and [`StringRead`] as the traits, and [`StrReader`] and [`StringReader`] as
4//! the structs.
5use std::collections::VecDeque;
6
7/// The base trait that both `RealStrRead` and `StringRead` need to implement.
8pub trait StrRead {
9    /// Get a reference to the next `&str`.
10    ///
11    /// Returns `None` if it's empty.
12    fn peek_str(&self) -> Option<&str>;
13    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str>;
14
15    // fn map_str(&mut self, mut f: impl FnMut(&mut str)) {
16    //     if let Some(s) = self.peek_mut_str() {
17    //         f(s)
18    //     }
19    // }
20
21    // fn map_str(&mut self, f: impl FnMut(&mut str));
22
23    /// Check if there is nothing to pop.
24    fn is_empty(&self) -> bool {
25        self.peek_str().is_none()
26    }
27}
28
29/// Represent anything that pops out `&str`.
30pub trait RealStrRead: StrRead {
31    /// Remove the next `&str` and return it.
32    ///
33    /// Returns `None` if it's empty.
34    fn pop_str(&mut self) -> Option<&str>;
35}
36
37/// Represent anything that pops out `String`.
38pub trait StringRead: StrRead {
39    /// Remove the next `String` and return it.
40    fn pop_string(&mut self) -> Option<String>;
41    /// Get a mutable reference to the next `String`.
42    fn peek_mut_string(&mut self) -> Option<&mut String>;
43
44    /// Change the next `String` that will be poped.
45    fn map_string(&mut self, f: impl FnMut(&mut String)) {
46        self.peek_mut_string().map(f);
47    }
48}
49
50/// Write/insert operations with `&str`-type readers.
51pub trait StrWrite<'a> {
52    /// Insert a `&str` into the reader.
53    ///
54    /// The newly inserted `&str` will be the *last* item in the list.
55    ///
56    /// # Examples
57    /// ```rust
58    /// let sread = StrReader::default();
59    /// sread.push_str("hai");
60    /// sread.push_str("bai");
61    /// assert_eq!(sread.pop_str(), Some("hai"));
62    /// assert_eq!(sread.pop_str(), Some("bai"));
63    /// assert_eq!(sread.pop_str(), None);
64    /// ```
65    fn push_str(&'a mut self, s: &'a str);
66
67    /// Insert a `&str` into the reader.
68    ///
69    /// The newly inserted `&str` will be the *next* item to be returned.
70    ///
71    /// # Examples
72    /// ```rust
73    /// let sread = StrReader::default();
74    /// sread.shift_str("hai");
75    /// sread.shift_str("bai");
76    /// assert_eq!(sread.pop_str(), Some("bai"));
77    /// assert_eq!(sread.pop_str(), Some("hai"));
78    /// assert_eq!(sread.pop_str(), None);
79    /// ```
80    fn shift_str(&'a mut self, s: &'a str);
81}
82
83/// Write/insert operations with `String`-type readers.
84pub trait StringWrite {
85    /// Insert a `String` into the reader.
86    ///
87    /// The newly inserted `String` will be the *last* item in the list.
88    ///
89    /// # Examples
90    /// ```rust
91    /// let sread = StringReader::default();
92    /// sread.push_string("hai".to_string());
93    /// sread.push_string("bai".to_string());
94    /// assert_eq!(sread.pop_string(), Some("hai".to_string()));
95    /// assert_eq!(sread.pop_string(), Some("bai".to_string()));
96    /// assert_eq!(sread.pop_string(), None);
97    /// ```
98    fn push_string(&mut self, s: String);
99    /// Insert a `String` into the reader.
100    ///
101    /// The newly inserted `String` will be the *last* item in the list.
102    ///
103    /// # Examples
104    /// ```rust
105    /// let sread = StringReader::default();
106    /// sread.shift_string("hai".to_string());
107    /// sread.shift_string"bai".to_string());
108    /// assert_eq!(sread.pop_string(), Some("bai".to_string()));
109    /// assert_eq!(sread.pop_string(), Some("hai".to_string()));
110    /// assert_eq!(sread.pop_string(), None);
111    /// ```
112    fn shift_string(&mut self, s: String);
113}
114
115impl StrRead for String {
116    fn peek_str(&self) -> Option<&str> {
117        Some(self)
118    }
119
120    // fn map_str(&mut self, mut f: impl FnMut(&mut str)) {
121    //     f(self)
122    // }
123
124    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
125    //     Some(self)
126    // }
127}
128impl StringRead for String {
129    fn pop_string(&mut self) -> Option<String> {
130        Some(std::mem::take(self))
131    }
132
133    fn map_string(&mut self, mut f: impl FnMut(&mut String)) {
134        f(self);
135    }
136
137    fn peek_mut_string(&mut self) -> Option<&mut String> {
138        Some(self)
139    }
140}
141
142// NOTE: #[derive(Default)] is not possible, it requires R to impl Default
143
144/// An equivalent of `std::io::BufReader` but for `String` instead of `char`.
145#[derive(Clone, Debug)]
146pub struct StringReader<R: StringRead = String> {
147    pub queue: VecDeque<String>,
148    pub reader: Option<R>,
149}
150
151impl<R: StringRead> Default for StringReader<R> {
152    fn default() -> Self {
153        Self {
154            queue: Default::default(),
155            reader: None,
156        }
157    }
158}
159
160impl<R: StringRead> From<R> for StringReader<R> {
161    fn from(value: R) -> Self {
162        Self {
163            queue: Default::default(),
164            reader: Some(value),
165        }
166    }
167}
168
169impl<R: StringRead> From<VecDeque<String>> for StringReader<R> {
170    fn from(value: VecDeque<String>) -> Self {
171        Self {
172            queue: value,
173            reader: None,
174        }
175    }
176}
177
178impl<R: StringRead> StringReader<R> {
179    /// Equivalent to `default()`.
180    #[must_use]
181    pub fn new() -> Self {
182        Self::default()
183    }
184}
185
186impl<R: StringRead> StrRead for StringReader<R> {
187    fn peek_str(&self) -> Option<&str> {
188        (self.queue.front().map(|s| s.as_str()))
189            .or_else(|| self.reader.as_ref().map(|r| r.peek_str())?)
190    }
191
192    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
193    //     (self.stack.last_mut().map(|s| s.as_mut_str()))
194    //         .or_else(|| self.reader.as_mut().map(|r| r.peek_mut_str())?)
195    // }
196
197    fn is_empty(&self) -> bool {
198        self.queue.is_empty() && self.reader.as_ref().map_or(true, |r| r.is_empty())
199    }
200}
201
202impl<R: StringRead> StringRead for StringReader<R> {
203    fn pop_string(&mut self) -> Option<String> {
204        (self.queue.pop_front()).or_else(|| self.reader.as_mut().map(|r| r.pop_string())?)
205    }
206
207    fn peek_mut_string(&mut self) -> Option<&mut String> {
208        (self.queue.front_mut()).or_else(|| self.reader.as_mut().map(|r| r.peek_mut_string())?)
209    }
210}
211
212impl<R: StringRead> std::io::Read for StringReader<R> {
213    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
214        let mut l = buf.len();
215        let mut pos = 0;
216        while let Some(s) = self.peek_mut_string() {
217            let slen = s.len();
218            if slen > l {
219                buf[pos..].copy_from_slice(s[..l].as_bytes());
220                *s = s[l..].to_string();
221                return Ok(buf.len());
222            }
223            // slen <= l
224            buf[pos..pos + slen].copy_from_slice(self.pop_string().unwrap().as_bytes());
225            pos += slen;
226            l -= slen;
227        }
228        Ok(pos)
229    }
230}
231
232impl<R: StringRead> std::io::BufRead for StringReader<R> {
233    fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
234        if let Some(s) = self.peek_str() {
235            Ok(s.as_bytes())
236        } else if let Some(s) = self.reader.as_ref().and_then(|r| r.peek_str()) {
237            Ok(s.as_bytes())
238        } else {
239            Ok(&[])
240        }
241    }
242
243    fn consume(&mut self, amt: usize) {
244        use std::io::Read;
245        let mut buf: Vec<u8> = Vec::new();
246        (0..amt).for_each(|_| buf.push(0));
247        self.read(&mut buf).unwrap();
248    }
249}
250
251impl StrRead for str {
252    fn peek_str(&self) -> Option<&str> {
253        Some(self)
254    }
255
256    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
257    //     Some(self)
258    // }
259}
260impl RealStrRead for str {
261    fn pop_str(&mut self) -> Option<&str> {
262        Some(self)
263    }
264}
265impl<R: StrRead + ?Sized> StrRead for Box<R> {
266    fn peek_str(&self) -> Option<&str> {
267        (**self).peek_str()
268    }
269
270    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
271    //     (**self).peek_mut_str()
272    // }
273}
274impl<R: RealStrRead + ?Sized> RealStrRead for Box<R> {
275    fn pop_str(&mut self) -> Option<&str> {
276        (**self).pop_str()
277    }
278}
279
280#[derive(Clone, Debug)]
281pub struct StrReader<'a, R: RealStrRead = Box<str>> {
282    pub queue: VecDeque<&'a str>,
283    pub reader: Option<R>,
284}
285
286impl<'a, R: RealStrRead> Default for StrReader<'a, R> {
287    fn default() -> Self {
288        Self {
289            queue: Default::default(),
290            reader: None,
291        }
292    }
293}
294
295impl<'a, R: RealStrRead> From<R> for StrReader<'a, R> {
296    fn from(value: R) -> Self {
297        Self {
298            queue: Default::default(),
299            reader: Some(value),
300        }
301    }
302}
303
304impl<'a, R: RealStrRead> From<VecDeque<&'a str>> for StrReader<'a, R> {
305    fn from(value: VecDeque<&'a str>) -> Self {
306        Self {
307            queue: value,
308            reader: None,
309        }
310    }
311}
312
313impl<'a, R: RealStrRead> StrReader<'a, R> {
314    #[must_use]
315    pub fn new() -> Self {
316        Self::default()
317    }
318}
319
320impl<'a, R: RealStrRead> StrRead for StrReader<'a, R> {
321    fn peek_str(&self) -> Option<&str> {
322        (self.queue.front().copied()).or_else(|| self.reader.as_ref().and_then(|r| r.peek_str()))
323    }
324
325    // fn peek_mut_str<'b>(&'b mut self) -> Option<&'b mut str> {
326    //     (self.stack.last_mut().map(|s| s.as_mut()))
327    //         .or_else(|| self.reader.as_mut().map(|r| r.peek_mut_str())?)
328    // }
329
330    fn is_empty(&self) -> bool {
331        self.queue.is_empty() && self.reader.as_ref().map_or(true, |r| r.is_empty())
332    }
333}
334
335impl<'a, R: RealStrRead> RealStrRead for StrReader<'a, R> {
336    fn pop_str(&mut self) -> Option<&str> {
337        self.queue
338            .pop_front()
339            .or_else(|| self.reader.as_mut().and_then(|r| r.pop_str()))
340    }
341}
342
343impl<'r, R: RealStrRead> StrWrite<'r> for StrReader<'r, R> {
344    fn push_str(&'r mut self, s: &'r str) {
345        self.queue.push_back(s);
346    }
347
348    fn shift_str(&'r mut self, s: &'r str) {
349        self.queue.push_front(s);
350    }
351}
352
353// impl<'r, R: RealStrRead> std::io::Read for StrReader<'r, R> {
354//     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
355//         let mut l = buf.len();
356//         let mut pos = 0;
357//         while let Some(s) = self.pop_str() {
358//             let slen = s.len();
359//             if slen > l {
360//                 buf[pos..].copy_from_slice(s[..l].as_bytes());
361//                 self.shift_str(&s[l..]);
362//                 return Ok(buf.len());
363//             }
364//             // slen <= l
365//             buf[pos..pos + slen].copy_from_slice(s.as_bytes());
366//             pos += slen;
367//             l -= slen;
368//         }
369//         Ok(pos)
370//     }
371// }
372
373impl<R: StringRead> StringWrite for StringReader<R> {
374    fn push_string(&mut self, s: String) {
375        self.queue.push_back(s);
376    }
377
378    fn shift_string(&mut self, s: String) {
379        self.queue.push_front(s);
380    }
381}