pax_global_header00006660000000000000000000000064141000544220014502gustar00rootroot0000000000000052 comment=d87bdc3f40cf23a96d4e73de8d5995357d5c9730 json-event-parser-0.1.1/000077500000000000000000000000001410005442200150635ustar00rootroot00000000000000json-event-parser-0.1.1/.github/000077500000000000000000000000001410005442200164235ustar00rootroot00000000000000json-event-parser-0.1.1/.github/dependabot.yml000066400000000000000000000003221410005442200212500ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily open-pull-requests-limit: 10 - package-ecosystem: gitsubmodule directory: "/" schedule: interval: daily json-event-parser-0.1.1/.github/workflows/000077500000000000000000000000001410005442200204605ustar00rootroot00000000000000json-event-parser-0.1.1/.github/workflows/build.yml000066400000000000000000000013241410005442200223020ustar00rootroot00000000000000name: build on: [push, pull_request] jobs: fmt: name: fmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - run: rustup update - run: rustup component add rustfmt - run: cargo fmt -- --check clippy: name: clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - run: rustup update - run: rustup component add clippy - run: cargo clippy --all --all-targets test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 with: submodules: true - run: rustup update - run: cargo build - run: cargo test --verbose --all --all-targets env: RUST_BACKTRACE: 1 json-event-parser-0.1.1/.gitignore000066400000000000000000000000231410005442200170460ustar00rootroot00000000000000/target Cargo.lock json-event-parser-0.1.1/.gitmodules000066400000000000000000000001421410005442200172350ustar00rootroot00000000000000[submodule "JSONTestSuite"] path = JSONTestSuite url = https://github.com/nst/JSONTestSuite.git json-event-parser-0.1.1/CHANGELOG.md000066400000000000000000000004701410005442200166750ustar00rootroot00000000000000## [0.1.1] - 2021-07-27 ### Added - Support for encoded UTF-16 surrogate pairs like `"\ud83d\udd25"`. The parser now complies with all [JSONTestSuite](https://github.com/nst/JSONTestSuite) positive and negative tests. ## [0.1.0] - 2021-05-30 ### Added - JSON streaming parser. - JSON streaming serializer. json-event-parser-0.1.1/Cargo.toml000066400000000000000000000007601410005442200170160ustar00rootroot00000000000000[package] name = "json-event-parser" version = "0.1.1" authors = ["Tpt "] license = "MIT OR Apache-2.0" readme = "README.md" keywords = ["JSON"] repository = "https://github.com/oxigraph/json-event-parser" homepage = "https://github.com/oxigraph/json-event-parser" description = """ A JSON event parser and serializer """ edition = "2018" exclude = ["JSONTestSuite"] [dev-dependencies] criterion = "0.3" serde_json = "1" [[bench]] name = "test_suite" harness = falsejson-event-parser-0.1.1/JSONTestSuite/000077500000000000000000000000001410005442200175065ustar00rootroot00000000000000json-event-parser-0.1.1/LICENSE-APACHE000066400000000000000000000251371410005442200170170ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. json-event-parser-0.1.1/LICENSE-MIT000066400000000000000000000020471410005442200165220ustar00rootroot00000000000000Copyright (c) 2018 Oxigraph developers 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. json-event-parser-0.1.1/README.md000066400000000000000000000045031410005442200163440ustar00rootroot00000000000000JSON streaming parser ================= [![actions status](https://github.com/oxigraph/json-event-parser/workflows/build/badge.svg)](https://github.com/oxigraph/json-event-parser/actions) [![Latest Version](https://img.shields.io/crates/v/json-event-parser.svg)](https://crates.io/crates/json-event-parser) [![Released API docs](https://docs.rs/json-event-parser/badge.svg)](https://docs.rs/json-event-parser) JSON event parser is a simple streaming JSON parser and serializer implementation in Rust. It does not aims to be the fastest or the more versatile JSON parser possible but to be an as simple as possible implementation. If you want fast and battle-tested code you might prefer to use [json](https://crates.io/crates/json), [serde_json](https://crates.io/crates/serde_json) or [simd-json](https://crates.io/crates/simd-json). Reader example: ```rust use json_event_parser::{JsonReader, JsonEvent}; use std::io::Cursor; let json = b"{\"foo\": 1}"; let mut reader = JsonReader::from_reader(Cursor::new(json)); let mut buffer = Vec::new(); assert_eq!(JsonEvent::StartObject, reader.read_event(&mut buffer)?); assert_eq!(JsonEvent::ObjectKey("foo"), reader.read_event(&mut buffer)?); assert_eq!(JsonEvent::Number("1"), reader.read_event(&mut buffer)?); assert_eq!(JsonEvent::EndObject, reader.read_event(&mut buffer)?); assert_eq!(JsonEvent::Eof, reader.read_event(&mut buffer)?); # std::io::Result::Ok(()) ``` Writer example: ```rust use json_event_parser::{JsonWriter, JsonEvent}; let mut buffer = Vec::new(); let mut writer = JsonWriter::from_writer(&mut buffer); writer.write_event(JsonEvent::StartObject)?; writer.write_event(JsonEvent::ObjectKey("foo"))?; writer.write_event(JsonEvent::Number("1"))?; writer.write_event(JsonEvent::EndObject)?; assert_eq!(buffer.as_slice(), b"{\"foo\":1}"); # std::io::Result::Ok(()) ``` ## License This project is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Futures by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. json-event-parser-0.1.1/benches/000077500000000000000000000000001410005442200164725ustar00rootroot00000000000000json-event-parser-0.1.1/benches/test_suite.rs000066400000000000000000000041261410005442200212330ustar00rootroot00000000000000use criterion::{criterion_group, criterion_main, Criterion}; use json_event_parser::{JsonEvent, JsonReader}; use std::fs::{read_dir, File}; use std::io::{Cursor, Read}; fn bench_json_parse(c: &mut Criterion) { let examples = load_testsuite_examples(); c.bench_function("JSON test suite", |b| { b.iter(|| { let mut buffer = Vec::new(); for json in examples.iter() { let mut reader = JsonReader::from_reader(Cursor::new(json)); while reader.read_event(&mut buffer).unwrap() != JsonEvent::Eof { //read more } } }) }); } fn bench_serde_json_parse(c: &mut Criterion) { let examples = load_testsuite_examples(); c.bench_function("Serde JSON test suite", |b| { b.iter(|| { for json in examples.iter() { let _: serde_json::Value = serde_json::from_reader(Cursor::new(json)).unwrap(); } }) }); } fn load_testsuite_examples() -> Vec> { let blacklist = vec![ "y_string_accepted_surrogate_pair.json", "y_string_accepted_surrogate_pairs.json", "y_string_last_surrogates_1_and_2.json", "y_string_unicode_U+1FFFE_nonchar.json", "y_string_unicode_U+10FFFE_nonchar.json", "y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json", ]; read_dir(format!( "{}/JSONTestSuite/test_parsing", env!("CARGO_MANIFEST_DIR") )) .unwrap() .filter_map(|file| { let file = file.unwrap(); let file_name = file.file_name().to_str().unwrap().to_owned(); if file_name.starts_with("y_") && file_name.ends_with(".json") && !blacklist.contains(&file_name.as_str()) { let mut buf = Vec::new(); File::open(file.path()) .unwrap() .read_to_end(&mut buf) .unwrap(); Some(buf) } else { None } }) .collect() } criterion_group!(parser, bench_json_parse, bench_serde_json_parse); criterion_main!(parser); json-event-parser-0.1.1/src/000077500000000000000000000000001410005442200156525ustar00rootroot00000000000000json-event-parser-0.1.1/src/lib.rs000066400000000000000000000033201410005442200167640ustar00rootroot00000000000000//! JSON event parser is a simple streaming JSON parser and serializer implementation. //! //! It does not aims to be the fastest or the more versatile JSON parser possible but to just be an as simple as possible implementation. //! //! Reader example: //! //! ```rust //! use json_event_parser::{JsonReader, JsonEvent}; //! use std::io::Cursor; //! //! let json = b"{\"foo\": 1}"; //! let mut reader = JsonReader::from_reader(Cursor::new(json)); //! //! let mut buffer = Vec::new(); //! assert_eq!(JsonEvent::StartObject, reader.read_event(&mut buffer)?); //! assert_eq!(JsonEvent::ObjectKey("foo"), reader.read_event(&mut buffer)?); //! assert_eq!(JsonEvent::Number("1"), reader.read_event(&mut buffer)?); //! assert_eq!(JsonEvent::EndObject, reader.read_event(&mut buffer)?); //! assert_eq!(JsonEvent::Eof, reader.read_event(&mut buffer)?); //! //! # std::io::Result::Ok(()) //! ``` //! //! Writer example: //! //! ```rust //! use json_event_parser::{JsonWriter, JsonEvent}; //! //! let mut buffer = Vec::new(); //! let mut writer = JsonWriter::from_writer(&mut buffer); //! writer.write_event(JsonEvent::StartObject)?; //! writer.write_event(JsonEvent::ObjectKey("foo"))?; //! writer.write_event(JsonEvent::Number("1"))?; //! writer.write_event(JsonEvent::EndObject)?; //! //! assert_eq!(buffer.as_slice(), b"{\"foo\":1}"); //! //! # std::io::Result::Ok(()) //! ``` mod read; mod write; pub use crate::read::JsonReader; pub use crate::write::JsonWriter; /// Possible events during JSON parsing #[derive(Eq, PartialEq, Debug, Clone, Copy, Hash)] pub enum JsonEvent<'a> { String(&'a str), Number(&'a str), Boolean(bool), Null, StartArray, EndArray, StartObject, EndObject, ObjectKey(&'a str), Eof, } json-event-parser-0.1.1/src/read.rs000066400000000000000000000462311410005442200171410ustar00rootroot00000000000000use crate::JsonEvent; use std::io::{BufRead, Error, ErrorKind, Result}; use std::str; /// A simple JSON streaming parser. /// /// Does not allocate except a stack to check if array and object opening and closing are properly nested. /// This stack size might be limited using the method [`max_stack_size`](JsonReader::max_stack_size). /// /// Example: /// ```rust /// use json_event_parser::{JsonReader, JsonEvent}; /// use std::io::Cursor; /// /// let json = b"{\"foo\": 1}"; /// let mut reader = JsonReader::from_reader(Cursor::new(json)); /// /// let mut buffer = Vec::new(); /// assert_eq!(JsonEvent::StartObject, reader.read_event(&mut buffer)?); /// assert_eq!(JsonEvent::ObjectKey("foo"), reader.read_event(&mut buffer)?); /// assert_eq!(JsonEvent::Number("1"), reader.read_event(&mut buffer)?); /// assert_eq!(JsonEvent::EndObject, reader.read_event(&mut buffer)?); /// assert_eq!(JsonEvent::Eof, reader.read_event(&mut buffer)?); /// /// # std::io::Result::Ok(()) /// ``` pub struct JsonReader { reader: R, state_stack: Vec, element_read: bool, max_stack_size: Option, } impl JsonReader { pub fn from_reader(reader: R) -> Self { Self { reader, state_stack: Vec::new(), element_read: false, max_stack_size: None, } } /// Maximal allowed number of nested object and array openings. Infinite by default. pub fn max_stack_size(&mut self, size: usize) -> &mut Self { self.max_stack_size = Some(size); self } pub fn read_event<'a>(&mut self, buffer: &'a mut Vec) -> Result> { let front = if let Some(b) = self.lookup_front_skipping_whitespaces()? { b } else { return if self.state_stack.is_empty() && self.element_read { Ok(JsonEvent::Eof) } else { Err(Error::from(ErrorKind::UnexpectedEof)) }; }; match front { b'{' => { self.reader.consume(1); self.check_stack_size()?; self.state_stack.push(JsonState::FirstObjectKey); Ok(JsonEvent::StartObject) } b'}' => { self.reader.consume(1); if matches!( self.state_stack.pop(), Some(JsonState::FirstObjectKey) | Some(JsonState::LastObjectKey) ) { self.read_after_value(JsonEvent::EndObject) } else { Err(Error::new( ErrorKind::InvalidData, "Closing a not opened object", )) } } b'[' => { self.reader.consume(1); self.check_stack_size()?; self.state_stack.push(JsonState::FirstArray); Ok(JsonEvent::StartArray) } b']' => { self.reader.consume(1); if matches!( self.state_stack.pop(), Some(JsonState::FirstArray) | Some(JsonState::LastArray) ) { self.read_after_value(JsonEvent::EndArray) } else { Err(Error::new( ErrorKind::InvalidData, "Closing a not opened array", )) } } b'"' => self.parse_string(buffer), b't' => self.parse_constant::<4>("true", JsonEvent::Boolean(true)), b'f' => self.parse_constant::<5>("false", JsonEvent::Boolean(false)), b'n' => self.parse_constant::<4>("null", JsonEvent::Null), b'-' | b'0'..=b'9' => self.parse_number(front, buffer), c => { self.reader.consume(1); Err(Error::new( ErrorKind::InvalidData, format!("Unexpected char: {}", char::from(c)), )) } } } fn parse_string<'a>(&mut self, output: &'a mut Vec) -> Result> { output.clear(); self.reader.consume(1); #[derive(Eq, PartialEq, Copy, Clone)] enum StringState { Default, Escape, } let mut state = StringState::Default; loop { match state { StringState::Default => { let buffer = match self.reader.fill_buf() { Ok(buf) => { if buf.is_empty() { return Err(Error::from(ErrorKind::UnexpectedEof)); } else { buf } } Err(e) => { if e.kind() == ErrorKind::Interrupted { continue; } else { return Err(e); } } }; let mut i = 0; for c in buffer { i += 1; match *c { b'"' => { self.reader.consume(i); return self.read_after_value(JsonEvent::String( str::from_utf8(output.as_slice()) .map_err(|e| Error::new(ErrorKind::InvalidData, e))?, )); } b'\\' => { state = StringState::Escape; break; } 0..=0x1F => { self.reader.consume(i); return Err(Error::new( ErrorKind::InvalidData, "Control characters are not allowed in JSON", )); } c => output.push(c), } } self.reader.consume(i); } StringState::Escape => { let c = self.lookup_mandatory_front()?; self.reader.consume(1); match c { b'"' => { output.push(b'"'); } b'\\' => { output.push(b'\\'); } b'/' => { output.push(b'/'); } b'b' => { output.push(8); } b'f' => { output.push(12); } b'n' => { output.push(b'\n'); } b'r' => { output.push(b'\r'); } b't' => { output.push(b'\t'); } b'u' => { let mut buf = [0u8; 4]; self.reader.read_exact(&mut buf)?; let code_point = read_hexa_char(&buf)?; if let Some(c) = char::from_u32(code_point) { output.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()); } else { let high_surrogate = code_point; let mut buf = [0u8; 6]; self.reader.read_exact(&mut buf)?; if !buf.starts_with(b"\\u") { return Err(Error::new( ErrorKind::InvalidData, format!( "\\u{:X} is a surrogate should be followed by an other surrogate", high_surrogate ), )); } let low_surrogate = read_hexa_char(&buf[2..])?; let code_point = 0x10000 + ((high_surrogate & 0x03FF) << 10) + (low_surrogate & 0x03FF); if let Some(c) = char::from_u32(code_point) { output.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()) } else { return Err(Error::new( ErrorKind::InvalidData, format!( "\\u{:X}\\u{:X} is an invalid surrogate pair", high_surrogate, low_surrogate ), )); } } } _ => { return Err(Error::new( ErrorKind::InvalidData, "Invalid string escape", )); } } state = StringState::Default; } } } } fn parse_constant<'a, const SIZE: usize>( &mut self, expected: &str, value: JsonEvent<'a>, ) -> Result> { debug_assert_eq!(expected.len(), SIZE); let mut buf = [0u8; SIZE]; self.reader.read_exact(&mut buf)?; if buf == expected.as_bytes() { self.read_after_value(value) } else { Err(Error::new( ErrorKind::InvalidData, format!( "{} expected, found {}", expected, str::from_utf8(&buf).map_err(|e| Error::new(ErrorKind::InvalidData, e))? ), )) } } fn parse_number<'a>( &mut self, first_byte: u8, output: &'a mut Vec, ) -> Result> { output.clear(); if first_byte == b'-' { output.push(b'-'); self.reader.consume(1); } // integer starting with first bytes // TODO: avoid too many fill_buf let c = self.lookup_mandatory_front()?; match c { b'0' => { output.push(b'0'); self.reader.consume(1); } b'1'..=b'9' => { output.push(c); self.reader.consume(1); self.read_digits(output)?; } _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid number")), } // Dot if self.lookup_front()? == Some(b'.') { output.push(b'.'); self.reader.consume(1); self.read_char(|c| matches!(c, b'0'..=b'9'), output)?; self.read_digits(output)?; } // Exp if let Some(c) = self.lookup_front()? { if c == b'e' || c == b'E' { output.push(c); self.reader.consume(1); let c = self.lookup_mandatory_front()?; match c { b'-' | b'+' => { output.push(c); self.reader.consume(1); self.read_char(|c| matches!(c, b'0'..=b'9'), output)?; } b'0'..=b'9' => { output.push(c); self.reader.consume(1); } _ => { return Err(Error::new( ErrorKind::InvalidData, format!("Invalid number. Found char {}", char::from(c)), )) } } self.read_digits(output)?; } } self.read_after_value(JsonEvent::Number( str::from_utf8(output.as_slice()).map_err(|e| Error::new(ErrorKind::InvalidData, e))?, )) } fn read_char(&mut self, valid: impl Fn(u8) -> bool, output: &mut Vec) -> Result<()> { let c = self.lookup_mandatory_front()?; if valid(c) { output.push(c); self.reader.consume(1); Ok(()) } else { Err(Error::new( ErrorKind::InvalidData, format!("Invalid number. Found char {}", char::from(c)), )) } } fn read_digits(&mut self, output: &mut Vec) -> Result<()> { while let Some(c) = self.lookup_front()? { if matches!(c, b'0'..=b'9') { output.push(c); self.reader.consume(1); } else { break; } } Ok(()) } fn read_after_value<'a>(&mut self, value: JsonEvent<'a>) -> Result> { match self.state_stack.pop() { Some(JsonState::FirstObjectKey) | Some(JsonState::NextObjectKey) => { if self.lookup_front_skipping_whitespaces()? == Some(b':') { self.reader.consume(1); self.state_stack.push(JsonState::ObjectValue); if let JsonEvent::String(value) = value { Ok(JsonEvent::ObjectKey(value)) } else { Err(Error::new( ErrorKind::InvalidData, "Object keys should strings", )) } } else { Err(Error::new( ErrorKind::InvalidData, "Object keys should be followed by ':'", )) } } Some(JsonState::ObjectValue) => match self.lookup_front_skipping_whitespaces()? { Some(b',') => { self.reader.consume(1); self.state_stack.push(JsonState::NextObjectKey); Ok(value) } Some(b'}') => { self.state_stack.push(JsonState::LastObjectKey); Ok(value) } _ => Err(Error::new( ErrorKind::InvalidData, "Object values should be followed by a comma or the object end", )), }, Some(JsonState::FirstArray) | Some(JsonState::NextArray) => { match self.lookup_front_skipping_whitespaces()? { Some(b',') => { self.reader.consume(1); self.state_stack.push(JsonState::NextArray); Ok(value) } Some(b']') => { self.state_stack.push(JsonState::LastArray); Ok(value) } _ => Err(Error::new( ErrorKind::InvalidData, "Array values should be followed by a comma or the array end", )), } } None => { if self.element_read { Err(Error::new(ErrorKind::InvalidData, "JSON trailing content")) } else { self.element_read = true; Ok(value) } } Some(JsonState::LastObjectKey) => Err(Error::new( ErrorKind::InvalidData, "JSON object elements should be separated by commas", )), Some(JsonState::LastArray) => Err(Error::new( ErrorKind::InvalidData, "JSON array elements should be separated by commas", )), } } fn lookup_front_skipping_whitespaces(&mut self) -> Result> { loop { match self.reader.fill_buf() { Ok(buf) => { if buf.is_empty() { return Ok(None); } let skipped = skip_whitespaces(buf); if skipped == buf.len() { self.reader.consume(skipped); } else { let result = Some(buf[skipped]); self.reader.consume(skipped); return Ok(result); } } Err(error) => { if error.kind() != ErrorKind::Interrupted { return Err(error); } } } } } fn lookup_mandatory_front(&mut self) -> Result { if let Some(v) = self.lookup_front()? { Ok(v) } else { Err(Error::from(ErrorKind::UnexpectedEof)) } } fn lookup_front(&mut self) -> Result> { loop { match self.reader.fill_buf() { Ok(buf) => return Ok(if buf.is_empty() { None } else { Some(buf[0]) }), Err(error) => { if error.kind() != ErrorKind::Interrupted { return Err(error); } } } } } fn check_stack_size(&self) -> Result<()> { if let Some(max_stack_size) = self.max_stack_size { if self.state_stack.len() > max_stack_size { Err(Error::new( ErrorKind::InvalidData, format!( "Max stack size of {} reached on an object opening", max_stack_size ), )) } else { Ok(()) } } else { Ok(()) } } } #[derive(Eq, PartialEq, Copy, Clone)] enum JsonState { FirstArray, NextArray, LastArray, FirstObjectKey, NextObjectKey, LastObjectKey, ObjectValue, } fn skip_whitespaces(buf: &[u8]) -> usize { for (i, c) in buf.iter().enumerate() { if !matches!(c, b' ' | b'\t' | b'\n' | b'\r') { return i; } } buf.len() } fn read_hexa_char(input: &[u8]) -> Result { let mut value = 0; for c in input.iter().copied() { value = value * 16 + match c { b'0'..=b'9' => u32::from(c) - u32::from(b'0'), b'a'..=b'f' => u32::from(c) - u32::from(b'a') + 10, b'A'..=b'F' => u32::from(c) - u32::from(b'A') + 10, _ => { return Err(Error::new( ErrorKind::InvalidData, "Unexpected character in a unicode escape", )) } } } Ok(value) } json-event-parser-0.1.1/src/write.rs000066400000000000000000000154621410005442200173620ustar00rootroot00000000000000use crate::JsonEvent; use std::io::{Error, ErrorKind, Result, Write}; /// A simple JSON streaming writer. /// /// ```rust /// use json_event_parser::{JsonWriter, JsonEvent}; /// /// let mut buffer = Vec::new(); /// let mut writer = JsonWriter::from_writer(&mut buffer); /// writer.write_event(JsonEvent::StartObject)?; /// writer.write_event(JsonEvent::ObjectKey("foo"))?; /// writer.write_event(JsonEvent::Number("1"))?; /// writer.write_event(JsonEvent::EndObject)?; /// /// assert_eq!(buffer.as_slice(), b"{\"foo\":1}"); /// /// # std::io::Result::Ok(()) /// ``` pub struct JsonWriter { writer: W, state_stack: Vec, element_written: bool, } impl JsonWriter { pub fn from_writer(writer: W) -> Self { Self { writer, state_stack: Vec::new(), element_written: false, } } pub fn into_inner(self) -> W { self.writer } pub fn inner(&mut self) -> &mut W { &mut self.writer } pub fn write_event(&mut self, event: JsonEvent<'_>) -> Result<()> { match event { JsonEvent::String(s) => { self.before_value()?; write_escaped_json_string(s, &mut self.writer) } JsonEvent::Number(number) => { self.before_value()?; self.writer.write_all(number.as_bytes()) } JsonEvent::Boolean(b) => { self.before_value()?; self.writer.write_all(if b { b"true" } else { b"false" }) } JsonEvent::Null => { self.before_value()?; self.writer.write_all(b"null") } JsonEvent::StartArray => { self.before_value()?; self.state_stack.push(JsonState::OpenArray); self.writer.write_all(b"[") } JsonEvent::EndArray => match self.state_stack.pop() { Some(JsonState::OpenArray) | Some(JsonState::ContinuationArray) => { self.writer.write_all(b"]") } Some(s) => { self.state_stack.push(s); Err(Error::new( ErrorKind::InvalidInput, "Closing a not opened array", )) } None => Err(Error::new( ErrorKind::InvalidInput, "Closing a not opened array", )), }, JsonEvent::StartObject => { self.before_value()?; self.state_stack.push(JsonState::OpenObject); self.writer.write_all(b"{") } JsonEvent::EndObject => match self.state_stack.pop() { Some(JsonState::OpenObject) | Some(JsonState::ContinuationObject) => { self.writer.write_all(b"}") } Some(s) => { self.state_stack.push(s); Err(Error::new( ErrorKind::InvalidInput, "Closing a not opened object", )) } None => Err(Error::new( ErrorKind::InvalidInput, "Closing a not opened object", )), }, JsonEvent::ObjectKey(key) => { match self.state_stack.pop() { Some(JsonState::OpenObject) => (), Some(JsonState::ContinuationObject) => self.writer.write_all(b",")?, _ => { return Err(Error::new( ErrorKind::InvalidInput, "Trying to write an object key in an not object", )) } } self.state_stack.push(JsonState::ContinuationObject); self.state_stack.push(JsonState::ObjectValue); write_escaped_json_string(key, &mut self.writer)?; self.writer.write_all(b":") } JsonEvent::Eof => Err(Error::new( ErrorKind::InvalidInput, "EOF is not allowed in JSON writer", )), } } fn before_value(&mut self) -> Result<()> { match self.state_stack.pop() { Some(JsonState::OpenArray) => { self.state_stack.push(JsonState::ContinuationArray); Ok(()) } Some(JsonState::ContinuationArray) => { self.state_stack.push(JsonState::ContinuationArray); self.writer.write_all(b",")?; Ok(()) } Some(last_state @ JsonState::OpenObject) | Some(last_state @ JsonState::ContinuationObject) => { self.state_stack.push(last_state); Err(Error::new( ErrorKind::InvalidInput, "Object key expected, string found", )) } Some(JsonState::ObjectValue) => Ok(()), None => { if self.element_written { Err(Error::new( ErrorKind::InvalidInput, "A root JSON value has already been written", )) } else { self.element_written = true; Ok(()) } } } } } enum JsonState { OpenArray, ContinuationArray, OpenObject, ContinuationObject, ObjectValue, } fn write_escaped_json_string(s: &str, sink: &mut impl Write) -> Result<()> { sink.write_all(b"\"")?; let mut buffer = [b'\\', b'u', 0, 0, 0, 0]; for c in s.chars() { match c { '\\' => sink.write_all(b"\\\\"), '"' => sink.write_all(b"\\\""), c => { if c < char::from(32) { match c { '\u{08}' => sink.write_all(b"\\b"), '\u{0C}' => sink.write_all(b"\\f"), '\n' => sink.write_all(b"\\n"), '\r' => sink.write_all(b"\\r"), '\t' => sink.write_all(b"\\t"), c => { let mut c = c as u8; for i in (2..6).rev() { let ch = c % 16; buffer[i] = ch + if ch < 10 { b'0' } else { b'A' }; c /= 16; } sink.write_all(&buffer) } } } else { sink.write_all(c.encode_utf8(&mut buffer[2..]).as_bytes()) } } }?; } sink.write_all(b"\"")?; Ok(()) } json-event-parser-0.1.1/tests/000077500000000000000000000000001410005442200162255ustar00rootroot00000000000000json-event-parser-0.1.1/tests/test_suite.rs000066400000000000000000000034711410005442200207700ustar00rootroot00000000000000use json_event_parser::{JsonEvent, JsonReader, JsonWriter}; use std::fs::{read_dir, File}; use std::io::{BufReader, Read, Result}; use std::str; #[test] fn test_testsuite_parsing() -> Result<()> { for file in read_dir(format!( "{}/JSONTestSuite/test_parsing", env!("CARGO_MANIFEST_DIR") ))? { let file = file?; let file_name = file.file_name().to_str().unwrap().to_owned(); if !file_name.ends_with(".json") { continue; } let result = parse_result(File::open(file.path())?); if file_name.starts_with("y_") { match result { Ok(serialization) => match parse_result(serialization.as_slice()) { Ok(other_serialization) => assert_eq!(serialization, other_serialization), Err(error) => panic!( "Parsing of {} failed with error {}", str::from_utf8(&serialization).unwrap(), error ), }, Err(error) => panic!("Parsing of {} failed with error {}", file_name, error), } } else if file_name.starts_with("n_") { assert!( result.is_err(), "Parsing of {} wrongly succeeded", file_name ) } } Ok(()) } fn parse_result(read: impl Read) -> Result> { let mut buffer = Vec::new(); let mut output_buffer = Vec::new(); let mut reader = JsonReader::from_reader(BufReader::new(read)); let mut writer = JsonWriter::from_writer(&mut output_buffer); loop { match reader.read_event(&mut buffer) { Ok(JsonEvent::Eof) => return Ok(output_buffer), Ok(e) => writer.write_event(e)?, Err(e) => return Err(e), } } }