1 mod parser;
2 
3 use std::io::Read;
4 
5 use winnow::error::ErrMode;
6 use winnow::error::InputError;
7 use winnow::error::Needed;
8 use winnow::prelude::*;
9 use winnow::stream::Offset;
10 
main() -> Result<(), lexopt::Error>11 fn main() -> Result<(), lexopt::Error> {
12     let args = Args::parse()?;
13     let input = args.input.ok_or_else(|| lexopt::Error::MissingValue {
14         option: Some("<PATH>".to_owned()),
15     })?;
16 
17     let mut file = std::fs::File::open(&input).map_err(to_lexopt)?;
18 
19     // Intentionally starting with a small buffer to make it easier to show `Incomplete` handling
20     let buffer_size = 10;
21     let min_buffer_growth = 100;
22     let buffer_growth_factor = 2;
23     let mut buffer = circular::Buffer::with_capacity(buffer_size);
24     loop {
25         let read = file.read(buffer.space()).map_err(to_lexopt)?;
26         eprintln!("read {}", read);
27         if read == 0 {
28             // Should be EOF since we always make sure there is `available_space`
29             assert_ne!(buffer.available_space(), 0);
30             assert_eq!(
31                 buffer.available_data(),
32                 0,
33                 "leftover data: {}",
34                 String::from_utf8_lossy(buffer.data())
35             );
36             break;
37         }
38         buffer.fill(read);
39 
40         loop {
41             let input = parser::Stream::new(std::str::from_utf8(buffer.data()).map_err(to_lexopt)?);
42             match parser::ndjson::<InputError<parser::Stream>>.parse_peek(input) {
43                 Ok((remainder, value)) => {
44                     println!("{:?}", value);
45                     println!();
46                     // Tell the buffer how much we read
47                     let consumed = remainder.offset_from(&input);
48                     buffer.consume(consumed);
49                 }
50                 Err(ErrMode::Backtrack(e)) | Err(ErrMode::Cut(e)) => {
51                     return Err(fmt_lexopt(e.to_string()));
52                 }
53                 Err(ErrMode::Incomplete(Needed::Size(size))) => {
54                     // Without the format telling us how much space is required, we really should
55                     // treat this the same as `Unknown` but are doing this to demonstrate how to
56                     // handle `Size`.
57                     //
58                     // Even when the format has a header to tell us `Size`, we could hit incidental
59                     // `Size(1)`s, so make sure we buffer more space than that to avoid reading
60                     // one byte at a time
61                     let head_room = size.get().max(min_buffer_growth);
62                     let new_capacity = buffer.available_data() + head_room;
63                     eprintln!("growing buffer to {}", new_capacity);
64                     buffer.grow(new_capacity);
65                     if buffer.available_space() < head_room {
66                         eprintln!("buffer shift");
67                         buffer.shift();
68                     }
69                     break;
70                 }
71                 Err(ErrMode::Incomplete(Needed::Unknown)) => {
72                     let new_capacity = buffer_growth_factor * buffer.capacity();
73                     eprintln!("growing buffer to {}", new_capacity);
74                     buffer.grow(new_capacity);
75                     break;
76                 }
77             }
78         }
79     }
80 
81     Ok(())
82 }
83 
84 #[derive(Default)]
85 struct Args {
86     input: Option<std::path::PathBuf>,
87 }
88 
89 impl Args {
parse() -> Result<Self, lexopt::Error>90     fn parse() -> Result<Self, lexopt::Error> {
91         use lexopt::prelude::*;
92 
93         let mut res = Args::default();
94 
95         let mut args = lexopt::Parser::from_env();
96         while let Some(arg) = args.next()? {
97             match arg {
98                 Value(input) => {
99                     res.input = Some(input.into());
100                 }
101                 _ => return Err(arg.unexpected()),
102             }
103         }
104         Ok(res)
105     }
106 }
107 
to_lexopt(e: impl std::error::Error + Send + Sync + 'static) -> lexopt::Error108 fn to_lexopt(e: impl std::error::Error + Send + Sync + 'static) -> lexopt::Error {
109     lexopt::Error::Custom(Box::new(e))
110 }
111 
fmt_lexopt(e: String) -> lexopt::Error112 fn fmt_lexopt(e: String) -> lexopt::Error {
113     lexopt::Error::Custom(e.into())
114 }
115