1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//! Readers for `&str`s and `String`s instead of `u8`s.
//!
//! See [`RealStrRead`] and [`StringRead`] as the traits, and [`StrReader`] and [`StringReader`] as
//! the structs.
use std::collections::VecDeque;

/// The base trait that both `RealStrRead` and `StringRead` need to implement.
pub trait StrRead {
    /// Get a reference to the next `&str`.
    ///
    /// Returns `None` if it's empty.
    fn peek_str<'a>(&'a self) -> Option<&'a str>;
    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str>;

    // fn map_str(&mut self, mut f: impl FnMut(&mut str)) {
    //     if let Some(s) = self.peek_mut_str() {
    //         f(s)
    //     }
    // }

    // fn map_str(&mut self, f: impl FnMut(&mut str));

    /// Check if there is nothing to pop.
    fn is_empty(&self) -> bool {
        self.peek_str().is_none()
    }
}

/// Represent anything that pops out `&str`.
pub trait RealStrRead: StrRead {
    /// Remove the next `&str` and return it.
    ///
    /// Returns `None` if it's empty.
    fn pop_str<'a>(&'a mut self) -> Option<&'a str>;
}

/// Represent anything that pops out `String`.
pub trait StringRead: StrRead {
    /// Remove the next `String` and return it.
    fn pop_string(&mut self) -> Option<String>;
    /// Get a mutable reference to the next `String`.
    fn peek_mut_string(&mut self) -> Option<&mut String>;

    /// Change the next `String` that will be poped.
    fn map_string(&mut self, f: impl FnMut(&mut String)) {
        self.peek_mut_string().map(f);
    }
}

/// Write/insert operations with `&str`-type readers.
pub trait StrWrite<'a> {
    /// Insert a `&str` into the reader.
    ///
    /// The newly inserted `&str` will be the *last* item in the list.
    ///
    /// # Examples
    /// ```rust
    /// let sread = StrReader::default();
    /// sread.push_str("hai");
    /// sread.push_str("bai");
    /// assert_eq!(sread.pop_str(), Some("hai"));
    /// assert_eq!(sread.pop_str(), Some("bai"));
    /// assert_eq!(sread.pop_str(), None);
    /// ```
    fn push_str(&'a mut self, s: &'a str);

    /// Insert a `&str` into the reader.
    ///
    /// The newly inserted `&str` will be the *next* item to be returned.
    ///
    /// # Examples
    /// ```rust
    /// let sread = StrReader::default();
    /// sread.shift_str("hai");
    /// sread.shift_str("bai");
    /// assert_eq!(sread.pop_str(), Some("bai"));
    /// assert_eq!(sread.pop_str(), Some("hai"));
    /// assert_eq!(sread.pop_str(), None);
    /// ```
    fn shift_str(&'a mut self, s: &'a str);
}

/// Write/insert operations with `String`-type readers.
pub trait StringWrite {
    /// Insert a `String` into the reader.
    ///
    /// The newly inserted `String` will be the *last* item in the list.
    ///
    /// # Examples
    /// ```rust
    /// let sread = StringReader::default();
    /// sread.push_string("hai".to_string());
    /// sread.push_string("bai".to_string());
    /// assert_eq!(sread.pop_string(), Some("hai".to_string()));
    /// assert_eq!(sread.pop_string(), Some("bai".to_string()));
    /// assert_eq!(sread.pop_string(), None);
    /// ```
    fn push_string(&mut self, s: String);
    /// Insert a `String` into the reader.
    ///
    /// The newly inserted `String` will be the *last* item in the list.
    ///
    /// # Examples
    /// ```rust
    /// let sread = StringReader::default();
    /// sread.shift_string("hai".to_string());
    /// sread.shift_string"bai".to_string());
    /// assert_eq!(sread.pop_string(), Some("bai".to_string()));
    /// assert_eq!(sread.pop_string(), Some("hai".to_string()));
    /// assert_eq!(sread.pop_string(), None);
    /// ```
    fn shift_string(&mut self, s: String);
}

impl StrRead for String {
    fn peek_str<'a>(&'a self) -> Option<&'a str> {
        Some(self)
    }

    // fn map_str(&mut self, mut f: impl FnMut(&mut str)) {
    //     f(self)
    // }

    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
    //     Some(self)
    // }
}
impl StringRead for String {
    fn pop_string(&mut self) -> Option<String> {
        Some(std::mem::take(self))
    }

    fn map_string(&mut self, mut f: impl FnMut(&mut String)) {
        f(self);
    }

    fn peek_mut_string(&mut self) -> Option<&mut String> {
        Some(self)
    }
}

// NOTE: #[derive(Default)] is not possible, it requires R to impl Default

/// An equivalent of `std::io::BufReader` but for `String` instead of `char`.
#[derive(Clone, Debug)]
pub struct StringReader<R: StringRead = String> {
    pub queue: VecDeque<String>,
    pub reader: Option<R>,
}

impl<R: StringRead> Default for StringReader<R> {
    fn default() -> Self {
        Self {
            queue: Default::default(),
            reader: None,
        }
    }
}

impl<R: StringRead> From<R> for StringReader<R> {
    fn from(value: R) -> Self {
        Self {
            queue: Default::default(),
            reader: Some(value),
        }
    }
}

impl<R: StringRead> From<VecDeque<String>> for StringReader<R> {
    fn from(value: VecDeque<String>) -> Self {
        Self {
            queue: value,
            reader: None,
        }
    }
}

