pax_global_header00006660000000000000000000000064145776366740014543gustar00rootroot0000000000000052 comment=52899c90f747ea57c36be7f72a5dabf574fdf653 json-event-parser-0.2.0/000077500000000000000000000000001457763667400151245ustar00rootroot00000000000000json-event-parser-0.2.0/.github/000077500000000000000000000000001457763667400164645ustar00rootroot00000000000000json-event-parser-0.2.0/.github/dependabot.yml000066400000000000000000000004451457763667400213170ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: weekly - package-ecosystem: gitsubmodule directory: "/" schedule: interval: weekly - package-ecosystem: "github-actions" directory: "/" schedule: interval: weekly json-event-parser-0.2.0/.github/workflows/000077500000000000000000000000001457763667400205215ustar00rootroot00000000000000json-event-parser-0.2.0/.github/workflows/build.yml000066400000000000000000000064301457763667400223460ustar00rootroot00000000000000name: build on: pull_request: branches: - main push: branches: - main schedule: - cron: "12 3 * * *" jobs: fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: rustup update && rustup component add rustfmt - run: cargo fmt -- --check clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: rustup update && rustup override set 1.76.0 && rustup component add clippy - uses: Swatinem/rust-cache@v2 - run: cargo clippy --all-targets -- -D warnings -D clippy::all test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - run: rustup update - uses: Swatinem/rust-cache@v2 - run: cargo test test_msv: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - run: rustup update && rustup override set 1.70.0 && rustup toolchain install nightly - uses: Swatinem/rust-cache@v2 - run: cargo +nightly update -Z direct-minimal-versions - run: cargo test rustdoc: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: rustup update && rustup override set 1.76.0 - uses: Swatinem/rust-cache@v2 - run: cargo doc --all-features --no-deps env: RUSTDOCFLAGS: -D warnings deny: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@v2 with: { tool: cargo-deny } - run: cargo deny check semver_checks: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: rustup update - uses: Swatinem/rust-cache@v2 - uses: taiki-e/install-action@v2 with: { tool: cargo-semver-checks } - run: cargo semver-checks check-release typos: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@v2 with: { tool: typos-cli } - run: typos codspeed: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - run: rustup update - uses: Swatinem/rust-cache@v2 - run: cargo install cargo-codspeed || true - run: cargo codspeed build - uses: CodSpeedHQ/action@v2 with: run: cargo codspeed run token: ${{ secrets.CODSPEED_TOKEN }} fuzz: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - run: rustup update && rustup toolchain install nightly - uses: Swatinem/rust-cache@v2 - uses: taiki-e/install-action@v2 with: { tool: cargo-fuzz } - run: python3 build_corpus.py working-directory: ./fuzz - run: cargo +nightly fuzz run parse -- -max_total_time=300 -max_len=128 codecov: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - run: rustup update - uses: Swatinem/rust-cache@v2 - uses: taiki-e/install-action@v2 with: { tool: cargo-llvm-cov } - run: cargo llvm-cov --codecov --output-path codecov.json - uses: codecov/codecov-action@v3 with: files: codecov.json flags: rust json-event-parser-0.2.0/.gitignore000066400000000000000000000000231457763667400171070ustar00rootroot00000000000000/target Cargo.lock json-event-parser-0.2.0/.gitmodules000066400000000000000000000003341457763667400173010ustar00rootroot00000000000000[submodule "JSONTestSuite"] path = JSONTestSuite url = https://github.com/nst/JSONTestSuite.git [submodule "benches/json-benchmark"] path = benches/json-benchmark url = https://github.com/serde-rs/json-benchmark.git json-event-parser-0.2.0/CHANGELOG.md000066400000000000000000000023151457763667400167360ustar00rootroot00000000000000## [0.2.0] - 2024-02-23 No change compared to the alpha releases. ## [0.2.0-alpha.2] - 2023-11-13 ## Changed - Improves error messages. - Improves ordering of tokens and errors when errors are present. - Fixes file position in case of errors. ## [0.2.0-alpha.1] - 2023-09-23 ### Added - Support of UTF-8 byte-order-mark (BOM) during parsing. - Support of Tokio `AsyncRead` and `AsyncWrite` interfaces behind the `async-tokio` feature. ## Changed - The parser API has been rewritten. The new entry points are `FromBufferJsonReader`, `FromReadJsonReader`, and `LowLevelJsonReader`. - The serializer API has been rewritten. The new entry points are `ToWriteJsonWriter` and `LowLevelJsonWriter`. - The parser now returns `ParseError` and `SyntaxError` types instead of `std::io::Error`. - Escaped unicode surrogate pairs are now carefully validated. - Minimal supported Rust version has been bumped to 1.70. ## [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.2.0/Cargo.toml000066400000000000000000000015161457763667400170570ustar00rootroot00000000000000[package] name = "json-event-parser" version = "0.2.0" authors = ["Tpt "] license = "MIT OR Apache-2.0" readme = "README.md" documentation = "https://docs.rs/json-event-parser" 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 = "2021" rust-version = "1.70" exclude = ["JSONTestSuite"] [features] async-tokio = ["dep:tokio"] [dependencies] tokio = { version = "1.29", optional = true, features = ["io-util"] } [dev-dependencies] codspeed-criterion-compat = "2.3.3" tokio = { version = "1.29", features = ["rt", "macros"] } clap = "4" [[bench]] name = "parser" harness = false [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] json-event-parser-0.2.0/JSONTestSuite/000077500000000000000000000000001457763667400175475ustar00rootroot00000000000000json-event-parser-0.2.0/LICENSE-APACHE000066400000000000000000000251371457763667400170600ustar00rootroot00000000000000 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.2.0/LICENSE-MIT000066400000000000000000000020471457763667400165630ustar00rootroot00000000000000Copyright (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.2.0/README.md000066400000000000000000000043601457763667400164060ustar00rootroot00000000000000JSON 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 JSON parser possible but to be a simple 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::{FromReadJsonReader, JsonEvent}; let json = b"{\"foo\": 1}"; let mut reader = FromReadJsonReader::new(json.as_slice()); assert_eq!(reader.read_next_event()?, JsonEvent::StartObject); assert_eq!(reader.read_next_event()?, JsonEvent::ObjectKey("foo".into())); assert_eq!(reader.read_next_event()?, JsonEvent::Number("1".into())); assert_eq!(reader.read_next_event()?, JsonEvent::EndObject); assert_eq!(reader.read_next_event()?, JsonEvent::Eof); # std::io::Result::Ok(()) ``` Writer example: ```rust use json_event_parser::{ToWriteJsonWriter, JsonEvent}; let mut writer = ToWriteJsonWriter::new(Vec::new()); writer.write_event(JsonEvent::StartObject)?; writer.write_event(JsonEvent::ObjectKey("foo".into()))?; writer.write_event(JsonEvent::Number("1".into()))?; writer.write_event(JsonEvent::EndObject)?; assert_eq!(writer.finish()?.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 ``) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ``) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in json-event-parser 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.2.0/benches/000077500000000000000000000000001457763667400165335ustar00rootroot00000000000000json-event-parser-0.2.0/benches/json-benchmark/000077500000000000000000000000001457763667400214345ustar00rootroot00000000000000json-event-parser-0.2.0/benches/parser.rs000066400000000000000000000035651457763667400204060ustar00rootroot00000000000000use codspeed_criterion_compat::{criterion_group, criterion_main, Criterion}; use json_event_parser::{FromReadJsonReader, JsonEvent}; use std::fs::{self, read_dir}; fn bench_parse_json_benchmark(c: &mut Criterion) { for dataset in ["canada", "citm_catalog", "twitter"] { let data = fs::read(format!( "{}/benches/json-benchmark/data/{dataset}.json", env!("CARGO_MANIFEST_DIR") )) .unwrap(); c.bench_function(dataset, |b| { b.iter(|| { let mut reader = FromReadJsonReader::new(data.as_slice()); while reader.read_next_event().unwrap() != JsonEvent::Eof { //read more } }) }); } } fn bench_parse_testsuite(c: &mut Criterion) { let example = load_testsuite_example(); c.bench_function("JSON test suite", |b| { b.iter(|| { let mut reader = FromReadJsonReader::new(example.as_slice()); while reader.read_next_event().unwrap() != JsonEvent::Eof { //read more } }) }); } fn load_testsuite_example() -> Vec { let mut result = Vec::new(); result.extend_from_slice(b"[\n"); for file in read_dir(format!( "{}/JSONTestSuite/test_parsing", env!("CARGO_MANIFEST_DIR") )) .unwrap() { 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") { if result.len() > 2 { result.extend_from_slice(b",\n"); } result.push(b'\t'); result.extend_from_slice(&fs::read(file.path()).unwrap()); } } result.extend_from_slice(b"\n]"); result } criterion_group!(parser, bench_parse_testsuite, bench_parse_json_benchmark); criterion_main!(parser); json-event-parser-0.2.0/deny.toml000066400000000000000000000002461457763667400167620ustar00rootroot00000000000000[licenses] unlicensed = "deny" allow = [ "MIT", "Apache-2.0", "Unicode-DFS-2016" ] default = "deny" [bans] multiple-versions = "warn" wildcards = "deny" json-event-parser-0.2.0/fuzz/000077500000000000000000000000001457763667400161225ustar00rootroot00000000000000json-event-parser-0.2.0/fuzz/.gitignore000066400000000000000000000000271457763667400201110ustar00rootroot00000000000000target corpus artifactsjson-event-parser-0.2.0/fuzz/Cargo.toml000066400000000000000000000004641457763667400200560ustar00rootroot00000000000000[package] name = "json-event-parser-fuzz" version = "0.0.0" authors = ["Automatically generated"] publish = false edition = "2021" [package.metadata] cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" [dependencies.json-event-parser] path = ".." [[bin]] name = "parse" path = "fuzz_targets/parse.rs" json-event-parser-0.2.0/fuzz/build_corpus.py000066400000000000000000000007331457763667400211710ustar00rootroot00000000000000import hashlib import random from pathlib import Path base = Path(__file__).parent.parent target_dir = base / "fuzz" / "corpus" / "parse" target_dir.mkdir(parents=True, exist_ok=True) for f in base.rglob("*.py"): for _ in range(3): data = f.read_bytes() pos = random.randint(0, len(data)) data = data[:pos] + b"\xff" + data[pos:] hash = hashlib.sha256() hash.update(data) (target_dir / hash.hexdigest()).write_bytes(data) json-event-parser-0.2.0/fuzz/fuzz_targets/000077500000000000000000000000001457763667400206515ustar00rootroot00000000000000json-event-parser-0.2.0/fuzz/fuzz_targets/parse.rs000066400000000000000000000054571457763667400223440ustar00rootroot00000000000000#![no_main] use json_event_parser::{ JsonEvent, LowLevelJsonReader, LowLevelJsonReaderResult, SyntaxError, ToWriteJsonWriter, }; use libfuzzer_sys::fuzz_target; fn parse_chunks(chunks: &[&[u8]]) -> (String, Option) { let mut input_buffer = Vec::new(); let mut input_cursor = 0; let mut output_buffer = Vec::new(); let mut reader = LowLevelJsonReader::new(); let mut writer = ToWriteJsonWriter::new(&mut output_buffer); let mut error = None; for (i, chunk) in chunks.iter().enumerate() { input_buffer.extend_from_slice(chunk); loop { let LowLevelJsonReaderResult { event, consumed_bytes, } = reader.read_next_event(&input_buffer[input_cursor..], i == chunks.len() - 1); input_cursor += consumed_bytes; match event { Some(Ok(JsonEvent::Eof)) => { if error.is_none() { writer.finish().unwrap(); } return (String::from_utf8(output_buffer).unwrap(), error); } Some(Ok(event)) => { if error.is_none() { writer.write_event(event).unwrap(); } else { let _ = writer.write_event(event); // We don't know if we write ok structure } } Some(Err(e)) => { if error.is_none() { error = Some(e) } } None => break, } } } panic!("Should not be reached") } fn merge<'a>(slices: impl IntoIterator) -> Vec { let mut buf = Vec::new(); for slice in slices { buf.extend_from_slice(slice); } buf } fuzz_target!(|data: &[u8]| { // We parse with separators let (with_separators, with_separators_error) = parse_chunks(&data.split(|c| *c == 0xFF).collect::>()); let (without_separators, without_separators_error) = parse_chunks(&[&merge(data.split(|c| *c == 0xFF))]); assert_eq!( with_separators_error .as_ref() .map_or_else(String::new, |e| e.to_string()), without_separators_error .as_ref() .map_or_else(String::new, |e| e.to_string()), "{with_separators_error:?} vs {without_separators_error:?}" ); assert_eq!(with_separators, without_separators); if with_separators_error.is_none() { let (again, again_error) = parse_chunks(&[with_separators.as_bytes()]); assert!( again_error.is_none(), "Failed to parse '{with_separators}' with error {}", again_error.unwrap() ); assert_eq!(with_separators, again); } }); json-event-parser-0.2.0/src/000077500000000000000000000000001457763667400157135ustar00rootroot00000000000000json-event-parser-0.2.0/src/lib.rs000066400000000000000000000017721457763667400170360ustar00rootroot00000000000000#![doc = include_str!("../README.md")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![deny( future_incompatible, nonstandard_style, rust_2018_idioms, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_qualifications )] mod read; mod write; #[cfg(feature = "async-tokio")] pub use crate::read::FromTokioAsyncReadJsonReader; pub use crate::read::{ FromBufferJsonReader, FromReadJsonReader, LowLevelJsonReader, LowLevelJsonReaderResult, ParseError, SyntaxError, TextPosition, }; #[cfg(feature = "async-tokio")] pub use crate::write::ToTokioAsyncWriteJsonWriter; pub use crate::write::{LowLevelJsonWriter, ToWriteJsonWriter}; use std::borrow::Cow; /// Possible events during JSON parsing. #[derive(Eq, PartialEq, Debug, Clone, Hash)] pub enum JsonEvent<'a> { String(Cow<'a, str>), Number(Cow<'a, str>), Boolean(bool), Null, StartArray, EndArray, StartObject, EndObject, ObjectKey(Cow<'a, str>), Eof, } json-event-parser-0.2.0/src/read.rs000066400000000000000000001343041457763667400172010ustar00rootroot00000000000000use crate::JsonEvent; use std::borrow::Cow; use std::cmp::{max, min}; use std::error::Error; use std::io::{self, Read}; use std::ops::Range; use std::{fmt, str}; #[cfg(feature = "async-tokio")] use tokio::io::{AsyncRead, AsyncReadExt}; const MAX_STATE_STACK_SIZE: usize = 65_536; const MIN_BUFFER_SIZE: usize = 4096; const MAX_BUFFER_SIZE: usize = 4096 * 4096; /// Parses a JSON file from a [`Read`] implementation. /// /// /// ``` /// use json_event_parser::{FromReadJsonReader, JsonEvent}; /// /// let mut reader = FromReadJsonReader::new(b"{\"foo\": 1}".as_slice()); /// assert_eq!(reader.read_next_event()?, JsonEvent::StartObject); /// assert_eq!(reader.read_next_event()?, JsonEvent::ObjectKey("foo".into())); /// assert_eq!(reader.read_next_event()?, JsonEvent::Number("1".into())); /// assert_eq!(reader.read_next_event()?, JsonEvent::EndObject); /// assert_eq!(reader.read_next_event()?, JsonEvent::Eof); /// # std::io::Result::Ok(()) /// ``` pub struct FromReadJsonReader { input_buffer: Vec, input_buffer_start: usize, input_buffer_end: usize, max_buffer_size: usize, is_ending: bool, read: R, parser: LowLevelJsonReader, } impl FromReadJsonReader { pub const fn new(read: R) -> Self { Self { input_buffer: Vec::new(), input_buffer_start: 0, input_buffer_end: 0, max_buffer_size: MAX_BUFFER_SIZE, is_ending: false, read, parser: LowLevelJsonReader::new(), } } /// Sets the max size of the internal buffer in bytes pub fn with_max_buffer_size(mut self, size: usize) -> Self { self.max_buffer_size = size; self } pub fn read_next_event(&mut self) -> Result, ParseError> { loop { { let LowLevelJsonReaderResult { event, consumed_bytes, } = self.parser.read_next_event( #[allow(unsafe_code)] unsafe { let input_buffer_ptr: *const [u8] = &self.input_buffer[self.input_buffer_start..self.input_buffer_end]; &*input_buffer_ptr }, // SAFETY: Borrow checker workaround https://github.com/rust-lang/rust/issues/70255 self.is_ending, ); self.input_buffer_start += consumed_bytes; if let Some(event) = event { return Ok(event?); } } if self.input_buffer_start > 0 { self.input_buffer .copy_within(self.input_buffer_start..self.input_buffer_end, 0); self.input_buffer_end -= self.input_buffer_start; self.input_buffer_start = 0; } if self.input_buffer.len() == self.max_buffer_size { return Err(io::Error::new( io::ErrorKind::OutOfMemory, format!( "Reached the buffer maximal size of {}", self.max_buffer_size ), ) .into()); } let min_end = min( self.input_buffer_end + MIN_BUFFER_SIZE, self.max_buffer_size, ); if self.input_buffer.len() < min_end { self.input_buffer.resize(min_end, 0); } if self.input_buffer.len() < self.input_buffer.capacity() { // We keep extending to have as much space as available without reallocation self.input_buffer.resize(self.input_buffer.capacity(), 0); } let read = self .read .read(&mut self.input_buffer[self.input_buffer_end..])?; self.input_buffer_end += read; self.is_ending = read == 0; } } } /// Parses a JSON file from an [`AsyncRead`] implementation. /// /// ``` /// use json_event_parser::{FromTokioAsyncReadJsonReader, JsonEvent}; /// /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> ::std::io::Result<()> { /// let mut reader = FromTokioAsyncReadJsonReader::new(b"{\"foo\": 1}".as_slice()); /// assert_eq!(reader.read_next_event().await?, JsonEvent::StartObject); /// assert_eq!(reader.read_next_event().await?, JsonEvent::ObjectKey("foo".into())); /// assert_eq!(reader.read_next_event().await?, JsonEvent::Number("1".into())); /// assert_eq!(reader.read_next_event().await?, JsonEvent::EndObject); /// assert_eq!(reader.read_next_event().await?, JsonEvent::Eof); /// # Ok(()) /// # } /// ``` #[cfg(feature = "async-tokio")] pub struct FromTokioAsyncReadJsonReader { input_buffer: Vec, input_buffer_start: usize, input_buffer_end: usize, max_buffer_size: usize, is_ending: bool, read: R, parser: LowLevelJsonReader, } #[cfg(feature = "async-tokio")] impl FromTokioAsyncReadJsonReader { pub const fn new(read: R) -> Self { Self { input_buffer: Vec::new(), input_buffer_start: 0, input_buffer_end: 0, max_buffer_size: MAX_BUFFER_SIZE, is_ending: false, read, parser: LowLevelJsonReader::new(), } } /// Sets the max size of the internal buffer in bytes pub fn with_max_buffer_size(mut self, size: usize) -> Self { self.max_buffer_size = size; self } pub async fn read_next_event(&mut self) -> Result, ParseError> { loop { { let LowLevelJsonReaderResult { event, consumed_bytes, } = self.parser.read_next_event( #[allow(unsafe_code)] unsafe { let input_buffer_ptr: *const [u8] = &self.input_buffer[self.input_buffer_start..self.input_buffer_end]; &*input_buffer_ptr }, // Borrow checker workaround https://github.com/rust-lang/rust/issues/70255 self.is_ending, ); self.input_buffer_start += consumed_bytes; if let Some(event) = event { return Ok(event?); } } if self.input_buffer_start > 0 { self.input_buffer .copy_within(self.input_buffer_start..self.input_buffer_end, 0); self.input_buffer_end -= self.input_buffer_start; self.input_buffer_start = 0; } if self.input_buffer.len() == self.max_buffer_size { return Err(io::Error::new( io::ErrorKind::OutOfMemory, format!( "Reached the buffer maximal size of {}", self.max_buffer_size ), ) .into()); } let min_end = min( self.input_buffer_end + MIN_BUFFER_SIZE, self.max_buffer_size, ); if self.input_buffer.len() < min_end { self.input_buffer.resize(min_end, 0); } if self.input_buffer.len() < self.input_buffer.capacity() { // We keep extending to have as much space as available without reallocation self.input_buffer.resize(self.input_buffer.capacity(), 0); } let read = self .read .read(&mut self.input_buffer[self.input_buffer_end..]) .await?; self.input_buffer_end += read; self.is_ending = read == 0; } } } /// Parses a JSON file from a `&[u8]`. /// /// ``` /// use json_event_parser::{FromBufferJsonReader, JsonEvent}; /// /// let mut reader = FromBufferJsonReader::new(b"{\"foo\": 1}"); /// assert_eq!(reader.read_next_event()?, JsonEvent::StartObject); /// assert_eq!(reader.read_next_event()?, JsonEvent::ObjectKey("foo".into())); /// assert_eq!(reader.read_next_event()?, JsonEvent::Number("1".into())); /// assert_eq!(reader.read_next_event()?, JsonEvent::EndObject); /// assert_eq!(reader.read_next_event()?, JsonEvent::Eof); /// # std::io::Result::Ok(()) /// ``` pub struct FromBufferJsonReader<'a> { input_buffer: &'a [u8], parser: LowLevelJsonReader, } impl<'a> FromBufferJsonReader<'a> { pub const fn new(buffer: &'a [u8]) -> Self { Self { input_buffer: buffer, parser: LowLevelJsonReader::new(), } } pub fn read_next_event(&mut self) -> Result, SyntaxError> { loop { let LowLevelJsonReaderResult { event, consumed_bytes, } = self.parser.read_next_event(self.input_buffer, true); self.input_buffer = &self.input_buffer[consumed_bytes..]; if let Some(event) = event { return event; } } } } /// A low-level JSON parser acting on a provided buffer. /// /// 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 [`with_max_stack_size`](LowLevelJsonReader::with_max_stack_size). /// /// ``` /// # use std::borrow::Cow; /// use json_event_parser::{LowLevelJsonReader, JsonEvent, LowLevelJsonReaderResult}; /// /// let mut reader = LowLevelJsonReader::new(); /// assert!(matches!( /// reader.read_next_event(b"{\"foo".as_slice(), false), /// LowLevelJsonReaderResult { consumed_bytes: 1, event: Some(Ok(JsonEvent::StartObject))} /// )); /// assert!(matches!( /// reader.read_next_event(b"\"foo".as_slice(), false), /// LowLevelJsonReaderResult { consumed_bytes: 0, event: None } /// )); /// assert!(matches!( /// reader.read_next_event(b"\"foo\": 1}".as_slice(), false), /// LowLevelJsonReaderResult { consumed_bytes: 5, event: Some(Ok(JsonEvent::ObjectKey(Cow::Borrowed("foo")))) } /// )); /// assert!(matches!( /// reader.read_next_event(b": 1}".as_slice(), false), /// LowLevelJsonReaderResult { consumed_bytes: 3, event: Some(Ok(JsonEvent::Number(Cow::Borrowed("1")))) } /// )); /// assert!(matches!( /// reader.read_next_event(b"}".as_slice(), false), /// LowLevelJsonReaderResult { consumed_bytes: 1, event: Some(Ok(JsonEvent::EndObject)) } /// )); /// assert!(matches!( /// reader.read_next_event(b"".as_slice(), true), /// LowLevelJsonReaderResult { consumed_bytes: 0, event: Some(Ok(JsonEvent::Eof)) } /// )); /// # std::io::Result::Ok(()) /// ``` pub struct LowLevelJsonReader { lexer: JsonLexer, state_stack: Vec, max_state_stack_size: usize, element_read: bool, buffered_event: Option>, } impl LowLevelJsonReader { pub const fn new() -> Self { Self { lexer: JsonLexer { file_offset: 0, file_line: 0, file_start_of_last_line: 0, file_start_of_last_token: 0, is_start: true, }, state_stack: Vec::new(), max_state_stack_size: MAX_STATE_STACK_SIZE, element_read: false, buffered_event: None, } } /// Maximal allowed number of nested object and array openings. Infinite by default. pub fn with_max_stack_size(mut self, size: usize) -> Self { self.max_state_stack_size = size; self } /// Reads a new event from the data in `input_buffer`. /// /// `is_ending` must be set to true if all the JSON data have been already consumed or are in `input_buffer`. pub fn read_next_event<'a>( &mut self, input_buffer: &'a [u8], is_ending: bool, ) -> LowLevelJsonReaderResult<'a> { if let Some(event) = self.buffered_event.take() { return LowLevelJsonReaderResult { consumed_bytes: 0, event: Some(Ok(event)), }; } let start_file_offset = self.lexer.file_offset; while let Some(token) = self.lexer.read_next_token( &input_buffer[usize::try_from(self.lexer.file_offset - start_file_offset).unwrap()..], is_ending, ) { let consumed_bytes = (self.lexer.file_offset - start_file_offset) .try_into() .unwrap(); match token { Ok(token) => { let (event, error) = self.apply_new_token(token); let error = error.map(|e| { self.lexer.syntax_error( self.lexer.file_start_of_last_token..self.lexer.file_offset, e, ) }); if let Some(error) = error { self.buffered_event = event.map(owned_event); return LowLevelJsonReaderResult { consumed_bytes, event: Some(Err(error)), }; } if let Some(event) = event { return LowLevelJsonReaderResult { consumed_bytes, event: Some(Ok(event)), }; } } Err(error) => { return LowLevelJsonReaderResult { consumed_bytes, event: Some(Err(error)), } } } } LowLevelJsonReaderResult { consumed_bytes: (self.lexer.file_offset - start_file_offset) .try_into() .unwrap(), event: if is_ending { self.buffered_event = Some(JsonEvent::Eof); Some(Err(self.lexer.syntax_error( self.lexer.file_offset..self.lexer.file_offset + 1, "Unexpected end of file", ))) } else { None }, } } fn apply_new_token<'a>( &mut self, token: JsonToken<'a>, ) -> (Option>, Option) { match self.state_stack.pop() { Some(JsonState::ObjectKeyOrEnd) => { if token == JsonToken::ClosingCurlyBracket { (Some(JsonEvent::EndObject), None) } else { if let Err(e) = self.push_state_stack(JsonState::ObjectKey) { return (None, Some(e)); } self.apply_new_token(token) } } Some(JsonState::ObjectKey) => { if token == JsonToken::ClosingCurlyBracket { return (Some(JsonEvent::EndObject), Some("Trailing commas are not allowed".into())); } if let Err(e) = self.push_state_stack(JsonState::ObjectColon) { return (None, Some(e)); } if let JsonToken::String(key) = token { (Some(JsonEvent::ObjectKey(key)), None) } else { (None, Some("Object keys must be strings".into())) } } Some(JsonState::ObjectColon) => { if let Err(e) = self.push_state_stack(JsonState::ObjectValue) { return (None, Some(e)); } if token == JsonToken::Colon { (None, None) } else { let (event, _) = self.apply_new_token(token); (event, Some("Object keys must be strings".into())) } } Some(JsonState::ObjectValue) => { if let Err(e) = self.push_state_stack(JsonState::ObjectCommaOrEnd) { return (None, Some(e)); } self.apply_new_token_for_value(token) } Some(JsonState::ObjectCommaOrEnd) => match token { JsonToken::Comma => { (None, self.push_state_stack(JsonState::ObjectKey).err()) } JsonToken::ClosingCurlyBracket => (Some(JsonEvent::EndObject), None), _ => (None, Some("Object values must be followed by a comma to add a new value or a curly bracket to end the object".into())), }, Some(JsonState::ArrayValueOrEnd) =>{ if token == JsonToken::ClosingSquareBracket { return (Some(JsonEvent::EndArray), None); } if let Err(e) = self.push_state_stack(JsonState::ArrayValue) { return (None, Some(e)); } self.apply_new_token(token) } Some(JsonState::ArrayValue) => { if token == JsonToken::ClosingSquareBracket { return (Some(JsonEvent::EndArray), Some("Trailing commas are not allowed".into())); } if let Err(e) = self.push_state_stack(JsonState::ArrayCommaOrEnd) { return (None, Some(e)); } self.apply_new_token_for_value(token) } Some(JsonState::ArrayCommaOrEnd) => match token { JsonToken::Comma => { (None, self.push_state_stack(JsonState::ArrayValue).err()) } JsonToken::ClosingSquareBracket => (Some(JsonEvent::EndArray), None), _ => { let _ = self.push_state_stack(JsonState::ArrayValue); // We already have an error let (event, _) = self.apply_new_token(token); (event, Some("Array values must be followed by a comma to add a new value or a squared bracket to end the array".into())) } } None => if self.element_read { if token == JsonToken::Eof { (Some(JsonEvent::Eof), None) } else { (None, Some("The JSON already contains one root element".into())) } } else { self.element_read = true; self.apply_new_token_for_value(token) } } } fn apply_new_token_for_value<'a>( &mut self, token: JsonToken<'a>, ) -> (Option>, Option) { match token { JsonToken::OpeningSquareBracket => ( Some(JsonEvent::StartArray), self.push_state_stack(JsonState::ArrayValueOrEnd).err(), ), JsonToken::ClosingSquareBracket => ( None, Some("Unexpected closing square bracket, no array to close".into()), ), JsonToken::OpeningCurlyBracket => ( Some(JsonEvent::StartObject), self.push_state_stack(JsonState::ObjectKeyOrEnd).err(), ), JsonToken::ClosingCurlyBracket => ( None, Some("Unexpected closing curly bracket, no array to close".into()), ), JsonToken::Comma => (None, Some("Unexpected comma, no values to separate".into())), JsonToken::Colon => (None, Some("Unexpected colon, no key to follow".into())), JsonToken::String(string) => (Some(JsonEvent::String(string)), None), JsonToken::Number(number) => (Some(JsonEvent::Number(number)), None), JsonToken::True => (Some(JsonEvent::Boolean(true)), None), JsonToken::False => (Some(JsonEvent::Boolean(false)), None), JsonToken::Null => (Some(JsonEvent::Null), None), JsonToken::Eof => ( Some(JsonEvent::Eof), Some("Unexpected end of file, a value was expected".into()), ), } } fn push_state_stack(&mut self, state: JsonState) -> Result<(), String> { self.check_stack_size()?; self.state_stack.push(state); Ok(()) } fn check_stack_size(&self) -> Result<(), String> { if self.state_stack.len() > self.max_state_stack_size { Err(format!( "Max stack size of {} reached on an object opening", self.max_state_stack_size )) } else { Ok(()) } } } #[derive(Eq, PartialEq, Copy, Clone, Debug)] enum JsonState { ObjectKey, ObjectKeyOrEnd, ObjectColon, ObjectValue, ObjectCommaOrEnd, ArrayValue, ArrayValueOrEnd, ArrayCommaOrEnd, } #[derive(Eq, PartialEq, Clone, Debug)] enum JsonToken<'a> { OpeningSquareBracket, // [ ClosingSquareBracket, // ] OpeningCurlyBracket, // { ClosingCurlyBracket, // } Comma, // , Colon, // : String(Cow<'a, str>), // "..." Number(Cow<'a, str>), // 1.2e3 True, // true False, // false Null, // null Eof, // EOF } struct JsonLexer { file_offset: u64, file_line: u64, file_start_of_last_line: u64, file_start_of_last_token: u64, is_start: bool, } impl JsonLexer { fn read_next_token<'a>( &mut self, mut input_buffer: &'a [u8], is_ending: bool, ) -> Option, SyntaxError>> { // We remove BOM at the beginning if self.is_start { if input_buffer.len() < 3 && !is_ending { return None; } self.is_start = false; if input_buffer.starts_with(&[0xEF, 0xBB, 0xBF]) { input_buffer = &input_buffer[3..]; self.file_offset += 3; } } // We skip whitespaces let mut i = 0; while let Some(c) = input_buffer.get(i) { match *c { b' ' | b'\t' => { i += 1; } b'\n' => { i += 1; self.file_line += 1; self.file_start_of_last_line = self.file_offset + u64::try_from(i).unwrap(); } b'\r' => { i += 1; if let Some(c) = input_buffer.get(i) { if *c == b'\n' { i += 1; // \r\n } } else if !is_ending { // We need an extra byte to check if followed by \n i -= 1; self.file_offset += u64::try_from(i).unwrap(); return None; } self.file_line += 1; self.file_start_of_last_line = self.file_offset + u64::try_from(i).unwrap(); } _ => { break; } } } self.file_offset += u64::try_from(i).unwrap(); input_buffer = &input_buffer[i..]; self.file_start_of_last_token = self.file_offset; if is_ending && input_buffer.is_empty() { return Some(Ok(JsonToken::Eof)); } // we get the first character match *input_buffer.first()? { b'{' => { self.file_offset += 1; Some(Ok(JsonToken::OpeningCurlyBracket)) } b'}' => { self.file_offset += 1; Some(Ok(JsonToken::ClosingCurlyBracket)) } b'[' => { self.file_offset += 1; Some(Ok(JsonToken::OpeningSquareBracket)) } b']' => { self.file_offset += 1; Some(Ok(JsonToken::ClosingSquareBracket)) } b',' => { self.file_offset += 1; Some(Ok(JsonToken::Comma)) } b':' => { self.file_offset += 1; Some(Ok(JsonToken::Colon)) } b'"' => self.read_string(input_buffer), b't' => self.read_constant(input_buffer, is_ending, "true", JsonToken::True), b'f' => self.read_constant(input_buffer, is_ending, "false", JsonToken::False), b'n' => self.read_constant(input_buffer, is_ending, "null", JsonToken::Null), b'-' | b'0'..=b'9' => self.read_number(input_buffer, is_ending), c => { self.file_offset += 1; Some(Err(self.syntax_error( self.file_offset - 1..self.file_offset, if c < 128 { format!("Unexpected char: '{}'", char::from(c)) } else { format!("Unexpected byte: \\x{c:X}") }, ))) } } } fn read_string<'a>( &mut self, input_buffer: &'a [u8], ) -> Option, SyntaxError>> { let mut error = None; let mut string: Option<(String, usize)> = None; let mut next_byte_offset = 1; loop { match *input_buffer.get(next_byte_offset)? { b'"' => { // end of string let result = Some(if let Some(error) = error { Err(error) } else if let Some((mut string, read_until)) = string { if read_until < next_byte_offset { let (str, e) = self.decode_utf8( &input_buffer[read_until..next_byte_offset], self.file_offset + u64::try_from(read_until).unwrap(), ); error = error.or(e); string.push_str(&str); } if let Some(error) = error { Err(error) } else { Ok(JsonToken::String(Cow::Owned(string))) } } else { let (string, error) = self .decode_utf8(&input_buffer[1..next_byte_offset], self.file_offset + 1); if let Some(error) = error { Err(error) } else { Ok(JsonToken::String(string)) } }); self.file_offset += u64::try_from(next_byte_offset).unwrap() + 1; return result; } b'\\' => { // Escape sequences if string.is_none() { string = Some((String::new(), 1)) } let (string, read_until) = string.as_mut().unwrap(); if *read_until < next_byte_offset { let (str, e) = self.decode_utf8( &input_buffer[*read_until..next_byte_offset], self.file_offset + u64::try_from(*read_until).unwrap(), ); error = error.or(e); string.push_str(&str); } next_byte_offset += 1; match *input_buffer.get(next_byte_offset)? { b'"' => { string.push('"'); next_byte_offset += 1; } b'\\' => { string.push('\\'); next_byte_offset += 1; } b'/' => { string.push('/'); next_byte_offset += 1; } b'b' => { string.push('\u{8}'); next_byte_offset += 1; } b'f' => { string.push('\u{C}'); next_byte_offset += 1; } b'n' => { string.push('\n'); next_byte_offset += 1; } b'r' => { string.push('\r'); next_byte_offset += 1; } b't' => { string.push('\t'); next_byte_offset += 1; } b'u' => { next_byte_offset += 1; let val = input_buffer.get(next_byte_offset..next_byte_offset + 4)?; next_byte_offset += 4; let code_point = match read_hexa_char(val) { Ok(cp) => cp, Err(e) => { error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error(pos - 4..pos, e)) }); char::REPLACEMENT_CHARACTER.into() } }; if let Some(c) = char::from_u32(code_point) { string.push(c); } else { let high_surrogate = code_point; if !(0xD800..=0xDBFF).contains(&high_surrogate) { error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error( pos - 6..pos, format!( "\\u{:X} is not a valid high surrogate", high_surrogate ), )) }); } let val = input_buffer.get(next_byte_offset..next_byte_offset + 6)?; next_byte_offset += 6; if !val.starts_with(b"\\u") { error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error( pos - 6..pos, format!( "\\u{:X} is a high surrogate and should be followed by a low surrogate \\uXXXX", high_surrogate ) )) }); } let low_surrogate = match read_hexa_char(&val[2..]) { Ok(cp) => cp, Err(e) => { error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error(pos - 6..pos, e)) }); char::REPLACEMENT_CHARACTER.into() } }; if !(0xDC00..=0xDFFF).contains(&low_surrogate) { error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error( pos - 6..pos, format!( "\\u{:X} is not a valid low surrogate", low_surrogate ), )) }); } let code_point = 0x10000 + ((high_surrogate & 0x03FF) << 10) + (low_surrogate & 0x03FF); if let Some(c) = char::from_u32(code_point) { string.push(c) } else { string.push(char::REPLACEMENT_CHARACTER); error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error( pos - 12..pos, format!( "\\u{:X}\\u{:X} is an invalid surrogate pair", high_surrogate, low_surrogate ), )) }); } } } c => { next_byte_offset += 1; error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error( pos - 2..pos, format!("'\\{}' is not a valid escape sequence", char::from(c)), )) }); string.push(char::REPLACEMENT_CHARACTER); } } *read_until = next_byte_offset; } c @ (0..=0x1F) => { error = error.or_else(|| { let pos = self.file_offset + u64::try_from(next_byte_offset).unwrap(); Some(self.syntax_error( pos..pos + 1, format!("'{}' is not allowed in JSON strings", char::from(c)), )) }); next_byte_offset += 1; } _ => { next_byte_offset += 1; } } } } fn read_constant( &mut self, input_buffer: &[u8], is_ending: bool, expected: &str, value: JsonToken<'static>, ) -> Option, SyntaxError>> { if input_buffer.get(..expected.len())? == expected.as_bytes() { self.file_offset += u64::try_from(expected.len()).unwrap(); return Some(Ok(value)); } let ascii_chars = input_buffer .iter() .take_while(|c| c.is_ascii_alphabetic()) .count(); if ascii_chars == input_buffer.len() && !is_ending { return None; // We might read a bigger token } let read = max(1, ascii_chars); // We want to consume at least a byte let start_offset = self.file_offset; self.file_offset += u64::try_from(read).unwrap(); Some(Err(self.syntax_error( start_offset..self.file_offset, format!("{} expected", expected), ))) } fn read_number<'a>( &mut self, input_buffer: &'a [u8], is_ending: bool, ) -> Option, SyntaxError>> { let mut next_byte_offset = 0; if *input_buffer.get(next_byte_offset)? == b'-' { next_byte_offset += 1; } // integer starting with first bytes match *input_buffer.get(next_byte_offset)? { b'0' => { next_byte_offset += 1; } b'1'..=b'9' => { next_byte_offset += 1; next_byte_offset += read_digits(&input_buffer[next_byte_offset..], is_ending)?; } c => { next_byte_offset += 1; self.file_offset += u64::try_from(next_byte_offset).unwrap(); return Some(Err(self.syntax_error( self.file_offset - 1..self.file_offset, format!("A number is not allowed to start with '{}'", char::from(c)), ))); } } // Dot if input_buffer.get(next_byte_offset).map_or_else( || if is_ending { Some(None) } else { None }, |c| Some(Some(*c)), )? == Some(b'.') { next_byte_offset += 1; let c = *input_buffer.get(next_byte_offset)?; next_byte_offset += 1; if !c.is_ascii_digit() { self.file_offset += u64::try_from(next_byte_offset).unwrap(); return Some(Err(self.syntax_error( self.file_offset - 1..self.file_offset, format!( "A number fractional part must start with a digit and not '{}'", char::from(c) ), ))); } next_byte_offset += read_digits(&input_buffer[next_byte_offset..], is_ending)?; } // Exp let c = input_buffer.get(next_byte_offset).map_or_else( || if is_ending { Some(None) } else { None }, |c| Some(Some(*c)), )?; if c == Some(b'e') || c == Some(b'E') { next_byte_offset += 1; match *input_buffer.get(next_byte_offset)? { b'-' | b'+' => { next_byte_offset += 1; let c = *input_buffer.get(next_byte_offset)?; next_byte_offset += 1; if !c.is_ascii_digit() { self.file_offset += u64::try_from(next_byte_offset).unwrap(); return Some(Err(self.syntax_error( self.file_offset - 1..self.file_offset, format!( "A number exponential part must contain at least a digit, '{}' found", char::from(c) ), ))); } } b'0'..=b'9' => { next_byte_offset += 1; } c => { next_byte_offset += 1; self.file_offset += u64::try_from(next_byte_offset).unwrap(); return Some(Err(self.syntax_error( self.file_offset - 1..self.file_offset, format!( "A number exponential part must start with +, - or a digit, '{}' found", char::from(c) ), ))); } } next_byte_offset += read_digits(&input_buffer[next_byte_offset..], is_ending)?; } self.file_offset += u64::try_from(next_byte_offset).unwrap(); Some(Ok(JsonToken::Number(Cow::Borrowed( str::from_utf8(&input_buffer[..next_byte_offset]).unwrap(), )))) } fn decode_utf8<'a>( &self, input_buffer: &'a [u8], start_position: u64, ) -> (Cow<'a, str>, Option) { match str::from_utf8(input_buffer) { Ok(str) => (Cow::Borrowed(str), None), Err(e) => ( String::from_utf8_lossy(input_buffer), Some({ let pos = start_position + u64::try_from(e.valid_up_to()).unwrap(); self.syntax_error(pos..pos + 1, format!("Invalid UTF-8: {e}")) }), ), } } fn syntax_error(&self, file_offset: Range, message: impl Into) -> SyntaxError { let start_file_offset = max(file_offset.start, self.file_start_of_last_line); SyntaxError { location: TextPosition { line: self.file_line, column: start_file_offset - self.file_start_of_last_line, //TODO: unicode offset: start_file_offset, }..TextPosition { line: self.file_line, column: file_offset.end - self.file_start_of_last_line, //TODO: unicode offset: file_offset.end, }, message: message.into(), } } } 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(format!( "Unexpected character in a unicode escape: '{}'", char::from(c) )) } } } Ok(value) } fn read_digits(input_buffer: &[u8], is_ending: bool) -> Option { let count = input_buffer .iter() .take_while(|c| c.is_ascii_digit()) .count(); if count == input_buffer.len() && !is_ending { return None; } Some(count) } fn owned_event(event: JsonEvent<'_>) -> JsonEvent<'static> { match event { JsonEvent::String(s) => JsonEvent::String(s.into_owned().into()), JsonEvent::Number(n) => JsonEvent::Number(n.into_owned().into()), JsonEvent::Boolean(b) => JsonEvent::Boolean(b), JsonEvent::Null => JsonEvent::Null, JsonEvent::StartArray => JsonEvent::StartArray, JsonEvent::EndArray => JsonEvent::EndArray, JsonEvent::StartObject => JsonEvent::StartObject, JsonEvent::EndObject => JsonEvent::EndObject, JsonEvent::ObjectKey(k) => JsonEvent::ObjectKey(k.into_owned().into()), JsonEvent::Eof => JsonEvent::Eof, } } /// Result of [`LowLevelJsonReader::read_next_event`]. #[derive(Debug)] pub struct LowLevelJsonReaderResult<'a> { /// How many bytes have been read from `input_buffer` and should be removed from it. pub consumed_bytes: usize, /// A possible new event pub event: Option, SyntaxError>>, } /// A position in a text i.e. a `line` number starting from 0, a `column` number starting from 0 (in number of code points) and a global file `offset` starting from 0 (in number of bytes). #[derive(Eq, PartialEq, Debug, Clone, Copy)] pub struct TextPosition { pub line: u64, pub column: u64, pub offset: u64, } /// An error in the syntax of the parsed file. /// /// It is composed of a message and a byte range in the input. #[derive(Debug)] pub struct SyntaxError { location: Range, message: String, } impl SyntaxError { /// The location of the error inside of the file. #[inline] pub fn location(&self) -> Range { self.location.clone() } /// The error message. #[inline] pub fn message(&self) -> &str { &self.message } } impl fmt::Display for SyntaxError { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.location.start.offset + 1 >= self.location.end.offset { write!( f, "Parser error at line {} column {}: {}", self.location.start.line + 1, self.location.start.column + 1, self.message ) } else if self.location.start.line == self.location.end.line { write!( f, "Parser error at line {} between columns {} and column {}: {}", self.location.start.line + 1, self.location.start.column + 1, self.location.end.column + 1, self.message ) } else { write!( f, "Parser error between line {} column {} and line {} column {}: {}", self.location.start.line + 1, self.location.start.column + 1, self.location.end.line + 1, self.location.end.column + 1, self.message ) } } } impl Error for SyntaxError {} impl From for io::Error { #[inline] fn from(error: SyntaxError) -> Self { io::Error::new(io::ErrorKind::InvalidData, error) } } /// A parsing error. /// /// It is the union of [`SyntaxError`] and [`std::io::Error`]. #[derive(Debug)] pub enum ParseError { /// I/O error during parsing (file not found...). Io(io::Error), /// An error in the file syntax. Syntax(SyntaxError), } impl fmt::Display for ParseError { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Io(e) => e.fmt(f), Self::Syntax(e) => e.fmt(f), } } } impl Error for ParseError { #[inline] fn source(&self) -> Option<&(dyn Error + 'static)> { Some(match self { Self::Io(e) => e, Self::Syntax(e) => e, }) } } impl From for ParseError { #[inline] fn from(error: SyntaxError) -> Self { Self::Syntax(error) } } impl From for ParseError { #[inline] fn from(error: io::Error) -> Self { Self::Io(error) } } impl From for io::Error { #[inline] fn from(error: ParseError) -> Self { match error { ParseError::Syntax(e) => e.into(), ParseError::Io(e) => e, } } } json-event-parser-0.2.0/src/write.rs000066400000000000000000000234451457763667400174230ustar00rootroot00000000000000use crate::JsonEvent; use std::io::{Error, ErrorKind, Result, Write}; #[cfg(feature = "async-tokio")] use tokio::io::{AsyncWrite, AsyncWriteExt}; /// A JSON streaming writer writing to a [`Write`] implementation. /// /// ``` /// use json_event_parser::{ToWriteJsonWriter, JsonEvent}; /// /// let mut writer = ToWriteJsonWriter::new(Vec::new()); /// writer.write_event(JsonEvent::StartObject)?; /// writer.write_event(JsonEvent::ObjectKey("foo".into()))?; /// writer.write_event(JsonEvent::Number("1".into()))?; /// writer.write_event(JsonEvent::EndObject)?; /// /// assert_eq!(writer.finish()?.as_slice(), b"{\"foo\":1}"); /// # std::io::Result::Ok(()) /// ``` pub struct ToWriteJsonWriter { write: W, writer: LowLevelJsonWriter, } impl ToWriteJsonWriter { pub const fn new(write: W) -> Self { Self { write, writer: LowLevelJsonWriter::new(), } } pub fn write_event(&mut self, event: JsonEvent<'_>) -> Result<()> { self.writer.write_event(event, &mut self.write) } pub fn finish(self) -> Result { self.writer.validate_eof()?; Ok(self.write) } } /// A JSON streaming writer writing to an [`AsyncWrite`] implementation. /// /// ``` /// use json_event_parser::{ToTokioAsyncWriteJsonWriter, JsonEvent}; /// /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> ::std::io::Result<()> { /// let mut writer = ToTokioAsyncWriteJsonWriter::new(Vec::new()); /// writer.write_event(JsonEvent::StartObject).await?; /// writer.write_event(JsonEvent::ObjectKey("foo".into())).await?; /// writer.write_event(JsonEvent::Number("1".into())).await?; /// writer.write_event(JsonEvent::EndObject).await?; /// assert_eq!(writer.finish()?.as_slice(), b"{\"foo\":1}"); /// # Ok(()) /// # } /// ``` #[cfg(feature = "async-tokio")] pub struct ToTokioAsyncWriteJsonWriter { write: W, writer: LowLevelJsonWriter, buffer: Vec, } #[cfg(feature = "async-tokio")] impl ToTokioAsyncWriteJsonWriter { pub const fn new(write: W) -> Self { Self { write, writer: LowLevelJsonWriter::new(), buffer: Vec::new(), } } pub async fn write_event(&mut self, event: JsonEvent<'_>) -> Result<()> { self.writer.write_event(event, &mut self.buffer)?; self.write.write_all(&self.buffer).await?; self.buffer.clear(); Ok(()) } pub fn finish(self) -> Result { self.writer.validate_eof()?; Ok(self.write) } } /// A low-level JSON streaming writer writing to a [`Write`] implementation. /// /// YOu probably want to use [`ToWriteJsonWriter`] instead. /// /// ``` /// use json_event_parser::{JsonEvent, LowLevelJsonWriter}; /// /// let mut writer = LowLevelJsonWriter::new(); /// let mut output = Vec::new(); /// writer.write_event(JsonEvent::StartObject, &mut output)?; /// writer.write_event(JsonEvent::ObjectKey("foo".into()), &mut output)?; /// writer.write_event(JsonEvent::Number("1".into()), &mut output)?; /// writer.write_event(JsonEvent::EndObject, &mut output)?; /// /// assert_eq!(output.as_slice(), b"{\"foo\":1}"); /// # std::io::Result::Ok(()) /// ``` #[derive(Default)] pub struct LowLevelJsonWriter { state_stack: Vec, element_written: bool, } impl LowLevelJsonWriter { pub const fn new() -> Self { Self { state_stack: Vec::new(), element_written: false, } } pub fn write_event(&mut self, event: JsonEvent<'_>, mut write: impl Write) -> Result<()> { match event { JsonEvent::String(s) => { self.before_value(&mut write)?; write_escaped_json_string(&s, write) } JsonEvent::Number(number) => { self.before_value(&mut write)?; write.write_all(number.as_bytes()) } JsonEvent::Boolean(b) => { self.before_value(&mut write)?; write.write_all(if b { b"true" } else { b"false" }) } JsonEvent::Null => { self.before_value(&mut write)?; write.write_all(b"null") } JsonEvent::StartArray => { self.before_value(&mut write)?; self.state_stack.push(JsonState::OpenArray); write.write_all(b"[") } JsonEvent::EndArray => match self.state_stack.pop() { Some(JsonState::OpenArray) | Some(JsonState::ContinuationArray) => { write.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(&mut write)?; self.state_stack.push(JsonState::OpenObject); write.write_all(b"{") } JsonEvent::EndObject => match self.state_stack.pop() { Some(JsonState::OpenObject) | Some(JsonState::ContinuationObject) => { write.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) => write.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 write)?; write.write_all(b":") } JsonEvent::Eof => Err(Error::new( ErrorKind::InvalidInput, "EOF is not allowed in JSON writer", )), } } fn before_value(&mut self, mut write: impl Write) -> 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); write.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(()) } } } } fn validate_eof(&self) -> Result<()> { if !self.state_stack.is_empty() { return Err(Error::new( ErrorKind::InvalidInput, "The written JSON is not balanced: an object or an array has not been closed", )); } if !self.element_written { return Err(Error::new( ErrorKind::InvalidInput, "A JSON file can't be empty", )); } Ok(()) } } enum JsonState { OpenArray, ContinuationArray, OpenObject, ContinuationObject, ObjectValue, } fn write_escaped_json_string(s: &str, mut write: impl Write) -> Result<()> { write.write_all(b"\"")?; let mut buffer = [b'\\', b'u', 0, 0, 0, 0]; for c in s.chars() { match c { '\\' => write.write_all(b"\\\\"), '"' => write.write_all(b"\\\""), c => { if c < char::from(32) { match c { '\u{08}' => write.write_all(b"\\b"), '\u{0C}' => write.write_all(b"\\f"), '\n' => write.write_all(b"\\n"), '\r' => write.write_all(b"\\r"), '\t' => write.write_all(b"\\t"), c => { let mut c = c as u8; for i in (2..6).rev() { let ch = c % 16; buffer[i] = if ch < 10 { b'0' + ch } else { b'A' + ch - 10 }; c /= 16; } write.write_all(&buffer) } } } else { write.write_all(c.encode_utf8(&mut buffer[2..]).as_bytes()) } } }?; } write.write_all(b"\"")?; Ok(()) } json-event-parser-0.2.0/tests/000077500000000000000000000000001457763667400162665ustar00rootroot00000000000000json-event-parser-0.2.0/tests/errors.rs000066400000000000000000000040031457763667400201450ustar00rootroot00000000000000use json_event_parser::{FromBufferJsonReader, JsonEvent, ToWriteJsonWriter}; #[test] fn test_recovery() { let entries = [ (b"[nonono]".as_slice(), "[]"), (b"[a]", "[]"), (b"[1,]", "[1]"), (b"{\"foo\":1,}", "{\"foo\":1}"), (b"{\"foo\" 1}", "{\"foo\":1}"), (b"[1 2]", "[1,2]"), (b"[\"\x00\"]", "[]"), (b"[\"\\uD888\\u1234\"]", "[]"), ]; for (input, expected_output) in entries { let mut reader = FromBufferJsonReader::new(input); let mut writer = ToWriteJsonWriter::new(Vec::new()); loop { match reader.read_next_event() { Ok(JsonEvent::Eof) => break, Ok(event) => writer.write_event(event).unwrap(), Err(_) => (), } } let actual_output = String::from_utf8(writer.finish().unwrap()).unwrap(); assert_eq!( expected_output, actual_output, "on {}", String::from_utf8_lossy(input) ); } } #[test] fn test_error_messages() { let entries = [ ( b"".as_slice(), "Parser error at line 1 column 1: Unexpected end of file, a value was expected", ), ( b"\n}", "Parser error at line 2 column 1: Unexpected closing curly bracket, no array to close", ), ( b"\r\n}", "Parser error at line 2 column 1: Unexpected closing curly bracket, no array to close", ), ( b"\"\n\"", "Parser error at line 1 column 2: '\n' is not allowed in JSON strings", ), ( b"\"\\uDCFF\\u0000\"", "Parser error at line 1 between columns 2 and column 8: \\uDCFF is not a valid high surrogate", ) ]; for (json, error) in entries { assert_eq!( FromBufferJsonReader::new(json) .read_next_event() .unwrap_err() .to_string(), error ); } } json-event-parser-0.2.0/tests/test_suite.rs000066400000000000000000000105371457763667400210320ustar00rootroot00000000000000use json_event_parser::{FromBufferJsonReader, FromReadJsonReader, JsonEvent, ToWriteJsonWriter}; use std::fs::{read_dir, File}; use std::io::{Read, Result}; use std::{fs, str}; const OTHER_VALID_TESTS: [&str; 12] = [ "i_number_double_huge_neg_exp.json", "i_number_huge_exp.json", "i_number_neg_int_huge_exp.json", "i_number_pos_double_huge_exp.json", "i_number_real_neg_overflow.json", "i_number_real_pos_overflow.json", "i_number_real_underflow.json", "i_number_too_big_neg_int.json", "i_number_too_big_pos_int.json", "i_number_very_big_negative_int.json", "i_structure_500_nested_arrays.json", "i_structure_UTF-8_BOM_empty_object.json", ]; const OTHER_INVALID_TESTS: [&str; 23] = [ "i_object_key_lone_2nd_surrogate.json", "i_string_1st_surrogate_but_2nd_missing.json", "i_string_1st_valid_surrogate_2nd_invalid.json", "i_string_incomplete_surrogate_and_escape_valid.json", "i_string_incomplete_surrogate_pair.json", "i_string_incomplete_surrogates_escape_valid.json", "i_string_invalid_lonely_surrogate.json", "i_string_invalid_surrogate.json", "i_string_invalid_utf-8.json", "i_string_inverted_surrogates_U+1D11E.json", "i_string_iso_latin_1.json", "i_string_lone_second_surrogate.json", "i_string_lone_utf8_continuation_byte.json", "i_string_not_in_unicode_range.json", "i_string_overlong_sequence_2_bytes.json", "i_string_overlong_sequence_6_bytes.json", "i_string_overlong_sequence_6_bytes_null.json", "i_string_truncated-utf-8.json", "i_string_UTF8_surrogate_U+D800.json", "i_string_utf16BE_no_BOM.json", "i_string_utf16LE_no_BOM.json", "i_string_UTF-8_invalid_sequence.json", "i_string_UTF-16LE_with_BOM.json", ]; #[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_read_result(File::open(file.path())?); if file_name.starts_with("y_") || OTHER_VALID_TESTS.contains(&file_name.as_ref()) { match result { Ok(serialization) => { let serialization_str = str::from_utf8(&serialization).unwrap(); match parse_buffer_result(&serialization) { Ok(other_serialization) => { let other_serialization_str = str::from_utf8(&other_serialization).unwrap(); assert_eq!( serialization_str, other_serialization_str, "Roundtrip {other_serialization_str} serialization of {serialization_str} is not identical (test {file_name})", ) } Err(error) => { panic!("Parsing of {serialization_str} failed with error {error}") } } } Err(error) => panic!( "Parsing of {file_name} failed with error {error} on {}", fs::read_to_string(file.path())? ), } } else if file_name.starts_with("n_") || OTHER_INVALID_TESTS.contains(&file_name.as_ref()) { if let Ok(json) = result { panic!( "Parsing of {file_name} wrongly succeeded with json {}", str::from_utf8(&json).unwrap() ) } } } Ok(()) } fn parse_buffer_result(read: &[u8]) -> Result> { let mut reader = FromBufferJsonReader::new(read); let mut writer = ToWriteJsonWriter::new(Vec::new()); loop { match reader.read_next_event()? { JsonEvent::Eof => return writer.finish(), e => writer.write_event(e)?, } } } fn parse_read_result(read: impl Read) -> Result> { let mut reader = FromReadJsonReader::new(read); let mut writer = ToWriteJsonWriter::new(Vec::new()); loop { match reader.read_next_event()? { JsonEvent::Eof => return writer.finish(), e => writer.write_event(e)?, } } } json-event-parser-0.2.0/typos.toml000066400000000000000000000000401457763667400171710ustar00rootroot00000000000000[default.extend-words] nd = "nd"