1 | use std::ops::Index; |
2 | use alloc::vec::Vec; |
3 | |
4 | #[derive(Debug, Clone)] |
5 | pub struct LazyBuffer<I: Iterator> { |
6 | pub it: I, |
7 | done: bool, |
8 | buffer: Vec<I::Item>, |
9 | } |
10 | |
11 | impl<I> LazyBuffer<I> |
12 | where |
13 | I: Iterator, |
14 | { |
15 | pub fn new(it: I) -> LazyBuffer<I> { |
16 | LazyBuffer { |
17 | it, |
18 | done: false, |
19 | buffer: Vec::new(), |
20 | } |
21 | } |
22 | |
23 | pub fn len(&self) -> usize { |
24 | self.buffer.len() |
25 | } |
26 | |
27 | pub fn get_next(&mut self) -> bool { |
28 | if self.done { |
29 | return false; |
30 | } |
31 | if let Some(x) = self.it.next() { |
32 | self.buffer.push(x); |
33 | true |
34 | } else { |
35 | self.done = true; |
36 | false |
37 | } |
38 | } |
39 | |
40 | pub fn prefill(&mut self, len: usize) { |
41 | let buffer_len = self.buffer.len(); |
42 | |
43 | if !self.done && len > buffer_len { |
44 | let delta = len - buffer_len; |
45 | |
46 | self.buffer.extend(self.it.by_ref().take(delta)); |
47 | self.done = self.buffer.len() < len; |
48 | } |
49 | } |
50 | } |
51 | |
52 | impl<I, J> Index<J> for LazyBuffer<I> |
53 | where |
54 | I: Iterator, |
55 | I::Item: Sized, |
56 | Vec<I::Item>: Index<J> |
57 | { |
58 | type Output = <Vec<I::Item> as Index<J>>::Output; |
59 | |
60 | fn index(&self, index: J) -> &Self::Output { |
61 | self.buffer.index(index) |
62 | } |
63 | } |
64 | |