1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use crate::json::{
4 json_minifier::JsonMinifier,
5 read::byte_to_char::{ByteToChar, CharsError},
6};
7use std::{
8 fmt,
9 io::{Error, ErrorKind, Read},
10 vec::IntoIter,
11};
12
13pub struct JsonRead<P, R> {
14 minifier: JsonMinifier,
15 read: Option<R>,
16 iter: Option<ByteToChar<R>>,
17 predicate: P,
18 initialized: bool,
19 item_iter: Option<IntoIter<u8>>,
20 item1: Option<char>,
21}
22
23impl<P, R: Read> JsonRead<P, R> {
24 #[inline]
25 pub fn new(read: R, predicate: P) -> Self {
26 JsonRead {
27 minifier: JsonMinifier::default(),
28 read: Some(read),
29 iter: None,
30 predicate,
31 initialized: false,
32 item_iter: None,
33 item1: None,
34 }
35 }
36
37 fn get_next(&mut self) -> Result<Option<char>, CharsError> {
38 match self.iter.as_mut().unwrap().next() {
39 None => Ok(None),
40 Some(item) => match item {
41 Ok(item) => Ok(Some(item)),
42 Err(err) => Err(err),
43 },
44 }
45 }
46
47 fn add_char_to_buffer(&mut self, buf: &mut [u8], buf_pos: &mut usize) {
48 if let Some(ref mut iter) = self.item_iter {
49 while *buf_pos < buf.len() {
50 if let Some(byte) = iter.next() {
51 buf[*buf_pos] = byte;
52 *buf_pos += 1;
53 } else {
54 break;
55 }
56 }
57 }
58 }
59}
60
61impl<P, R: Read + fmt::Debug> fmt::Debug for JsonRead<P, R> {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f&mut DebugStruct<'_, '_>.debug_struct("Filter")
64 .field("iter", &self.iter)
65 .field(name:"initialized", &self.initialized)
66 .finish()
67 }
68}
69
70impl<P, R> Read for JsonRead<P, R>
71where
72 R: Read,
73 P: FnMut(&mut JsonMinifier, &char, Option<&char>) -> bool,
74{
75 fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
76 let mut buf_pos: usize = 0;
77
78 if buf.is_empty() {
79 return Ok(0);
80 }
81
82 if !self.initialized {
83 self.iter = Some(ByteToChar::new(self.read.take().unwrap(), buf.len())?);
84 self.item1 = self.get_next()?;
85 self.initialized = true;
86 }
87
88 while let Some(item) = self.item1.take() {
89 self.item1 = self.get_next()?;
90 if (self.predicate)(&mut self.minifier, &item, self.item1.as_ref()) {
91 self.item_iter = Some(item.to_string().into_bytes().into_iter());
92 self.add_char_to_buffer(buf, &mut buf_pos);
93 }
94 if buf_pos >= buf.len() {
95 break;
96 }
97 }
98 Ok(buf_pos)
99 }
100}
101
102impl From<CharsError> for Error {
103 fn from(_: CharsError) -> Self {
104 Error::from(ErrorKind::InvalidData)
105 }
106}
107