diff options
| author | nsfisis <nsfisis@gmail.com> | 2024-07-15 13:58:32 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2024-07-15 13:58:32 +0900 |
| commit | a245b635c9099448a00eea15cec5bc61dcf1d026 (patch) | |
| tree | 7bf7476fa386f3746f9ad9471f2fa00bb45fa41d | |
| parent | 8eae1719cd68929580ea2c8e795d238a1a03d81d (diff) | |
| download | reparojson-a245b635c9099448a00eea15cec5bc61dcf1d026.tar.gz reparojson-a245b635c9099448a00eea15cec5bc61dcf1d026.tar.zst reparojson-a245b635c9099448a00eea15cec5bc61dcf1d026.zip | |
initial implementation
| -rw-r--r-- | Cargo.lock | 175 | ||||
| -rw-r--r-- | Cargo.toml | 7 | ||||
| -rw-r--r-- | LICENSE | 9 | ||||
| -rw-r--r-- | docs/JSON.md | 29 | ||||
| -rw-r--r-- | src/lib.rs | 636 | ||||
| -rw-r--r-- | src/main.rs | 77 |
6 files changed, 923 insertions, 10 deletions
@@ -3,14 +3,181 @@ version = 3 [[package]] -name = "anyhow" -version = "1.0.86" +name = "anstream" +version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" + +[[package]] +name = "anstyle-parse" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" +dependencies = [ + "anstyle", + "windows-sys", +] + +[[package]] +name = "clap" +version = "4.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64acc1846d54c1fe936a78dc189c34e28d3f5afc348403f28ecf53660b9b8462" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fb8393d67ba2e7bfaf28a23458e4e2b543cc73a99595511eb207fdb8aede942" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" + +[[package]] +name = "colorchoice" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" [[package]] name = "reparojson" version = "0.1.0" dependencies = [ - "anyhow", + "clap", ] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" @@ -3,7 +3,6 @@ name = "reparojson" version = "0.1.0" edition = "2021" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -anyhow = "1.0.86" +[dependencies.clap] +version = "4.5.9" +features = ["cargo"] @@ -0,0 +1,9 @@ +MIT License + +Copyright 2024 nsfisis + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/docs/JSON.md b/docs/JSON.md index f5fab89..184fd05 100644 --- a/docs/JSON.md +++ b/docs/JSON.md @@ -103,3 +103,32 @@ ws '000D' ws '0009' ws ``` + +``` +object + { ws members_opt trailing_comma_opt } + +members_opt + <empty> + members + +trailing_comma_opt + <empty> + , ws + +members + (member ws trailing_comma_opt)+ + +member + string ws : ws value + +array + [ ws elements_opt trailing_comma_opt ] + +elements_opt + <empty> + elements + +elements + (value ws trailing_comma_opt)+ +``` diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5fca21c --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,636 @@ +use std::io::{Read, Write}; +use std::iter::Peekable; + +pub type RepairResult = Result<RepairOk, RepairErr>; + +pub enum RepairOk { + Valid, + Repaired, +} + +pub enum RepairErr { + Invalid(SyntaxError), + IoErr(std::io::Error), +} + +impl From<std::io::Error> for RepairErr { + fn from(value: std::io::Error) -> Self { + Self::IoErr(value) + } +} + +pub enum SyntaxError { + UnexpectedEof, + InvalidValue, +} + +impl SyntaxError { + fn to_result(self) -> ParserResult { + Err(RepairErr::Invalid(self)) + } +} + +impl std::fmt::Display for SyntaxError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::UnexpectedEof => write!(f, "unexpected end of file"), + Self::InvalidValue => write!(f, "invalid value"), + } + } +} + +pub fn repair(r: impl Read, mut w: impl Write) -> RepairResult { + let mut p = Parser::new(); + match p.walk_json(&mut r.bytes().peekable(), &mut w) { + Ok(_) => Ok(if p.repaired() { + RepairOk::Repaired + } else { + RepairOk::Valid + }), + Err(err) => Err(err), + } +} + +struct Parser { + repaired: bool, +} + +type ParserResult = Result<(), RepairErr>; + +impl Parser { + fn new() -> Self { + Self { repaired: false } + } + + fn repaired(&self) -> bool { + self.repaired + } + + fn walk_json<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + self.walk_element(input, w) + } + + fn walk_value<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let Some(c) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(c) = c else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + + match c { + b'n' => { + input.next(); // => n + match input.next() { + Some(Ok(b'u')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b'l')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b'l')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + w.write_all(b"null")?; + Ok(()) + } + b't' => { + input.next(); // => t + match input.next() { + Some(Ok(b'r')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b'u')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b'e')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + w.write_all(b"true")?; + Ok(()) + } + b'f' => { + input.next(); // => f + match input.next() { + Some(Ok(b'a')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b'l')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b's')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + match input.next() { + Some(Ok(b'e')) => (), + Some(Ok(_)) => return SyntaxError::InvalidValue.to_result(), + Some(Err(err)) => return Err(err.into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + w.write_all(b"false")?; + Ok(()) + } + b'{' => self.walk_object(input, w), + b'[' => self.walk_array(input, w), + b'"' => self.walk_string(input, w), + b'-' | b'0' | b'1' | b'2' | b'3' | b'4' | b'5' | b'6' | b'7' | b'8' | b'9' => { + self.walk_number(input, w) + } + _ => SyntaxError::InvalidValue.to_result(), + } + } + + fn walk_object<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + w.write_all(b"{")?; + input.next(); // => { + + self.walk_ws(input, w)?; + + // members_opt + let Some(first) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(first) = first else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *first == b'"' { + self.walk_members(input, w)?; + } + + // trailing_comma_opt + let Some(maybe_comma) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(maybe_comma) = maybe_comma else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *maybe_comma == b',' { + self.repaired = true; + input.next(); + self.walk_ws(input, w)?; + } + + let Some(last) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let last = last?; + if last != b'}' { + return SyntaxError::InvalidValue.to_result(); + } + w.write_all(b"}")?; + Ok(()) + } + + fn walk_members<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + loop { + self.walk_member(input, w)?; + + let mut ws = Vec::with_capacity(1024); + self.walk_ws(input, &mut ws)?; + + let Some(next) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(next) = next else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + + match *next { + b'}' => { + w.write_all(&mut ws)?; + return Ok(()); + } + b',' => { + w.write_all(&mut ws)?; + + input.next(); + + self.walk_ws(input, &mut ws)?; + + let Some(c) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(c) = c else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + match *c { + b'}' => { + self.repaired = true; + w.write_all(&mut ws)?; + return Ok(()); + } + _ => { + w.write_all(b",")?; + w.write_all(&mut ws)?; + } + } + } + _ => { + self.repaired = true; + w.write_all(b",")?; + w.write_all(&mut ws)?; + } + } + } + } + + fn walk_member<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + self.walk_string(input, w)?; + self.walk_ws(input, w)?; + let Some(colon) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let colon = colon?; + if colon != b':' { + return SyntaxError::InvalidValue.to_result(); + } + w.write_all(b":")?; + self.walk_element(input, w) + } + + fn walk_array<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + w.write_all(b"[")?; + input.next(); // => [ + + self.walk_ws(input, w)?; + + // elements_opt + let Some(first) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(first) = first else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *first != b',' && *first != b']' { + self.walk_elements(input, w)?; + } + + // trailing_comma_opt + let Some(maybe_comma) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(maybe_comma) = maybe_comma else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *maybe_comma == b',' { + self.repaired = true; + input.next(); + self.walk_ws(input, w)?; + } + + let Some(last) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let last = last?; + if last != b']' { + return SyntaxError::InvalidValue.to_result(); + } + w.write_all(b"]")?; + Ok(()) + } + + fn walk_elements<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + loop { + self.walk_value(input, w)?; + + let mut ws = Vec::with_capacity(1024); + self.walk_ws(input, &mut ws)?; + + let Some(next) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(next) = next else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + + match *next { + b']' => { + w.write_all(&mut ws)?; + return Ok(()); + } + b',' => { + w.write_all(&mut ws)?; + + input.next(); + + self.walk_ws(input, &mut ws)?; + + let Some(c) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(c) = c else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + match *c { + b']' => { + self.repaired = true; + w.write_all(&mut ws)?; + return Ok(()); + } + _ => { + w.write_all(b",")?; + w.write_all(&mut ws)?; + } + } + } + _ => { + self.repaired = true; + w.write_all(b",")?; + w.write_all(&mut ws)?; + } + } + } + } + + fn walk_element<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + self.walk_ws(input, w)?; + self.walk_value(input, w)?; + self.walk_ws(input, w) + } + + fn walk_string<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + w.write_all(b"\"")?; + input.next(); // => " + loop { + match input.next() { + Some(Ok(b'"')) => break, + Some(Ok(b'\\')) => { + self.walk_escape(input, w)?; + } + Some(Ok(c)) => { + w.write_all(&[c])?; + } + Some(Err(_)) => return Err(input.next().unwrap().unwrap_err().into()), + None => return SyntaxError::UnexpectedEof.to_result(), + } + } + w.write_all(b"\"")?; + Ok(()) + } + + fn walk_escape<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let Some(c) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let c = c?; + match c { + b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => { + w.write_all(&[b'\\', c])?; + } + b'u' => { + let Some(u1) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let u1 = u1?; + if !u1.is_ascii_hexdigit() { + return SyntaxError::InvalidValue.to_result(); + } + let Some(u2) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let u2 = u2?; + if !u2.is_ascii_hexdigit() { + return SyntaxError::InvalidValue.to_result(); + } + let Some(u3) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let u3 = u3?; + if !u3.is_ascii_hexdigit() { + return SyntaxError::InvalidValue.to_result(); + } + let Some(u4) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let u4 = u4?; + if !u4.is_ascii_hexdigit() { + return SyntaxError::InvalidValue.to_result(); + } + w.write_all(&[b'\\', u1, u2, u3, u4])?; + } + _ => return SyntaxError::InvalidValue.to_result(), + } + Ok(()) + } + + fn walk_number<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + self.walk_integer(input, w)?; + self.walk_fraction(input, w)?; + self.walk_exponent(input, w) + } + + fn walk_integer<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let Some(first) = input.next() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let first = first?; + match first { + b'-' => { + w.write_all(b"-")?; + return self.walk_integer(input, w); + } + b'0' => { + w.write_all(b"0")?; + return Ok(()); + } + b'1' | b'2' | b'3' | b'4' | b'5' | b'6' | b'7' | b'8' | b'9' => { + w.write_all(&[first])?; + loop { + match input.peek() { + Some(Ok(c @ b'0')) | Some(Ok(c @ b'1')) | Some(Ok(c @ b'2')) + | Some(Ok(c @ b'3')) | Some(Ok(c @ b'4')) | Some(Ok(c @ b'5')) + | Some(Ok(c @ b'6')) | Some(Ok(c @ b'7')) | Some(Ok(c @ b'8')) + | Some(Ok(c @ b'9')) => { + w.write_all(&[*c])?; + input.next(); + } + Some(Ok(_)) => break, + Some(Err(_)) => return Err(input.next().unwrap().unwrap_err().into()), + None => return Ok(()), + } + } + } + _ => return SyntaxError::InvalidValue.to_result(), + } + Ok(()) + } + + fn walk_digits<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let mut has_digit = false; + loop { + match input.peek() { + Some(Ok(c @ b'0')) | Some(Ok(c @ b'1')) | Some(Ok(c @ b'2')) + | Some(Ok(c @ b'3')) | Some(Ok(c @ b'4')) | Some(Ok(c @ b'5')) + | Some(Ok(c @ b'6')) | Some(Ok(c @ b'7')) | Some(Ok(c @ b'8')) + | Some(Ok(c @ b'9')) => { + w.write_all(&[*c])?; + input.next(); + has_digit = true; + } + Some(Ok(_)) => break, + Some(Err(_)) => return Err(input.next().unwrap().unwrap_err().into()), + None => break, + } + } + if has_digit { + Ok(()) + } else { + match input.peek() { + Some(_) => SyntaxError::InvalidValue.to_result(), + None => SyntaxError::UnexpectedEof.to_result(), + } + } + } + + fn walk_fraction<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let Some(first) = input.peek() else { + return Ok(()); + }; + let Ok(first) = first else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *first != b'.' { + return Ok(()); + } + w.write_all(b".")?; + input.next(); + self.walk_digits(input, w) + } + + fn walk_exponent<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let Some(first) = input.peek() else { + return Ok(()); + }; + let Ok(first) = first else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *first != b'e' && *first != b'E' { + return Ok(()); + } + w.write_all(&[*first])?; + input.next(); + self.walk_sign(input, w)?; + self.walk_digits(input, w) + } + + fn walk_sign<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + let Some(c) = input.peek() else { + return SyntaxError::UnexpectedEof.to_result(); + }; + let Ok(c) = c else { + return Err(input.next().unwrap().unwrap_err().into()); + }; + if *c == b'+' || *c == b'-' { + w.write_all(&[*c])?; + input.next(); + } + Ok(()) + } + + fn walk_ws<I: Iterator<Item = std::io::Result<u8>>, W: Write>( + &mut self, + input: &mut Peekable<I>, + w: &mut W, + ) -> ParserResult { + loop { + match input.peek() { + Some(Ok(c @ 0x09)) | Some(Ok(c @ 0x0A)) | Some(Ok(c @ 0x0D)) + | Some(Ok(c @ 0x20)) => { + w.write_all(&[*c])?; + input.next(); + } + Some(Ok(_)) => return Ok(()), + Some(Err(_)) => return Err(input.next().unwrap().unwrap_err().into()), + None => return Ok(()), + } + } + } +} diff --git a/src/main.rs b/src/main.rs index 0672e51..c113039 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,76 @@ -fn main() { - println!("Hello, World!"); +use reparojson::{self, RepairErr, RepairOk, RepairResult}; +use std::ffi::{OsStr, OsString}; +use std::fs::File; +use std::io::{stdin, stdout, BufReader, BufWriter, Write}; +use std::process::ExitCode; + +struct Config { + quiet: bool, + file_path: Option<OsString>, +} + +fn parse_args() -> std::io::Result<Config> { + use clap::{arg, command, value_parser}; + + let matches = command!() + .arg(arg!(-q --quiet "Successfully exit if the input JSON is repaired")) + .arg( + arg!([FILE] "The input JSON file (default: STDIN)") + .value_parser(value_parser!(OsString)), + ) + .get_matches(); + + let quiet = matches.get_flag("quiet"); + let file_path = matches.get_one("FILE").cloned(); + Ok(Config { quiet, file_path }) +} + +fn repair(input_file_path: Option<OsString>, mut w: impl Write) -> RepairResult { + match input_file_path.as_ref() { + None => { + let reader = stdin().lock(); + let reader = BufReader::new(reader); + reparojson::repair(reader, &mut w) + } + Some(file_path) => { + if file_path == OsStr::new("-") { + let reader = stdin().lock(); + let reader = BufReader::new(reader); + reparojson::repair(reader, &mut w) + } else { + let reader = File::open(file_path)?; + let reader = BufReader::new(reader); + reparojson::repair(reader, &mut w) + } + } + } +} + +fn main() -> std::io::Result<ExitCode> { + let config = parse_args()?; + + let writer = stdout().lock(); + let mut writer = BufWriter::new(writer); + + let exit_code = match repair(config.file_path, &mut writer) { + Ok(RepairOk::Valid) => ExitCode::SUCCESS, + Ok(RepairOk::Repaired) => { + if config.quiet { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } + } + Err(RepairErr::Invalid(err)) => { + eprintln!("{}", err); + ExitCode::from(2) + } + Err(RepairErr::IoErr(err)) => { + eprintln!("{}", err); + ExitCode::from(3) + } + }; + + writer.flush()?; + Ok(exit_code) } |
