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