impl<R: StringRead> StringReader<R> {
    /// Equivalent to `default()`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl<R: StringRead> StrRead for StringReader<R> {
    fn peek_str<'a>(&'a self) -> Option<&'a str> {
        (self.queue.front().map(|s| s.as_str()))
            .or_else(|| self.reader.as_ref().map(|r| r.peek_str())?)
    }

    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
    //     (self.stack.last_mut().map(|s| s.as_mut_str()))
    //         .or_else(|| self.reader.as_mut().map(|r| r.peek_mut_str())?)
    // }

    fn is_empty(&self) -> bool {
        self.queue.is_empty() && self.reader.as_ref().map_or(true, |r| r.is_empty())
    }
}

impl<R: StringRead> StringRead for StringReader<R> {
    fn pop_string(&mut self) -> Option<String> {
        (self.queue.pop_front()).or_else(|| self.reader.as_mut().map(|r| r.pop_string())?)
    }

    fn peek_mut_string(&mut self) -> Option<&mut String> {
        (self.queue.front_mut()).or_else(|| self.reader.as_mut().map(|r| r.peek_mut_string())?)
    }
}

impl<R: StringRead> std::io::Read for StringReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let mut l = buf.len();
        let mut pos = 0;
        while let Some(s) = self.peek_mut_string() {
            let slen = s.len();
            if slen > l {
                buf[pos..].copy_from_slice(s[..l].as_bytes());
                *s = s[l..].to_string();
                return Ok(buf.len());
            }
            // slen <= l
            buf[pos..pos + slen].copy_from_slice(self.pop_string().unwrap().as_bytes());
            pos += slen;
            l -= slen;
        }
        Ok(pos)
    }
}

impl<R: StringRead> std::io::BufRead for StringReader<R> {
    fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
        if let Some(s) = self.peek_str() {
            Ok(s.as_bytes())
        } else if let Some(s) = self.reader.as_ref().and_then(|r| r.peek_str()) {
            Ok(s.as_bytes())
        } else {
            Ok(&[])
        }
    }

    fn consume(&mut self, amt: usize) {
        use std::io::Read;
        let mut buf: Vec<u8> = Vec::new();
        (0..amt).for_each(|_| buf.push(0));
        self.read(&mut buf).unwrap();
    }
}

impl StrRead for str {
    fn peek_str<'a>(&'a self) -> Option<&'a str> {
        Some(self)
    }

    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
    //     Some(self)
    // }
}
impl RealStrRead for str {
    fn pop_str<'a>(&'a mut self) -> Option<&'a str> {
        Some(self)
    }
}
impl<R: StrRead + ?Sized> StrRead for Box<R> {
    fn peek_str<'a>(&'a self) -> Option<&'a str> {
        (**self).peek_str()
    }

    // fn peek_mut_str<'a>(&'a mut self) -> Option<&'a mut str> {
    //     (**self).peek_mut_str()
    // }
}
impl<R: RealStrRead + ?Sized> RealStrRead for Box<R> {
    fn pop_str<'a>(&'a mut self) -> Option<&'a str> {
        (**self).pop_str()
    }
}

#[derive(Clone, Debug)]
pub struct StrReader<'a, R: RealStrRead = Box<str>> {
    pub queue: VecDeque<&'a str>,
    pub reader: Option<R>,
}

impl<'a, R: RealStrRead> Default for StrReader<'a, R> {
    fn default() -> Self {
        Self {
            queue: Default::default(),
            reader: None,
        }
    }
}

impl<'a, R: RealStrRead> From<R> for StrReader<'a, R> {
    fn from(value: R) -> Self {
        Self {
            queue: Default::default(),
            reader: Some(value),
        }
    }
}

impl<'a, R: RealStrRead> From<VecDeque<&'a str>> for StrReader<'a, R> {
    fn from(value: VecDeque<&'a str>) -> Self {
        Self {
            queue: value,
            reader: None,
        }
    }
}

impl<'a, R: RealStrRead> StrReader<'a, R> {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl<'a, R: RealStrRead> StrRead for StrReader<'a, R> {
    fn peek_str<'b>(&'b self) -> Option<&'b str> {
        (self.queue.front().copied()).or_else(|| self.reader.as_ref().and_then(|r| r.peek_str()))
    }

    // fn peek_mut_str<'b>(&'b mut self) -> Option<&'b mut str> {
    //     (self.stack.last_mut().map(|s| s.as_mut()))
    //         .or_else(|| self.reader.as_mut().map(|r| r.peek_mut_str())?)
    // }

    fn is_empty(&self) -> bool {
        self.queue.is_empty() && self.reader.as_ref().map_or(true, |r| r.is_empty())
    }
}

impl<'a, R: RealStrRead> RealStrRead for StrReader<'a, R> {
    fn pop_str<'b>(&'b mut self) -> Option<&'b str> {
        self.queue
            .pop_front()
            .or_else(|| self.reader.as_mut().and_then(|r| r.pop_str()))
    }
}

impl<'r, R: RealStrRead> StrWrite<'r> for StrReader<'r, R> {
    fn push_str(&'r mut self, s: &'r str) {
        self.queue.push_back(s);
    }

    fn shift_str(&'r mut self, s: &'r str) {
        self.queue.push_front(s);
    }
}

// impl<'r, R: RealStrRead> std::io::Read for StrReader<'r, R> {
//     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
//         let mut l = buf.len();
//         let mut pos = 0;
//         while let Some(s) = self.pop_str() {
//             let slen = s.len();
//             if slen > l {
//                 buf[pos..].copy_from_slice(s[..l].as_bytes());
//                 self.shift_str(&s[l..]);
//                 return Ok(buf.len());
//             }
//             // slen <= l
//             buf[pos..pos + slen].copy_from_slice(s.as_bytes());
//             pos += slen;
//             l -= slen;
//         }
//         Ok(pos)
//     }
// }