Skip to main content

streams_rs/
io_stream.rs

1use std::io::{BufRead,Read};
2use crate::*;
3use std::borrow::Cow;
4use std::io::ErrorKind;
5pub struct LineReadStream<'a,T: BufRead> {
6    pub value: &'a mut T,
7    pub cache: Vec<Option<String>>,
8}
9impl<'a,T: BufRead> LineReadStream<'a,T> {
10    pub fn new(item: &'a mut T) -> Self {
11        Self {
12            value: item,
13            cache: vec![]
14        }
15    }
16}
17
18impl<'b,'a: 'b,T: BufRead> Stream<'a> for LineReadStream<'a,T> {
19    type Item = Option<String>;
20
21    fn token(&mut self,x: usize) -> StreamResult<Option<String>> {
22        if self.cache.get(x).is_some() {
23            return match &self.cache[x] {
24                Some(x) => StreamResult::Ok(Some(x.clone())),
25                _ => StreamResult::Ok(None)
26            }
27        }
28        let mut n = self.cache.len();
29        let mut c = (0..x + 1).map(|_| None).collect::<Vec<_>>();
30        while n <= x {
31            let mut buf = String::new();
32            let p = self.value.read_line(&mut buf);
33            match p {
34                Ok(0) => {
35                    c[n] = None;
36                }
37                Ok(_) => {
38                    c[n] = Some(buf);
39                    n += 1;
40                }
41                Err(e) => return StreamResult::Err(StreamError::Str(e.to_string())),
42            }
43           
44        }
45        self.cache = c;
46        StreamResult::Ok(self.cache[x].clone())
47    }
48
49    fn junk(&mut self,mut x: usize) {
50        let c = self.cache.len();
51        
52        if c >= x {
53            self.cache.truncate(c - x);
54        } else {
55            self.cache = vec![];
56            x = x - c;
57            while x > 0 {
58                
59                let _ = self.value.read_line(&mut String::new());
60                x = x - 1;
61            }
62        }
63    }
64
65    fn pos(&self) -> usize {
66        0
67    }
68    
69}