1 | // Take a look at the license at the top of the repository in the LICENSE file. |
2 | |
3 | use super::internal_buffer::Buffer; |
4 | use std::{ |
5 | fmt, |
6 | io::{Error, Read}, |
7 | }; |
8 | |
9 | pub struct InternalReader<R> { |
10 | read: R, |
11 | buffer_size: usize, |
12 | buffer: Buffer, |
13 | } |
14 | |
15 | impl<R: Read> InternalReader<R> { |
16 | pub fn new(mut read: R, buffer_size: usize) -> Result<Self, Error> { |
17 | let mut buffer: Buffer = Buffer::new(buffer_size); |
18 | InternalReader::read_data(&mut read, &mut buffer)?; |
19 | Ok(InternalReader { |
20 | read, |
21 | buffer_size, |
22 | buffer, |
23 | }) |
24 | } |
25 | |
26 | fn read_data(read: &mut R, buffer: &mut Buffer) -> Result<(), Error> { |
27 | let size: usize = read.read(buf:buffer.as_mut())?; |
28 | buffer.update_metadata(size); |
29 | Ok(()) |
30 | } |
31 | } |
32 | |
33 | impl<R: Read + fmt::Debug> fmt::Debug for InternalReader<R> { |
34 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
35 | f&mut DebugStruct<'_, '_>.debug_struct("JsonReader" ) |
36 | .field("read" , &self.read) |
37 | .field("buffer_size" , &self.buffer_size) |
38 | .field(name:"buffer" , &self.buffer) |
39 | .finish() |
40 | } |
41 | } |
42 | |
43 | impl<R: Read> Iterator for InternalReader<R> { |
44 | type Item = Result<u8, Error>; |
45 | |
46 | #[inline ] |
47 | fn next(&mut self) -> Option<Result<u8, Error>> { |
48 | if self.buffer_size == 0 { |
49 | return None; |
50 | } |
51 | loop { |
52 | if let Some(item: u8) = self.buffer.next() { |
53 | return Some(Ok(item)); |
54 | } else if self.buffer.cont() { |
55 | if let Err(err: Error) = InternalReader::read_data(&mut self.read, &mut self.buffer) { |
56 | return Some(Err(err)); |
57 | }; |
58 | } else { |
59 | return None; |
60 | } |
61 | } |
62 | } |
63 | } |
64 | |