From 0b2a02490a4ea20d130a081f65eb2e0407e46b03 Mon Sep 17 00:00:00 2001 From: devrosch Date: Tue, 6 Jan 2026 11:13:04 +0100 Subject: [PATCH 1/3] add lazy loading capability and u64 position --- .github/workflows/ci.yml | 20 +-- Cargo.toml | 16 ++- README.md | 138 +++++++++++++++---- fuzz/Cargo.toml | 4 +- fuzz/fuzz_targets/from_slice.rs | 2 +- src/de.rs | 43 +++--- src/error.rs | 32 ++--- src/iter.rs | 12 +- src/lib.rs | 49 +++---- src/macros.rs | 8 +- src/map.rs | 90 ++++++------ src/number.rs | 12 +- src/raw.rs | 38 ++--- src/read.rs | 20 +-- src/span.rs | 137 ++++++++++++++++++ src/value/from.rs | 32 ++--- src/value/index.rs | 12 +- src/value/mod.rs | 116 ++++++++-------- src/value/ser.rs | 8 +- tests/crate/Cargo.toml | 18 +-- tests/crate/test.rs | 2 +- tests/debug.rs | 4 +- tests/map.rs | 2 +- tests/regression/issue1004.rs | 4 +- tests/regression/issue520.rs | 4 +- tests/regression/issue795.rs | 6 +- tests/regression/issue845.rs | 10 +- tests/regression/issue953.rs | 6 +- tests/span.rs | 153 +++++++++++++++++++++ tests/stream.rs | 2 +- tests/test.rs | 102 +++++++------- tests/ui/missing_colon.rs | 2 +- tests/ui/missing_comma.rs | 2 +- tests/ui/missing_value.rs | 2 +- tests/ui/not_found.rs | 2 +- tests/ui/parse_expr.rs | 2 +- tests/ui/parse_key.rs | 2 +- tests/ui/unexpected_after_array_element.rs | 2 +- tests/ui/unexpected_after_map_entry.rs | 2 +- tests/ui/unexpected_colon.rs | 2 +- tests/ui/unexpected_comma.rs | 2 +- 41 files changed, 765 insertions(+), 357 deletions(-) create mode 100644 src/span.rs create mode 100644 tests/span.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 10e6e6066..f36fe42ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,17 +64,17 @@ jobs: - run: cargo check --manifest-path tests/crate/Cargo.toml --features arbitrary_precision - run: cargo check --manifest-path tests/crate/Cargo.toml --features raw_value - run: cargo check --manifest-path tests/crate/Cargo.toml --features unbounded_depth - - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc - - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc,arbitrary_precision - - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc,raw_value - - run: cargo check --manifest-path tests/crate/Cargo.toml --features serde_json/preserve_order + # - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc + # - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc,arbitrary_precision + # - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc,raw_value + - run: cargo check --manifest-path tests/crate/Cargo.toml --features sciformats_serde_json/preserve_order if: matrix.rust != '1.68.0' - - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc,serde_json/preserve_order - if: matrix.rust != '1.68.0' - - name: Build without std - run: cargo check --manifest-path tests/crate/Cargo.toml --target - ${{matrix.target}} --no-default-features --features alloc - if: matrix.target + # - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features --features alloc,serde_json/preserve_order + # if: matrix.rust != '1.68.0' + # - name: Build without std + # run: cargo check --manifest-path tests/crate/Cargo.toml --target + # ${{matrix.target}} --no-default-features --features alloc + # if: matrix.target minimal: name: Minimal versions diff --git a/Cargo.toml b/Cargo.toml index 9845be6d9..2d6826efa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,11 @@ [package] -name = "serde_json" -version = "1.0.148" -authors = ["Erick Tryzelaar ", "David Tolnay "] +name = "sciformats_serde_json" +version = "0.0.148" +authors = [ + "Erick Tryzelaar ", + "David Tolnay ", + "Robert Schiwon ", +] categories = ["encoding", "parser-implementations", "no-std"] description = "A JSON serialization file format" documentation = "https://docs.rs/serde_json" @@ -59,7 +63,7 @@ std = ["memchr/std", "serde_core/std"] # NOTE: Disabling both `std` *and* `alloc` features is not supported yet. alloc = ["serde_core/alloc"] -# Make serde_json::Map use a representation which maintains insertion order. +# Make sciformats_serde_json::Map use a representation which maintains insertion order. # This allows data to be read into a Value and written back to a JSON string # while preserving the order of map keys in the input. preserve_order = ["indexmap", "std"] @@ -73,11 +77,11 @@ preserve_order = ["indexmap", "std"] # output identical to the input. float_roundtrip = [] -# Use an arbitrary precision number representation for serde_json::Number. This +# Use an arbitrary precision number representation for sciformats_serde_json::Number. This # allows JSON numbers of arbitrary size/precision to be read into a Number and # written back to a JSON string without loss of precision. # -# Unlike float_roundtrip, this feature makes JSON -> serde_json::Number -> JSON +# Unlike float_roundtrip, this feature makes JSON -> sciformats_serde_json::Number -> JSON # produce output identical to the input. arbitrary_precision = [] diff --git a/README.md b/README.md index e19dc62c3..983feebbe 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,99 @@ +# sciformats_serde_json + +This is a fork of [Serde JSON](https://github.com/serde-rs/json). + +It provides these additional features: + +- Deserialize elements of a JSON documents to a Span, i.e., only deserialize the byte range. This allows lazy loading parts of a JSON document, e.g., when reading from a file. +- Provide byte offsets as u64. This allows tracking of positions beyond 4 GiB even on 32 bit architectures, e.g., WASM32. + +Limitations: + +- `std` is required. + +This fork has been inspired by draft PR [#1266](https://github.com/serde-rs/json/pull/1266) to the Serde JSON repository. + +## Usage + +```toml +[dependencies] +sciformats_serde_json = "1.0" +``` + +## Example + +```rust +#[derive(Debug, Deserialize, PartialEq)] +struct NestedStructParent { + foo: i32, + nested: Span, + bar: String, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct NestedStruct { + foo: i32, + bar: String, +} + +// Make JSON data available a type that implements the Seek and Read traits. +// In this example a Cursor is used, but in more realistic scenarios +// this could be a std::io::BufReader that reads from a file. +let json = br#"{"foo": 42, "nested": {"foo": 42, "bar": "baz"}, "bar": "baz"}"#; +let json_len = json.len() as u64; +let reader = Cursor::new(json); +let rc_reader = Rc::new(RefCell::new(reader)); +let mut borrow = rc_reader.borrow_mut(); + +// Deserialize JSON data. +let mut de = sciformats_serde_json::Deserializer::from_reader(&mut *borrow); +let value = NestedStructParent::deserialize(&mut de).unwrap(); + +// For the NestedStruct only the range in the JSON data has been captured. +assert_eq!( + NestedStructParent { + foo: 42, + nested: Span { span: 22..47 }, + bar: "baz".to_string(), + }, + value +); +assert_eq!(json_len, de.byte_offset()); + +// Simulate that the scopes for the deserializer and borrow of the reader end. +drop(de); +drop(borrow); + +// Acquire a new borrow for the reader and deserialize the NestedStruct. +let mut borrow = rc_reader.borrow_mut(); +borrow + .seek(std::io::SeekFrom::Start(value.nested.span.start)) + .unwrap(); +let nested_span = (&mut *borrow).take(value.nested.span.end - value.nested.span.start); +let mut nested_de = sciformats_serde_json::Deserializer::from_reader(nested_span); +let nested = NestedStruct::deserialize(&mut nested_de).unwrap(); + +assert_eq!( + NestedStruct { + foo: 42, + bar: "baz".to_string(), + }, + nested +); +``` + +See `tests/span.rs` for more examples. + +## License + +The [Serde JSON](https://github.com/serde-rs/json) license terms also apply to this fork. + +## Original content from Serde JSON follows below + # Serde JSON   [![Build Status]][actions] [![Latest Version]][crates.io] -[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/json/ci.yml?branch=master -[actions]: https://github.com/serde-rs/json/actions?query=branch%3Amaster +[Build Status]: https://img.shields.io/github/actions/workflow/status/devrosch/sciformats_serde_json/ci.yml?branch=master +[actions]: https://github.com/devrosch/sciformats_serde_json/actions?query=branch%3Amaster [Latest Version]: https://img.shields.io/crates/v/serde_json.svg [crates.io]: https://crates.io/crates/serde\_json @@ -59,7 +151,7 @@ each of these representations. ## Operating on untyped JSON values Any valid JSON data can be manipulated in the following recursive enum -representation. This data structure is [`serde_json::Value`][value]. +representation. This data structure is [`sciformats_serde_json::Value`][value]. ```rust enum Value { @@ -72,8 +164,8 @@ enum Value { } ``` -A string of JSON data can be parsed into a `serde_json::Value` by the -[`serde_json::from_str`][from_str] function. There is also +A string of JSON data can be parsed into a `sciformats_serde_json::Value` by the +[`sciformats_serde_json::from_str`][from_str] function. There is also [`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and [`from_reader`][from_reader] for parsing from any `io::Read` like a File or a TCP stream. @@ -85,7 +177,7 @@ TCP stream. ```rust -use serde_json::{Result, Value}; +use sciformats_serde_json::{Result, Value}; fn untyped_example() -> Result<()> { // Some JSON input data as a &str. Maybe this comes from the user. @@ -99,8 +191,8 @@ fn untyped_example() -> Result<()> { ] }"#; - // Parse the string of data into serde_json::Value. - let v: Value = serde_json::from_str(data)?; + // Parse the string of data into sciformats_serde_json::Value. + let v: Value = sciformats_serde_json::from_str(data)?; // Access parts of the data by indexing with square brackets. println!("Please call {} at the number {}", v["name"], v["phones"][0]); @@ -146,7 +238,7 @@ largely automatically. ```rust use serde::{Deserialize, Serialize}; -use serde_json::Result; +use sciformats_serde_json::Result; #[derive(Serialize, Deserialize)] struct Person { @@ -168,9 +260,9 @@ fn typed_example() -> Result<()> { }"#; // Parse the string of data into a Person object. This is exactly the - // same function as the one that produced serde_json::Value above, but + // same function as the one that produced sciformats_serde_json::Value above, but // now we are asking it for a Person as output. - let p: Person = serde_json::from_str(data)?; + let p: Person = sciformats_serde_json::from_str(data)?; // Do things just like with any other Rust data structure. println!("Please call {} at the number {}", p.name, p.phones[0]); @@ -179,7 +271,7 @@ fn typed_example() -> Result<()> { } ``` -This is the same `serde_json::from_str` function as before, but this time we +This is the same `sciformats_serde_json::from_str` function as before, but this time we assign the return value to a variable of type `Person` so Serde will automatically interpret the input data as a `Person` and produce informative error messages if the layout does not conform to what a `Person` is expected to @@ -192,7 +284,7 @@ way. This includes built-in Rust standard library types like `Vec` and Once we have `p` of type `Person`, our IDE and the Rust compiler can help us use it correctly like they do for any other Rust code. The IDE can autocomplete -field names to prevent typos, which was impossible in the `serde_json::Value` +field names to prevent typos, which was impossible in the `sciformats_serde_json::Value` representation. And the Rust compiler can check that when we write `p.phones[0]`, then `p.phones` is guaranteed to be a `Vec` so indexing into it makes sense and produces a `String`. @@ -204,7 +296,7 @@ derive]* page of the Serde site. ## Constructing JSON values -Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +Serde JSON provides a [`json!` macro][macro] to build `sciformats_serde_json::Value` objects with very natural JSON syntax.
@@ -214,10 +306,10 @@ objects with very natural JSON syntax.
```rust -use serde_json::json; +use sciformats_serde_json::json; fn main() { - // The type of `john` is `serde_json::Value` + // The type of `john` is `sciformats_serde_json::Value` let john = json!({ "name": "John Doe", "age": 43, @@ -234,7 +326,7 @@ fn main() { } ``` -The `Value::to_string()` function converts a `serde_json::Value` into a `String` +The `Value::to_string()` function converts a `sciformats_serde_json::Value` into a `String` of JSON text. One neat thing about the `json!` macro is that variables and expressions can be @@ -252,7 +344,7 @@ represented as JSON. let full_name = "John Doe"; let age_last_year = 42; -// The type of `john` is `serde_json::Value` +// The type of `john` is `sciformats_serde_json::Value` let john = json!({ "name": full_name, "age": age_last_year + 1, @@ -270,9 +362,9 @@ text. ## Creating JSON by serializing data structures A data structure can be converted to a JSON string by -[`serde_json::to_string`][to_string]. There is also -[`serde_json::to_vec`][to_vec] which serializes to a `Vec` and -[`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +[`sciformats_serde_json::to_string`][to_string]. There is also +[`sciformats_serde_json::to_vec`][to_vec] which serializes to a `Vec` and +[`sciformats_serde_json::to_writer`][to_writer] which serializes to any `io::Write` such as a File or a TCP stream.
@@ -283,7 +375,7 @@ such as a File or a TCP stream. ```rust use serde::{Deserialize, Serialize}; -use serde_json::Result; +use sciformats_serde_json::Result; #[derive(Serialize, Deserialize)] struct Address { @@ -299,7 +391,7 @@ fn print_an_address() -> Result<()> { }; // Serialize it to a JSON string. - let j = serde_json::to_string(&address)?; + let j = sciformats_serde_json::to_string(&address)?; // Print, write to a file, or send to an HTTP server. println!("{}", j); diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 5fe38b679..a7d209270 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "serde_json-fuzz" +name = "sciformats_serde_json-fuzz" version = "0.0.0" authors = ["David Tolnay "] edition = "2021" @@ -10,7 +10,7 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" -serde_json = { path = ".." } +sciformats_serde_json = { path = ".." } [[bin]] name = "from_slice" diff --git a/fuzz/fuzz_targets/from_slice.rs b/fuzz/fuzz_targets/from_slice.rs index 28bb3ee01..187341080 100644 --- a/fuzz/fuzz_targets/from_slice.rs +++ b/fuzz/fuzz_targets/from_slice.rs @@ -1,7 +1,7 @@ #![no_main] use libfuzzer_sys::fuzz_target; -use serde_json::{from_slice, Value}; +use sciformats_serde_json::{from_slice, Value}; fuzz_target!(|data: &[u8]| { _ = from_slice::(data); diff --git a/src/de.rs b/src/de.rs index 4080c54ac..14e4161f4 100644 --- a/src/de.rs +++ b/src/de.rs @@ -67,6 +67,11 @@ where disable_recursion_limit: false, } } + + /// Returns the current byte offset of the underlying reader. + pub fn byte_offset(&self) -> u64 { + self.read.byte_offset() + } } #[cfg(feature = "std")] @@ -185,7 +190,7 @@ impl<'de, R: Read<'de>> Deserializer { /// /// ``` /// use serde::Deserialize; - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// fn main() { /// let mut json = String::new(); @@ -193,7 +198,7 @@ impl<'de, R: Read<'de>> Deserializer { /// json = format!("[{}]", json); /// } /// - /// let mut deserializer = serde_json::Deserializer::from_str(&json); + /// let mut deserializer = sciformats_serde_json::Deserializer::from_str(&json); /// deserializer.disable_recursion_limit(); /// let deserializer = serde_stacker::Deserializer::new(&mut deserializer); /// let value = Value::deserialize(deserializer).unwrap(); @@ -1597,9 +1602,9 @@ impl<'de, R: Read<'de>> de::Deserializer<'de> for &mut Deserializer { /// ``` /// use serde_bytes::ByteBuf; /// - /// fn look_at_bytes() -> Result<(), serde_json::Error> { + /// fn look_at_bytes() -> Result<(), sciformats_serde_json::Error> { /// let json_data = b"\"some bytes: \xe5\x00\xe5\""; - /// let bytes: ByteBuf = serde_json::from_slice(json_data)?; + /// let bytes: ByteBuf = sciformats_serde_json::from_slice(json_data)?; /// /// assert_eq!(b'\xe5', bytes[12]); /// assert_eq!(b'\0', bytes[13]); @@ -1618,9 +1623,9 @@ impl<'de, R: Read<'de>> de::Deserializer<'de> for &mut Deserializer { /// ``` /// use serde_bytes::ByteBuf; /// - /// fn look_at_bytes() -> Result<(), serde_json::Error> { + /// fn look_at_bytes() -> Result<(), sciformats_serde_json::Error> { /// let json_data = b"\"lone surrogate: \\uD801\""; - /// let bytes: ByteBuf = serde_json::from_slice(json_data)?; + /// let bytes: ByteBuf = sciformats_serde_json::from_slice(json_data)?; /// let expected = b"lone surrogate: \xED\xA0\x81"; /// assert_eq!(expected, bytes.as_slice()); /// Ok(()) @@ -1817,8 +1822,8 @@ impl<'de, R: Read<'de>> de::Deserializer<'de> for &mut Deserializer { fn deserialize_struct( self, - _name: &'static str, - _fields: &'static [&'static str], + name: &'static str, + fields: &'static [&'static str], visitor: V, ) -> Result where @@ -1831,6 +1836,10 @@ impl<'de, R: Read<'de>> de::Deserializer<'de> for &mut Deserializer { } }; + if crate::span::is_span(name, fields) { + return visitor.visit_map(crate::span::SpanDeserializer::new(self)); + } + let value = match peek { b'[' => { check_recursion! { @@ -2334,7 +2343,7 @@ where /// arrays, objects, or strings, or be followed by whitespace or a self-delineating value. /// /// ``` -/// use serde_json::{Deserializer, Value}; +/// use sciformats_serde_json::{Deserializer, Value}; /// /// fn main() { /// let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{} [0, 1, 2]"; @@ -2348,7 +2357,7 @@ where /// ``` pub struct StreamDeserializer<'de, R, T> { de: Deserializer, - offset: usize, + offset: u64, failed: bool, output: PhantomData, lifetime: PhantomData<&'de ()>, @@ -2386,7 +2395,7 @@ where /// ``` /// let data = b"[0] [1] ["; /// - /// let de = serde_json::Deserializer::from_slice(data); + /// let de = sciformats_serde_json::Deserializer::from_slice(data); /// let mut stream = de.into_iter::>(); /// assert_eq!(0, stream.byte_offset()); /// @@ -2400,7 +2409,7 @@ where /// assert_eq!(8, stream.byte_offset()); /// /// // If err.is_eof(), can join the remaining data to new data and continue. - /// let remaining = &data[stream.byte_offset()..]; + /// let remaining = &data[stream.byte_offset() as usize..]; /// ``` /// /// *Note:* In the future this method may be changed to return the number of @@ -2409,7 +2418,7 @@ where /// example illustrating this. /// /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70 - pub fn byte_offset(&self) -> usize { + pub fn byte_offset(&self) -> u64 { self.offset } @@ -2550,7 +2559,7 @@ where /// let reader = BufReader::new(file); /// /// // Read the JSON contents of the file as an instance of `User`. -/// let u = serde_json::from_reader(reader)?; +/// let u = sciformats_serde_json::from_reader(reader)?; /// /// // Return the `User`. /// Ok(u) @@ -2580,7 +2589,7 @@ where /// } /// /// fn read_user_from_stream(stream: &mut BufReader) -> Result> { -/// let mut de = serde_json::Deserializer::from_reader(stream); +/// let mut de = sciformats_serde_json::Deserializer::from_reader(stream); /// let u = User::deserialize(&mut de)?; /// /// Ok(u) @@ -2638,7 +2647,7 @@ where /// \"location\": \"Menlo Park, CA\" /// }"; /// -/// let u: User = serde_json::from_slice(j).unwrap(); +/// let u: User = sciformats_serde_json::from_slice(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` @@ -2680,7 +2689,7 @@ where /// \"location\": \"Menlo Park, CA\" /// }"; /// -/// let u: User = serde_json::from_str(j).unwrap(); +/// let u: User = sciformats_serde_json::from_str(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` diff --git a/src/error.rs b/src/error.rs index b74f4449e..059d25780 100644 --- a/src/error.rs +++ b/src/error.rs @@ -21,7 +21,7 @@ pub struct Error { err: Box, } -/// Alias for a `Result` with the error type `serde_json::Error`. +/// Alias for a `Result` with the error type `sciformats_serde_json::Error`. pub type Result = result::Result; impl Error { @@ -29,7 +29,7 @@ impl Error { /// /// Characters in the first line of the input (before the first newline /// character) are in line 1. - pub fn line(&self) -> usize { + pub fn line(&self) -> u64 { self.err.line } @@ -41,7 +41,7 @@ impl Error { /// Note that errors may occur in column 0, for example if a read from an /// I/O stream fails immediately following a previously read newline /// character. - pub fn column(&self) -> usize { + pub fn column(&self) -> u64 { self.err.column } @@ -117,7 +117,7 @@ impl Error { /// # Example /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// use std::io::{self, ErrorKind, Read}; /// use std::process; /// @@ -136,7 +136,7 @@ impl Error { /// fn main() { /// let reader = ReaderThatWillTimeOut(br#" {"k": "#); /// - /// let _: Value = match serde_json::from_reader(reader) { + /// let _: Value = match sciformats_serde_json::from_reader(reader) { /// Ok(value) => value, /// Err(error) => { /// if error.io_error_kind() == Some(ErrorKind::TimedOut) { @@ -161,7 +161,7 @@ impl Error { } } -/// Categorizes the cause of a `serde_json::Error`. +/// Categorizes the cause of a `sciformats_serde_json::Error`. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Category { /// The error was caused by a failure to read or write bytes on an I/O @@ -187,7 +187,7 @@ pub enum Category { #[cfg(feature = "std")] #[allow(clippy::fallible_impl_from)] impl From for io::Error { - /// Convert a `serde_json::Error` into an `io::Error`. + /// Convert a `sciformats_serde_json::Error` into an `io::Error`. /// /// JSON syntax and data errors are turned into `InvalidData` I/O errors. /// EOF errors are turned into `UnexpectedEof` I/O errors. @@ -197,12 +197,12 @@ impl From for io::Error { /// /// enum MyError { /// Io(io::Error), - /// Json(serde_json::Error), + /// Json(sciformats_serde_json::Error), /// } /// - /// impl From for MyError { - /// fn from(err: serde_json::Error) -> MyError { - /// use serde_json::error::Category; + /// impl From for MyError { + /// fn from(err: sciformats_serde_json::Error) -> MyError { + /// use sciformats_serde_json::error::Category; /// match err.classify() { /// Category::Io => { /// MyError::Io(err.into()) @@ -229,8 +229,8 @@ impl From for io::Error { struct ErrorImpl { code: ErrorCode, - line: usize, - column: usize, + line: u64, + column: u64, } pub(crate) enum ErrorCode { @@ -312,7 +312,7 @@ pub(crate) enum ErrorCode { impl Error { #[cold] - pub(crate) fn syntax(code: ErrorCode, line: usize, column: usize) -> Self { + pub(crate) fn syntax(code: ErrorCode, line: u64, column: u64) -> Self { Error { err: Box::new(ErrorImpl { code, line, column }), } @@ -485,8 +485,8 @@ fn make_error(mut msg: String) -> Error { Error { err: Box::new(ErrorImpl { code: ErrorCode::Message(msg.into_boxed_str()), - line, - column, + line: line as u64, + column: column as u64, }), } } diff --git a/src/iter.rs b/src/iter.rs index 9792916dc..de97684fa 100644 --- a/src/iter.rs +++ b/src/iter.rs @@ -5,18 +5,18 @@ pub struct LineColIterator { /// Index of the current line. Characters in the first line of the input /// (before the first newline character) are in line 1. - line: usize, + line: u64, /// Index of the current column. The first character in the input and any /// characters immediately following a newline character are in column 1. /// The column is 0 immediately after a newline character has been read. - col: usize, + col: u64, /// Byte offset of the start of the current line. This is the sum of lengths /// of all previous lines. Keeping track of things this way allows efficient /// computation of the current line, column, and byte offset while only /// updating one of the counters in `next()` in the common case. - start_of_line: usize, + start_of_line: u64, } impl LineColIterator @@ -32,15 +32,15 @@ where } } - pub fn line(&self) -> usize { + pub fn line(&self) -> u64 { self.line } - pub fn col(&self) -> usize { + pub fn col(&self) -> u64 { self.col } - pub fn byte_offset(&self) -> usize { + pub fn byte_offset(&self) -> u64 { self.start_of_line + self.col } } diff --git a/src/lib.rs b/src/lib.rs index 183a91b30..f90f3c06d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,10 +38,10 @@ //! # Operating on untyped JSON values //! //! Any valid JSON data can be manipulated in the following recursive enum -//! representation. This data structure is [`serde_json::Value`][value]. +//! representation. This data structure is [`sciformats_serde_json::Value`][value]. //! //! ``` -//! # use serde_json::{Number, Map}; +//! # use sciformats_serde_json::{Number, Map}; //! # //! # #[allow(dead_code)] //! enum Value { @@ -54,13 +54,13 @@ //! } //! ``` //! -//! A string of JSON data can be parsed into a `serde_json::Value` by the -//! [`serde_json::from_str`][from_str] function. There is also [`from_slice`] +//! A string of JSON data can be parsed into a `sciformats_serde_json::Value` by the +//! [`sciformats_serde_json::from_str`][from_str] function. There is also [`from_slice`] //! for parsing from a byte slice `&[u8]` and [`from_reader`] for parsing from //! any `io::Read` like a File or a TCP stream. //! //! ``` -//! use serde_json::{Result, Value}; +//! use sciformats_serde_json::{Result, Value}; //! //! fn untyped_example() -> Result<()> { //! // Some JSON input data as a &str. Maybe this comes from the user. @@ -74,8 +74,8 @@ //! ] //! }"#; //! -//! // Parse the string of data into serde_json::Value. -//! let v: Value = serde_json::from_str(data)?; +//! // Parse the string of data into sciformats_serde_json::Value. +//! let v: Value = sciformats_serde_json::from_str(data)?; //! //! // Access parts of the data by indexing with square brackets. //! println!("Please call {} at the number {}", v["name"], v["phones"][0]); @@ -119,7 +119,7 @@ //! //! ``` //! use serde::{Deserialize, Serialize}; -//! use serde_json::Result; +//! use sciformats_serde_json::Result; //! //! #[derive(Serialize, Deserialize)] //! struct Person { @@ -141,9 +141,9 @@ //! }"#; //! //! // Parse the string of data into a Person object. This is exactly the -//! // same function as the one that produced serde_json::Value above, but +//! // same function as the one that produced sciformats_serde_json::Value above, but //! // now we are asking it for a Person as output. -//! let p: Person = serde_json::from_str(data)?; +//! let p: Person = sciformats_serde_json::from_str(data)?; //! //! // Do things just like with any other Rust data structure. //! println!("Please call {} at the number {}", p.name, p.phones[0]); @@ -156,7 +156,7 @@ //! # } //! ``` //! -//! This is the same `serde_json::from_str` function as before, but this time we +//! This is the same `sciformats_serde_json::from_str` function as before, but this time we //! assign the return value to a variable of type `Person` so Serde will //! automatically interpret the input data as a `Person` and produce informative //! error messages if the layout does not conform to what a `Person` is expected @@ -170,20 +170,20 @@ //! Once we have `p` of type `Person`, our IDE and the Rust compiler can help us //! use it correctly like they do for any other Rust code. The IDE can //! autocomplete field names to prevent typos, which was impossible in the -//! `serde_json::Value` representation. And the Rust compiler can check that +//! `sciformats_serde_json::Value` representation. And the Rust compiler can check that //! when we write `p.phones[0]`, then `p.phones` is guaranteed to be a //! `Vec` so indexing into it makes sense and produces a `String`. //! //! # Constructing JSON values //! -//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +//! Serde JSON provides a [`json!` macro][macro] to build `sciformats_serde_json::Value` //! objects with very natural JSON syntax. //! //! ``` -//! use serde_json::json; +//! use sciformats_serde_json::json; //! //! fn main() { -//! // The type of `john` is `serde_json::Value` +//! // The type of `john` is `sciformats_serde_json::Value` //! let john = json!({ //! "name": "John Doe", //! "age": 43, @@ -200,7 +200,7 @@ //! } //! ``` //! -//! The `Value::to_string()` function converts a `serde_json::Value` into a +//! The `Value::to_string()` function converts a `sciformats_serde_json::Value` into a //! `String` of JSON text. //! //! One neat thing about the `json!` macro is that variables and expressions can @@ -209,14 +209,14 @@ //! be represented as JSON. //! //! ``` -//! # use serde_json::json; +//! # use sciformats_serde_json::json; //! # //! # fn random_phone() -> u16 { 0 } //! # //! let full_name = "John Doe"; //! let age_last_year = 42; //! -//! // The type of `john` is `serde_json::Value` +//! // The type of `john` is `sciformats_serde_json::Value` //! let john = json!({ //! "name": full_name, //! "age": age_last_year + 1, @@ -234,14 +234,14 @@ //! # Creating JSON by serializing data structures //! //! A data structure can be converted to a JSON string by -//! [`serde_json::to_string`][to_string]. There is also -//! [`serde_json::to_vec`][to_vec] which serializes to a `Vec` and -//! [`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +//! [`sciformats_serde_json::to_string`][to_string]. There is also +//! [`sciformats_serde_json::to_vec`][to_vec] which serializes to a `Vec` and +//! [`sciformats_serde_json::to_writer`][to_writer] which serializes to any `io::Write` //! such as a File or a TCP stream. //! //! ``` //! use serde::{Deserialize, Serialize}; -//! use serde_json::Result; +//! use sciformats_serde_json::Result; //! //! #[derive(Serialize, Deserialize)] //! struct Address { @@ -257,7 +257,7 @@ //! }; //! //! // Serialize it to a JSON string. -//! let j = serde_json::to_string(&address)?; +//! let j = sciformats_serde_json::to_string(&address)?; //! //! // Print, write to a file, or send to an HTTP server. //! println!("{}", j); @@ -439,3 +439,6 @@ mod read; #[cfg(feature = "raw_value")] mod raw; + +/// Functionality related to JSON value spans. +pub mod span; diff --git a/src/macros.rs b/src/macros.rs index 2955e4a53..5c6ba44b5 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1,7 +1,7 @@ -/// Construct a `serde_json::Value` from a JSON literal. +/// Construct a `sciformats_serde_json::Value` from a JSON literal. /// /// ``` -/// # use serde_json::json; +/// # use sciformats_serde_json::json; /// # /// let value = json!({ /// "code": 200, @@ -24,7 +24,7 @@ /// map with non-string keys, the `json!` macro will panic. /// /// ``` -/// # use serde_json::json; +/// # use sciformats_serde_json::json; /// # /// let code = 200; /// let features = vec!["serde", "json"]; @@ -41,7 +41,7 @@ /// Trailing commas are allowed inside both arrays and objects. /// /// ``` -/// # use serde_json::json; +/// # use sciformats_serde_json::json; /// # /// let value = json!([ /// "notice", diff --git a/src/map.rs b/src/map.rs index f91e70b24..c05bc70f3 100644 --- a/src/map.rs +++ b/src/map.rs @@ -1,4 +1,4 @@ -//! A map of String to serde_json::Value. +//! A map of String to sciformats_serde_json::Value. //! //! By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order` //! feature of serde_json to use [`IndexMap`] instead. @@ -435,7 +435,7 @@ impl Hash for Map { /// map. /// /// ``` -/// # use serde_json::Value; +/// # use sciformats_serde_json::Value; /// # /// # let val = &Value::String("".to_owned()); /// # let _ = @@ -463,10 +463,10 @@ where /// present in the map. /// /// ``` -/// # use serde_json::json; +/// # use sciformats_serde_json::json; /// # -/// # let mut map = serde_json::Map::new(); -/// # map.insert("key".to_owned(), serde_json::Value::Null); +/// # let mut map = sciformats_serde_json::Map::new(); +/// # map.insert("key".to_owned(), sciformats_serde_json::Value::Null); /// # /// map["key"] = json!("value"); /// ``` @@ -653,7 +653,7 @@ impl<'a> Entry<'a> { /// # Examples /// /// ``` - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// assert_eq!(map.entry("serde").key(), &"serde"); /// ``` pub fn key(&self) -> &String { @@ -669,9 +669,9 @@ impl<'a> Entry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.entry("serde").or_insert(json!(12)); /// /// assert_eq!(map["serde"], 12); @@ -690,9 +690,9 @@ impl<'a> Entry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.entry("serde").or_insert_with(|| json!("hoho")); /// /// assert_eq!(map["serde"], "hoho".to_owned()); @@ -713,9 +713,9 @@ impl<'a> Entry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.entry("serde") /// .and_modify(|e| *e = json!("rust")) /// .or_insert(json!("cpp")); @@ -749,9 +749,9 @@ impl<'a> VacantEntry<'a> { /// # Examples /// /// ``` - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// /// match map.entry("serde") { /// Entry::Vacant(vacant) => { @@ -771,11 +771,11 @@ impl<'a> VacantEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// /// match map.entry("serde") { /// Entry::Vacant(vacant) => { @@ -796,11 +796,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!(12)); /// /// match map.entry("serde") { @@ -820,11 +820,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!(12)); /// /// match map.entry("serde") { @@ -844,11 +844,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!([1, 2, 3])); /// /// match map.entry("serde") { @@ -870,11 +870,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!([1, 2, 3])); /// /// match map.entry("serde") { @@ -897,11 +897,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!(12)); /// /// match map.entry("serde") { @@ -928,11 +928,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!(12)); /// /// match map.entry("serde") { @@ -989,11 +989,11 @@ impl<'a> OccupiedEntry<'a> { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # - /// use serde_json::map::Entry; + /// use sciformats_serde_json::map::Entry; /// - /// let mut map = serde_json::Map::new(); + /// let mut map = sciformats_serde_json::Map::new(); /// map.insert("serde".to_owned(), json!(12)); /// /// match map.entry("serde") { @@ -1055,7 +1055,7 @@ impl<'a> IntoIterator for &'a Map { } } -/// An iterator over a serde_json::Map's entries. +/// An iterator over a sciformats_serde_json::Map's entries. #[derive(Clone, Debug)] pub struct Iter<'a> { iter: IterImpl<'a>, @@ -1081,7 +1081,7 @@ impl<'a> IntoIterator for &'a mut Map { } } -/// A mutable iterator over a serde_json::Map's entries. +/// A mutable iterator over a sciformats_serde_json::Map's entries. #[derive(Debug)] pub struct IterMut<'a> { iter: IterMutImpl<'a>, @@ -1107,7 +1107,7 @@ impl IntoIterator for Map { } } -/// An owning iterator over a serde_json::Map's entries. +/// An owning iterator over a sciformats_serde_json::Map's entries. #[derive(Debug)] pub struct IntoIter { iter: IntoIterImpl, @@ -1122,7 +1122,7 @@ delegate_iterator!((IntoIter) => (String, Value)); ////////////////////////////////////////////////////////////////////////////// -/// An iterator over a serde_json::Map's keys. +/// An iterator over a sciformats_serde_json::Map's keys. #[derive(Clone, Debug)] pub struct Keys<'a> { iter: KeysImpl<'a>, @@ -1137,7 +1137,7 @@ delegate_iterator!((Keys<'a>) => &'a String); ////////////////////////////////////////////////////////////////////////////// -/// An iterator over a serde_json::Map's values. +/// An iterator over a sciformats_serde_json::Map's values. #[derive(Clone, Debug)] pub struct Values<'a> { iter: ValuesImpl<'a>, @@ -1152,7 +1152,7 @@ delegate_iterator!((Values<'a>) => &'a Value); ////////////////////////////////////////////////////////////////////////////// -/// A mutable iterator over a serde_json::Map's values. +/// A mutable iterator over a sciformats_serde_json::Map's values. #[derive(Debug)] pub struct ValuesMut<'a> { iter: ValuesMutImpl<'a>, @@ -1167,7 +1167,7 @@ delegate_iterator!((ValuesMut<'a>) => &'a mut Value); ////////////////////////////////////////////////////////////////////////////// -/// An owning iterator over a serde_json::Map's values. +/// An owning iterator over a sciformats_serde_json::Map's values. #[derive(Debug)] pub struct IntoValues { iter: IntoValuesImpl, diff --git a/src/number.rs b/src/number.rs index 51c2d6df7..3e869c91c 100644 --- a/src/number.rs +++ b/src/number.rs @@ -15,7 +15,7 @@ use serde::de::{IntoDeserializer, MapAccess}; use serde::{forward_to_deserialize_any, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "arbitrary_precision")] -pub(crate) const TOKEN: &str = "$serde_json::private::Number"; +pub(crate) const TOKEN: &str = "$sciformats_serde_json::private::Number"; /// Represents a JSON number, whether integer or floating point. #[derive(Clone, PartialEq, Eq, Hash)] @@ -174,7 +174,7 @@ impl Number { /// numbers. /// /// ``` - /// # use serde_json::Number; + /// # use sciformats_serde_json::Number; /// # /// assert!(Number::from_f64(256.0).is_some()); /// @@ -228,7 +228,7 @@ impl Number { /// "arbitrary_precision" feature is enabled. /// /// ``` - /// # use serde_json::Number; + /// # use sciformats_serde_json::Number; /// # /// assert!(Number::from_i128(256).is_some()); /// ``` @@ -257,7 +257,7 @@ impl Number { /// is enabled. /// /// ``` - /// # use serde_json::Number; + /// # use sciformats_serde_json::Number; /// # /// assert!(Number::from_u128(256).is_some()); /// ``` @@ -287,7 +287,7 @@ impl Number { /// number. /// /// ``` - /// # use serde_json::Number; + /// # use sciformats_serde_json::Number; /// for value in [ /// "7", /// "12.34", @@ -296,7 +296,7 @@ impl Number { /// "343412345678910111213141516171819202122232425262728293034", /// "-343412345678910111213141516171819202122232425262728293031", /// ] { - /// let number: Number = serde_json::from_str(value).unwrap(); + /// let number: Number = sciformats_serde_json::from_str(value).unwrap(); /// assert_eq!(number.as_str(), value); /// } /// ``` diff --git a/src/raw.rs b/src/raw.rs index be4dad44d..9ae4de54b 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -36,7 +36,7 @@ use serde::ser::{Serialize, SerializeStruct, Serializer}; /// /// ``` /// use serde::{Deserialize, Serialize}; -/// use serde_json::{Result, value::RawValue}; +/// use sciformats_serde_json::{Result, value::RawValue}; /// /// #[derive(Deserialize)] /// struct Input<'a> { @@ -53,18 +53,18 @@ use serde::ser::{Serialize, SerializeStruct, Serializer}; /// // Efficiently rearrange JSON input containing separate "code" and "payload" /// // keys into a single "info" key holding an array of code and payload. /// // -/// // This could be done equivalently using serde_json::Value as the type for +/// // This could be done equivalently using sciformats_serde_json::Value as the type for /// // payload, but &RawValue will perform better because it does not require /// // memory allocation. The correct range of bytes is borrowed from the input /// // data and pasted verbatim into the output. /// fn rearrange(input: &str) -> Result { -/// let input: Input = serde_json::from_str(input)?; +/// let input: Input = sciformats_serde_json::from_str(input)?; /// /// let output = Output { /// info: (input.code, input.payload), /// }; /// -/// serde_json::to_string(&output) +/// sciformats_serde_json::to_string(&output) /// } /// /// fn main() -> Result<()> { @@ -82,7 +82,7 @@ use serde::ser::{Serialize, SerializeStruct, Serializer}; /// /// ``` /// # use serde::Deserialize; -/// # use serde_json::value::RawValue; +/// # use sciformats_serde_json::value::RawValue; /// # /// #[derive(Deserialize)] /// struct SomeStruct<'a> { @@ -92,20 +92,20 @@ use serde::ser::{Serialize, SerializeStruct, Serializer}; /// ``` /// /// The borrowed form is suitable when deserializing through -/// [`serde_json::from_str`] and [`serde_json::from_slice`] which support +/// [`sciformats_serde_json::from_str`] and [`sciformats_serde_json::from_slice`] which support /// borrowing from the input data without memory allocation. /// -/// When deserializing through [`serde_json::from_reader`] you will need to use +/// When deserializing through [`sciformats_serde_json::from_reader`] you will need to use /// the boxed form of `RawValue` instead. This is almost as efficient but /// involves buffering the raw value from the I/O stream into memory. /// -/// [`serde_json::from_str`]: crate::from_str -/// [`serde_json::from_slice`]: crate::from_slice -/// [`serde_json::from_reader`]: crate::from_reader +/// [`sciformats_serde_json::from_str`]: crate::from_str +/// [`sciformats_serde_json::from_slice`]: crate::from_slice +/// [`sciformats_serde_json::from_reader`]: crate::from_reader /// /// ``` /// # use serde::Deserialize; -/// # use serde_json::value::RawValue; +/// # use sciformats_serde_json::value::RawValue; /// # /// #[derive(Deserialize)] /// struct SomeStruct { @@ -177,7 +177,7 @@ impl RawValue { /// Convert an owned `String` of JSON data to an owned `RawValue`. /// - /// This function is equivalent to `serde_json::from_str::>` + /// This function is equivalent to `sciformats_serde_json::from_str::>` /// except that we avoid an allocation and memcpy if both of the following /// are true: /// @@ -197,7 +197,7 @@ impl RawValue { /// /// ``` /// use serde::Deserialize; - /// use serde_json::{Result, value::RawValue}; + /// use sciformats_serde_json::{Result, value::RawValue}; /// /// #[derive(Deserialize)] /// struct Response<'a> { @@ -207,7 +207,7 @@ impl RawValue { /// } /// /// fn process(input: &str) -> Result<()> { - /// let response: Response = serde_json::from_str(input)?; + /// let response: Response = sciformats_serde_json::from_str(input)?; /// /// let payload = response.payload.get(); /// if payload.starts_with('{') { @@ -250,7 +250,7 @@ impl From> for Box { /// /// // Local crate /// use serde::Serialize; -/// use serde_json::value::{to_raw_value, RawValue}; +/// use sciformats_serde_json::value::{to_raw_value, RawValue}; /// /// #[derive(Serialize)] /// struct MyExtraData { @@ -264,8 +264,8 @@ impl From> for Box { /// extra_data: to_raw_value(&MyExtraData { a: 1, b: 2 }).unwrap(), /// }; /// # assert_eq!( -/// # serde_json::to_value(my_thing).unwrap(), -/// # serde_json::json!({ +/// # sciformats_serde_json::to_value(my_thing).unwrap(), +/// # sciformats_serde_json::json!({ /// # "foo": "FooVal", /// # "bar": null, /// # "extra_data": { "a": 1, "b": 2 } @@ -285,7 +285,7 @@ impl From> for Box { /// let mut map = BTreeMap::new(); /// map.insert(vec![32, 64], "x86"); /// -/// println!("{}", serde_json::value::to_raw_value(&map).unwrap_err()); +/// println!("{}", sciformats_serde_json::value::to_raw_value(&map).unwrap_err()); /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "raw_value")))] pub fn to_raw_value(value: &T) -> Result, Error> @@ -296,7 +296,7 @@ where Ok(RawValue::from_owned(json_string.into_boxed_str())) } -pub const TOKEN: &str = "$serde_json::private::RawValue"; +pub const TOKEN: &str = "$sciformats_serde_json::private::RawValue"; impl Serialize for RawValue { fn serialize(&self, serializer: S) -> Result diff --git a/src/read.rs b/src/read.rs index f90d9f74a..d37be9dbc 100644 --- a/src/read.rs +++ b/src/read.rs @@ -58,7 +58,7 @@ pub trait Read<'de>: private::Sealed { /// Offset from the beginning of the input to the next byte that would be /// returned by next() or peek(). #[doc(hidden)] - fn byte_offset(&self) -> usize; + fn byte_offset(&self) -> u64; /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped /// string until the next quotation mark using the given scratch space if @@ -117,8 +117,8 @@ pub trait Read<'de>: private::Sealed { } pub struct Position { - pub line: usize, - pub column: usize, + pub line: u64, + pub column: u64, } pub enum Reference<'b, 'c, T> @@ -325,7 +325,7 @@ where self.position() } - fn byte_offset(&self) -> usize { + fn byte_offset(&self) -> u64 { match self.ch { Some(_) => self.iter.byte_offset() - 1, None => self.iter.byte_offset(), @@ -424,8 +424,8 @@ impl<'a> SliceRead<'a> { None => 0, }; Position { - line: 1 + memchr::memchr_iter(b'\n', &self.slice[..start_of_line]).count(), - column: i - start_of_line, + line: 1 + memchr::memchr_iter(b'\n', &self.slice[..start_of_line]).count() as u64, + column: i as u64 - start_of_line as u64, } } @@ -580,8 +580,8 @@ impl<'a> Read<'a> for SliceRead<'a> { self.position_of_index(cmp::min(self.slice.len(), self.index + 1)) } - fn byte_offset(&self) -> usize { - self.index + fn byte_offset(&self) -> u64 { + self.index as u64 } fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec) -> Result> { @@ -702,7 +702,7 @@ impl<'a> Read<'a> for StrRead<'a> { self.delegate.peek_position() } - fn byte_offset(&self) -> usize { + fn byte_offset(&self) -> u64 { self.delegate.byte_offset() } @@ -783,7 +783,7 @@ where R::peek_position(self) } - fn byte_offset(&self) -> usize { + fn byte_offset(&self) -> u64 { R::byte_offset(self) } diff --git a/src/span.rs b/src/span.rs new file mode 100644 index 000000000..0516a1068 --- /dev/null +++ b/src/span.rs @@ -0,0 +1,137 @@ +use crate::{read, Value}; +use serde::{ + de::{value::BorrowedStrDeserializer, DeserializeSeed, IntoDeserializer, MapAccess}, + Deserialize, Deserializer, +}; +use std::ops::Range; + +pub(crate) const NAME: &str = "$__sciformats_serde_span_private_name"; +pub(crate) const START_FIELD: &str = "$__sciformats_serde_span_private_start_field"; +pub(crate) const END_FIELD: &str = "$__sciformats_serde_span_private_end_field"; + +/// Check if the given name and fields correspond to a Span. +pub(crate) fn is_span(name: &str, fields: &[&str]) -> bool { + name == NAME && [START_FIELD, END_FIELD] == fields +} + +/// A span representing a range of bytes. +#[derive(Clone, Debug, PartialEq)] +pub struct Span { + /// The range of bytes. + pub span: Range, +} + +impl<'de> Deserialize<'de> for Span { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let visitor = SpanVisitor; + deserializer.deserialize_struct(NAME, &[START_FIELD, END_FIELD], visitor) + } +} + +struct SpanVisitor; + +impl<'de> serde::de::Visitor<'de> for SpanVisitor { + type Value = Span; + + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { + formatter.write_str("a span") + } + + fn visit_map(self, mut access: M) -> Result + where + M: MapAccess<'de>, + { + let mut start: Option = None; + let mut end: Option = None; + + while let Some(key) = tri!(access.next_key()) { + match key { + START_FIELD => { + if start.is_some() { + return Err(serde::de::Error::duplicate_field(START_FIELD)); + } + start = Some(tri!(access.next_value())); + } + END_FIELD => { + if end.is_some() { + return Err(serde::de::Error::duplicate_field(END_FIELD)); + } + end = Some(tri!(access.next_value())); + } + field => { + return Err(serde::de::Error::unknown_field( + field, + &[START_FIELD, END_FIELD], + )); + } + } + } + match (start, end) { + (Some(start), Some(end)) => Ok(Span { span: start..end }), + (None, _) => Err(serde::de::Error::missing_field(START_FIELD)), + (_, None) => Err(serde::de::Error::missing_field(END_FIELD)), + } + } +} + +pub(crate) enum SpanDeserializer<'d, R> { + Start { de: &'d mut crate::Deserializer }, + End { de: &'d mut crate::Deserializer }, + Done, +} + +impl<'d, R> SpanDeserializer<'d, R> { + pub fn new(de: &'d mut crate::Deserializer) -> Self { + Self::Start { de } + } +} + +impl<'d, 'de: 'd, R> MapAccess<'de> for SpanDeserializer<'d, R> +where + R: read::Read<'de>, +{ + type Error = crate::Error; + + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + { + let key = match self { + Self::Start { .. } => START_FIELD, + Self::End { .. } => END_FIELD, + Self::Done => return Ok(None), + }; + + seed.deserialize(BorrowedStrDeserializer::new(key)) + .map(Some) + } + + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>, + { + match self { + // It's not possible extract de in pattern match directly, hence use std::mem::replace. + Self::Start { .. } => { + if let Self::Start { de } = std::mem::replace(self, Self::Done) { + let start = de.byte_offset(); + *self = Self::End { de }; + seed.deserialize(start.into_deserializer()) + } else { + unreachable!() + } + } + Self::End { de } => { + // Read and ignore value. + tri!(Value::deserialize(&mut **de)); + let end = de.byte_offset(); + *self = Self::Done; + seed.deserialize(end.into_deserializer()) + } + Self::Done => panic!("unexpected call to next_value_seed() after Done"), + } + } +} diff --git a/src/value/from.rs b/src/value/from.rs index df4b2038c..dbfe06ea0 100644 --- a/src/value/from.rs +++ b/src/value/from.rs @@ -34,7 +34,7 @@ impl From for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let f: f32 = 13.37; /// let x: Value = f.into(); @@ -51,7 +51,7 @@ impl From for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let f: f64 = 13.37; /// let x: Value = f.into(); @@ -67,7 +67,7 @@ impl From for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let b = false; /// let x: Value = b.into(); @@ -83,7 +83,7 @@ impl From for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let s: String = "lorem".to_owned(); /// let x: Value = s.into(); @@ -99,7 +99,7 @@ impl From<&str> for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let s: &str = "lorem"; /// let x: Value = s.into(); @@ -115,7 +115,7 @@ impl<'a> From> for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// use std::borrow::Cow; /// /// let s: Cow = Cow::Borrowed("lorem"); @@ -123,7 +123,7 @@ impl<'a> From> for Value { /// ``` /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// use std::borrow::Cow; /// /// let s: Cow = Cow::Owned("lorem".to_owned()); @@ -140,7 +140,7 @@ impl From for Value { /// # Examples /// /// ``` - /// use serde_json::{Number, Value}; + /// use sciformats_serde_json::{Number, Value}; /// /// let n = Number::from(7); /// let x: Value = n.into(); @@ -156,7 +156,7 @@ impl From> for Value { /// # Examples /// /// ``` - /// use serde_json::{Map, Value}; + /// use sciformats_serde_json::{Map, Value}; /// /// let mut m = Map::new(); /// m.insert("Lorem".to_owned(), "ipsum".into()); @@ -173,7 +173,7 @@ impl> From> for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let v = vec!["lorem", "ipsum", "dolor"]; /// let x: Value = v.into(); @@ -195,7 +195,7 @@ impl> From<&[T]> for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let v: &[&str] = &["lorem", "ipsum", "dolor"]; /// let x: Value = v.into(); @@ -211,14 +211,14 @@ impl> FromIterator for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let v = std::iter::repeat(42).take(5); /// let x: Value = v.collect(); /// ``` /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; /// let x: Value = v.into_iter().collect(); @@ -226,7 +226,7 @@ impl> FromIterator for Value { /// /// ``` /// use std::iter::FromIterator; - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]); /// ``` @@ -241,7 +241,7 @@ impl, V: Into> FromIterator<(K, V)> for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let v: Vec<_> = vec![("lorem", 40), ("ipsum", 2)]; /// let x: Value = v.into_iter().collect(); @@ -261,7 +261,7 @@ impl From<()> for Value { /// # Examples /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// let u = (); /// let x: Value = u.into(); diff --git a/src/value/index.rs b/src/value/index.rs index 7b0011004..72a796a44 100644 --- a/src/value/index.rs +++ b/src/value/index.rs @@ -5,7 +5,7 @@ use alloc::string::String; use core::fmt::{self, Display}; use core::ops; -/// A type that can be used to index into a `serde_json::Value`. +/// A type that can be used to index into a `sciformats_serde_json::Value`. /// /// The [`get`] and [`get_mut`] methods of `Value` accept any type that /// implements `Index`, as does the [square-bracket indexing operator]. This @@ -22,7 +22,7 @@ use core::ops; /// # Examples /// /// ``` -/// # use serde_json::json; +/// # use sciformats_serde_json::json; /// # /// let data = json!({ "inner": [1, 2, 3] }); /// @@ -181,7 +181,7 @@ where { type Output = Value; - /// Index into a `serde_json::Value` using the syntax `value[0]` or + /// Index into a `sciformats_serde_json::Value` using the syntax `value[0]` or /// `value["k"]`. /// /// Returns `Value::Null` if the type of `self` does not match the type of @@ -195,7 +195,7 @@ where /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let data = json!({ /// "x": { @@ -219,7 +219,7 @@ impl ops::IndexMut for Value where I: Index, { - /// Write into a `serde_json::Value` using the syntax `value[0] = ...` or + /// Write into a `sciformats_serde_json::Value` using the syntax `value[0] = ...` or /// `value["k"] = ...`. /// /// If the index is a number, the value must be an array of length bigger @@ -234,7 +234,7 @@ where /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let mut data = json!({ "x": 0 }); /// diff --git a/src/value/mod.rs b/src/value/mod.rs index 7c562f82d..256e77dcc 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -2,14 +2,14 @@ //! //! # Constructing JSON //! -//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +//! Serde JSON provides a [`json!` macro][macro] to build `sciformats_serde_json::Value` //! objects with very natural JSON syntax. //! //! ``` -//! use serde_json::json; +//! use sciformats_serde_json::json; //! //! fn main() { -//! // The type of `john` is `serde_json::Value` +//! // The type of `john` is `sciformats_serde_json::Value` //! let john = json!({ //! "name": "John Doe", //! "age": 43, @@ -26,7 +26,7 @@ //! } //! ``` //! -//! The `Value::to_string()` function converts a `serde_json::Value` into a +//! The `Value::to_string()` function converts a `sciformats_serde_json::Value` into a //! `String` of JSON text. //! //! One neat thing about the `json!` macro is that variables and expressions can @@ -35,14 +35,14 @@ //! be represented as JSON. //! //! ``` -//! # use serde_json::json; +//! # use sciformats_serde_json::json; //! # //! # fn random_phone() -> u16 { 0 } //! # //! let full_name = "John Doe"; //! let age_last_year = 42; //! -//! // The type of `john` is `serde_json::Value` +//! // The type of `john` is `sciformats_serde_json::Value` //! let john = json!({ //! "name": full_name, //! "age": age_last_year + 1, @@ -52,14 +52,14 @@ //! }); //! ``` //! -//! A string of JSON data can be parsed into a `serde_json::Value` by the -//! [`serde_json::from_str`][from_str] function. There is also +//! A string of JSON data can be parsed into a `sciformats_serde_json::Value` by the +//! [`sciformats_serde_json::from_str`][from_str] function. There is also //! [`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and //! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or //! a TCP stream. //! //! ``` -//! use serde_json::{json, Value, Error}; +//! use sciformats_serde_json::{json, Value, Error}; //! //! fn untyped_example() -> Result<(), Error> { //! // Some JSON input data as a &str. Maybe this comes from the user. @@ -73,8 +73,8 @@ //! ] //! }"#; //! -//! // Parse the string of data into serde_json::Value. -//! let v: Value = serde_json::from_str(data)?; +//! // Parse the string of data into sciformats_serde_json::Value. +//! let v: Value = sciformats_serde_json::from_str(data)?; //! //! // Access parts of the data by indexing with square brackets. //! println!("Please call {} at the number {}", v["name"], v["phones"][0]); @@ -111,13 +111,13 @@ pub use crate::raw::{to_raw_value, RawValue}; /// Represents any valid JSON value. /// -/// See the [`serde_json::value` module documentation](self) for usage examples. +/// See the [`sciformats_serde_json::value` module documentation](self) for usage examples. #[derive(Clone, Eq, PartialEq, Hash)] pub enum Value { /// Represents a JSON null value. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!(null); /// ``` @@ -126,7 +126,7 @@ pub enum Value { /// Represents a JSON boolean. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!(true); /// ``` @@ -135,7 +135,7 @@ pub enum Value { /// Represents a JSON number, whether integer or floating point. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!(12.5); /// ``` @@ -144,7 +144,7 @@ pub enum Value { /// Represents a JSON string. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!("a string"); /// ``` @@ -153,7 +153,7 @@ pub enum Value { /// Represents a JSON array. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!(["an", "array"]); /// ``` @@ -168,7 +168,7 @@ pub enum Value { /// string while retaining the order of map keys in the input. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "an": "object" }); /// ``` @@ -198,7 +198,7 @@ impl Display for Value { /// Display a JSON value as a string. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let json = json!({ "city": "London", "street": "10 Downing Street" }); /// @@ -274,7 +274,7 @@ impl Value { /// or the given index is not within the bounds of the array. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let object = json!({ "A": 65, "B": 66, "C": 67 }); /// assert_eq!(*object.get("A").unwrap(), json!(65)); @@ -290,7 +290,7 @@ impl Value { /// `None`. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let object = json!({ /// "A": ["a", "á", "à"], @@ -316,7 +316,7 @@ impl Value { /// or the given index is not within the bounds of the array. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let mut object = json!({ "A": 65, "B": 66, "C": 67 }); /// *object.get_mut("A").unwrap() = json!(69); @@ -335,7 +335,7 @@ impl Value { /// object. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] }); /// @@ -353,7 +353,7 @@ impl Value { /// otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] }); /// @@ -374,7 +374,7 @@ impl Value { /// Returns None otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let mut v = json!({ "a": { "nested": true } }); /// @@ -395,7 +395,7 @@ impl Value { /// array. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } }); /// @@ -412,7 +412,7 @@ impl Value { /// otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } }); /// @@ -433,7 +433,7 @@ impl Value { /// Returns None otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let mut v = json!({ "a": ["an", "array"] }); /// @@ -453,7 +453,7 @@ impl Value { /// to return the string slice. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": "some string", "b": false }); /// @@ -470,7 +470,7 @@ impl Value { /// otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": "some string", "b": false }); /// @@ -499,7 +499,7 @@ impl Value { /// Returns true if the `Value` is a Number. Returns false otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": 1, "b": "2" }); /// @@ -519,7 +519,7 @@ impl Value { /// None otherwise. /// /// ``` - /// # use serde_json::{json, Number}; + /// # use sciformats_serde_json::{json, Number}; /// # /// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" }); /// @@ -544,7 +544,7 @@ impl Value { /// return the integer value. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let big = i64::max_value() as u64 + 10; /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); @@ -570,7 +570,7 @@ impl Value { /// return the integer value. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); /// @@ -598,7 +598,7 @@ impl Value { /// `is_u64` return false but this is not a guarantee in the future. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); /// @@ -619,7 +619,7 @@ impl Value { /// None otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let big = i64::max_value() as u64 + 10; /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); @@ -639,7 +639,7 @@ impl Value { /// None otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); /// @@ -658,7 +658,7 @@ impl Value { /// None otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); /// @@ -679,7 +679,7 @@ impl Value { /// guaranteed to return the boolean value. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": false, "b": "false" }); /// @@ -696,7 +696,7 @@ impl Value { /// otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": false, "b": "false" }); /// @@ -718,7 +718,7 @@ impl Value { /// to return `Some(())`. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": null, "b": false }); /// @@ -734,7 +734,7 @@ impl Value { /// If the `Value` is a Null, returns (). Returns None otherwise. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let v = json!({ "a": null, "b": false }); /// @@ -765,7 +765,7 @@ impl Value { /// # Examples /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let data = json!({ /// "x": { @@ -810,11 +810,11 @@ impl Value { /// # Example of Use /// /// ``` - /// use serde_json::Value; + /// use sciformats_serde_json::Value; /// /// fn main() { /// let s = r#"{"x": 1.0, "y": 2.0}"#; - /// let mut value: Value = serde_json::from_str(s).unwrap(); + /// let mut value: Value = sciformats_serde_json::from_str(s).unwrap(); /// /// // Check value using read-only pointer /// assert_eq!(value.pointer("/x"), Some(&1.0.into())); @@ -852,7 +852,7 @@ impl Value { /// Takes the value out of the `Value`, leaving a `Null` in its place. /// /// ``` - /// # use serde_json::json; + /// # use sciformats_serde_json::json; /// # /// let mut v = json!({ "x": "y" }); /// assert_eq!(v["x"].take(), json!("y")); @@ -897,7 +897,7 @@ impl Value { /// /// ``` /// # use serde::Deserialize; -/// use serde_json::Value; +/// use sciformats_serde_json::Value; /// /// #[derive(Deserialize)] /// struct Settings { @@ -906,9 +906,9 @@ impl Value { /// extras: Value, /// } /// -/// # fn try_main() -> Result<(), serde_json::Error> { +/// # fn try_main() -> Result<(), sciformats_serde_json::Error> { /// let data = r#" { "level": 42 } "#; -/// let s: Settings = serde_json::from_str(data)?; +/// let s: Settings = sciformats_serde_json::from_str(data)?; /// /// assert_eq!(s.level, 42); /// assert_eq!(s.extras, Value::Null); @@ -937,14 +937,14 @@ mod index; mod partial_eq; mod ser; -/// Convert a `T` into `serde_json::Value` which is an enum that can represent +/// Convert a `T` into `sciformats_serde_json::Value` which is an enum that can represent /// any valid JSON data. /// /// # Example /// /// ``` /// use serde::Serialize; -/// use serde_json::json; +/// use sciformats_serde_json::json; /// use std::error::Error; /// /// #[derive(Serialize)] @@ -959,13 +959,13 @@ mod ser; /// location: "Menlo Park, CA".to_owned(), /// }; /// -/// // The type of `expected` is `serde_json::Value` +/// // The type of `expected` is `sciformats_serde_json::Value` /// let expected = json!({ /// "fingerprint": "0xF9BA143B95FF6D82", /// "location": "Menlo Park, CA", /// }); /// -/// let v = serde_json::to_value(u).unwrap(); +/// let v = sciformats_serde_json::to_value(u).unwrap(); /// assert_eq!(v, expected); /// /// Ok(()) @@ -987,7 +987,7 @@ mod ser; /// let mut map = BTreeMap::new(); /// map.insert(vec![32, 64], "x86"); /// -/// println!("{}", serde_json::to_value(map).unwrap_err()); +/// println!("{}", sciformats_serde_json::to_value(map).unwrap_err()); /// } /// ``` // Taking by value is more friendly to iterator adapters, option and result @@ -999,13 +999,13 @@ where value.serialize(Serializer) } -/// Interpret a `serde_json::Value` as an instance of type `T`. +/// Interpret a `sciformats_serde_json::Value` as an instance of type `T`. /// /// # Example /// /// ``` /// use serde::Deserialize; -/// use serde_json::json; +/// use sciformats_serde_json::json; /// /// #[derive(Deserialize, Debug)] /// struct User { @@ -1014,13 +1014,13 @@ where /// } /// /// fn main() { -/// // The type of `j` is `serde_json::Value` +/// // The type of `j` is `sciformats_serde_json::Value` /// let j = json!({ /// "fingerprint": "0xF9BA143B95FF6D82", /// "location": "Menlo Park, CA" /// }); /// -/// let u: User = serde_json::from_value(j).unwrap(); +/// let u: User = sciformats_serde_json::from_value(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` diff --git a/src/value/ser.rs b/src/value/ser.rs index d5e2e84f6..68353d726 100644 --- a/src/value/ser.rs +++ b/src/value/ser.rs @@ -37,22 +37,22 @@ impl Serialize for Value { /// Serializer whose output is a `Value`. /// -/// This is the serializer that backs [`serde_json::to_value`][crate::to_value]. +/// This is the serializer that backs [`sciformats_serde_json::to_value`][crate::to_value]. /// Unlike the main serde_json serializer which goes from some serializable /// value of type `T` to JSON text, this one goes from `T` to -/// `serde_json::Value`. +/// `sciformats_serde_json::Value`. /// /// The `to_value` function is implementable as: /// /// ``` /// use serde::Serialize; -/// use serde_json::{Error, Value}; +/// use sciformats_serde_json::{Error, Value}; /// /// pub fn to_value(input: T) -> Result /// where /// T: Serialize, /// { -/// input.serialize(serde_json::value::Serializer) +/// input.serialize(sciformats_serde_json::value::Serializer) /// } /// ``` pub struct Serializer; diff --git a/tests/crate/Cargo.toml b/tests/crate/Cargo.toml index e13df6a8e..60626e56e 100644 --- a/tests/crate/Cargo.toml +++ b/tests/crate/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "serde_json_test" +name = "sciformats_serde_json_test" version = "0.0.0" authors = ["David Tolnay "] edition = "2021" @@ -9,14 +9,14 @@ publish = false path = "test.rs" [dependencies] -serde_json = { path = "../..", default-features = false } +sciformats_serde_json = { path = "../..", default-features = false } [features] default = ["std"] -std = ["serde_json/std"] -alloc = ["serde_json/alloc"] -#preserve_order = ["serde_json/preserve_order"] -float_roundtrip = ["serde_json/float_roundtrip"] -arbitrary_precision = ["serde_json/arbitrary_precision"] -raw_value = ["serde_json/raw_value"] -unbounded_depth = ["serde_json/unbounded_depth"] +std = ["sciformats_serde_json/std"] +alloc = ["sciformats_serde_json/alloc"] +#preserve_order = ["sciformats_serde_json/preserve_order"] +float_roundtrip = ["sciformats_serde_json/float_roundtrip"] +arbitrary_precision = ["sciformats_serde_json/arbitrary_precision"] +raw_value = ["sciformats_serde_json/raw_value"] +unbounded_depth = ["sciformats_serde_json/unbounded_depth"] diff --git a/tests/crate/test.rs b/tests/crate/test.rs index 83f18a42d..37f60dfdf 100644 --- a/tests/crate/test.rs +++ b/tests/crate/test.rs @@ -1,3 +1,3 @@ #![no_std] -pub use serde_json::*; +pub use sciformats_serde_json::*; diff --git a/tests/debug.rs b/tests/debug.rs index b804d8d57..0fcef9ec0 100644 --- a/tests/debug.rs +++ b/tests/debug.rs @@ -1,7 +1,7 @@ #![allow(clippy::uninlined_format_args)] use indoc::indoc; -use serde_json::{json, Number, Value}; +use sciformats_serde_json::{json, Number, Value}; #[test] fn number() { @@ -50,7 +50,7 @@ fn value_object() { #[test] fn error() { - let err = serde_json::from_str::("{0}").unwrap_err(); + let err = sciformats_serde_json::from_str::("{0}").unwrap_err(); let expected = "Error(\"key must be a string\", line: 1, column: 2)"; assert_eq!(format!("{:?}", err), expected); } diff --git a/tests/map.rs b/tests/map.rs index aa3cb2549..4fc76a3e2 100644 --- a/tests/map.rs +++ b/tests/map.rs @@ -1,4 +1,4 @@ -use serde_json::{from_str, Map, Value}; +use sciformats_serde_json::{from_str, Map, Value}; #[test] fn test_preserve_order() { diff --git a/tests/regression/issue1004.rs b/tests/regression/issue1004.rs index c09fb9610..8a08ee151 100644 --- a/tests/regression/issue1004.rs +++ b/tests/regression/issue1004.rs @@ -3,8 +3,8 @@ #[test] fn test() { let float = 5.55f32; - let value = serde_json::to_value(float).unwrap(); - let json = serde_json::to_string(&value).unwrap(); + let value = sciformats_serde_json::to_value(float).unwrap(); + let json = sciformats_serde_json::to_string(&value).unwrap(); // If the f32 were cast to f64 by Value before serialization, then this // would incorrectly serialize as 5.550000190734863. diff --git a/tests/regression/issue520.rs b/tests/regression/issue520.rs index 730ecc60a..288453a06 100644 --- a/tests/regression/issue520.rs +++ b/tests/regression/issue520.rs @@ -11,8 +11,8 @@ enum E { #[test] fn test() { let e = E::Float(159.1); - let v = serde_json::to_value(e).unwrap(); - let e = serde_json::from_value::(v).unwrap(); + let v = sciformats_serde_json::to_value(e).unwrap(); + let e = sciformats_serde_json::from_value::(v).unwrap(); match e { E::Float(f) => assert_eq!(f, 159.1), diff --git a/tests/regression/issue795.rs b/tests/regression/issue795.rs index 411e8af5d..0dbe99396 100644 --- a/tests/regression/issue795.rs +++ b/tests/regression/issue795.rs @@ -1,9 +1,9 @@ #![allow(clippy::assertions_on_result_states)] +use sciformats_serde_json::json; use serde::de::{ Deserialize, Deserializer, EnumAccess, IgnoredAny, MapAccess, VariantAccess, Visitor, }; -use serde_json::json; use std::fmt; #[derive(Debug)] @@ -55,8 +55,8 @@ impl<'de> Deserialize<'de> for Enum { #[test] fn test() { let s = r#" {"Variant":{"x":0,"y":0}} "#; - assert!(serde_json::from_str::(s).is_err()); + assert!(sciformats_serde_json::from_str::(s).is_err()); let j = json!({"Variant":{"x":0,"y":0}}); - assert!(serde_json::from_value::(j).is_err()); + assert!(sciformats_serde_json::from_value::(j).is_err()); } diff --git a/tests/regression/issue845.rs b/tests/regression/issue845.rs index 7b6564dad..65a079aa7 100644 --- a/tests/regression/issue845.rs +++ b/tests/regression/issue845.rs @@ -67,8 +67,14 @@ pub struct Struct { #[test] fn test() { let j = r#" {"i":100} "#; - println!("{:?}", serde_json::from_str::(j).unwrap()); + println!( + "{:?}", + sciformats_serde_json::from_str::(j).unwrap() + ); let j = r#" {"i":"100"} "#; - println!("{:?}", serde_json::from_str::(j).unwrap()); + println!( + "{:?}", + sciformats_serde_json::from_str::(j).unwrap() + ); } diff --git a/tests/regression/issue953.rs b/tests/regression/issue953.rs index 771aa5287..c04c09f1f 100644 --- a/tests/regression/issue953.rs +++ b/tests/regression/issue953.rs @@ -1,9 +1,9 @@ -use serde_json::Value; +use sciformats_serde_json::Value; #[test] fn test() { - let x1 = serde_json::from_str::("18446744073709551615."); + let x1 = sciformats_serde_json::from_str::("18446744073709551615."); assert!(x1.is_err()); - let x2 = serde_json::from_str::("18446744073709551616."); + let x2 = sciformats_serde_json::from_str::("18446744073709551616."); assert!(x2.is_err()); } diff --git a/tests/span.rs b/tests/span.rs new file mode 100644 index 000000000..ae335d393 --- /dev/null +++ b/tests/span.rs @@ -0,0 +1,153 @@ +use sciformats_serde_json::span::Span; +use serde::Deserialize; +use std::{ + cell::RefCell, + io::{Cursor, Read, Seek}, + rc::Rc, +}; + +#[derive(Debug, Deserialize, PartialEq)] +struct SimpleStruct { + foo: i32, + bar: String, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct NestedStructParent { + foo: i32, + nested: Span, + bar: String, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct NestedSeqParent { + foo: i32, + nested: Span, + bar: String, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct NestedStruct { + foo: i32, + bar: String, +} + +#[test] +fn test_deserialize_no_span_simple_struct() { + let json = br#"{"foo": 42, "bar": "baz"}"#; + let cursor = Cursor::new(json); + let rc_cursor = Rc::new(RefCell::new(cursor)); + let mut borrow = rc_cursor.borrow_mut(); + + let mut de = sciformats_serde_json::Deserializer::from_reader(&mut *borrow); + let value = SimpleStruct::deserialize(&mut de).unwrap(); + + assert_eq!( + value, + SimpleStruct { + foo: 42, + bar: "baz".to_string() + } + ); +} + +#[test] +fn deserialize_top_level_span_struct() { + let json = br#"{"foo": 42, "bar": "baz"}"#; + let json_len = json.len() as u64; + let cursor = Cursor::new(json); + let rc_cursor = Rc::new(RefCell::new(cursor)); + let mut borrow = rc_cursor.borrow_mut(); + + let mut de = sciformats_serde_json::Deserializer::from_reader(&mut *borrow); + let value = Span::deserialize(&mut de).unwrap(); + + assert_eq!(Span { span: 0..json_len }, value); + assert_eq!(json_len, de.byte_offset()); +} + +#[test] +fn deserialize_nested_span_struct() { + let json = br#"{"foo": 42, "nested": {"foo": 42, "bar": "baz"}, "bar": "baz"}"#; + let json_len = json.len() as u64; + let cursor = Cursor::new(json); + let rc_cursor = Rc::new(RefCell::new(cursor)); + let mut borrow = rc_cursor.borrow_mut(); + let mut de = sciformats_serde_json::Deserializer::from_reader(&mut *borrow); + let value = NestedStructParent::deserialize(&mut de).unwrap(); + + assert_eq!( + NestedStructParent { + foo: 42, + nested: Span { span: 22..47 }, + bar: "baz".to_string(), + }, + value + ); + assert_eq!(json_len, de.byte_offset()); + + drop(de); + drop(borrow); + + let mut borrow = rc_cursor.borrow_mut(); + borrow + .seek(std::io::SeekFrom::Start(value.nested.span.start)) + .unwrap(); + let nested_span = (&mut *borrow).take(value.nested.span.end - value.nested.span.start); + let mut nested_de = sciformats_serde_json::Deserializer::from_reader(nested_span); + let nested = NestedStruct::deserialize(&mut nested_de).unwrap(); + + assert_eq!( + NestedStruct { + foo: 42, + bar: "baz".to_string(), + }, + nested + ); +} + +#[test] +fn deserialize_nested_span_seq() { + let json = br#"{"foo": 42, "nested": [{"foo": 42, "bar": "baz"}, {"foo": 43, "bar": "bazz"}], "bar": "baz"}"#; + let json_len = json.len() as u64; + let cursor = Cursor::new(json); + let rc_cursor = Rc::new(RefCell::new(cursor)); + let mut borrow = rc_cursor.borrow_mut(); + let mut de = sciformats_serde_json::Deserializer::from_reader(&mut *borrow); + let value = NestedSeqParent::deserialize(&mut de).unwrap(); + + assert_eq!( + NestedSeqParent { + foo: 42, + nested: Span { span: 22..77 }, + bar: "baz".to_string(), + }, + value + ); + assert_eq!(json_len, de.byte_offset()); + + drop(de); + drop(borrow); + + let mut borrow = rc_cursor.borrow_mut(); + borrow + .seek(std::io::SeekFrom::Start(value.nested.span.start)) + .unwrap(); + let nested_span = (&mut *borrow).take(value.nested.span.end - value.nested.span.start); + let mut nested_de = sciformats_serde_json::Deserializer::from_reader(nested_span); + let nested = Vec::::deserialize(&mut nested_de).unwrap(); + + assert_eq!( + vec![ + NestedStruct { + foo: 42, + bar: "baz".to_string(), + }, + NestedStruct { + foo: 43, + bar: "bazz".to_string(), + } + ], + nested + ); +} diff --git a/tests/stream.rs b/tests/stream.rs index fa52cedeb..fd8f277b9 100644 --- a/tests/stream.rs +++ b/tests/stream.rs @@ -1,6 +1,6 @@ #![allow(clippy::assertions_on_result_states)] -use serde_json::{json, Deserializer, Value}; +use sciformats_serde_json::{json, Deserializer, Value}; // Rustfmt issue https://github.com/rust-lang-nursery/rustfmt/issues/2740 #[rustfmt::skip] diff --git a/tests/test.rs b/tests/test.rs index f371f6f58..7942320fc 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -23,16 +23,16 @@ mod macros; #[cfg(feature = "raw_value")] use ref_cast::RefCast; -use serde::de::{self, IgnoredAny, IntoDeserializer}; -use serde::ser::{self, SerializeMap, SerializeSeq, Serializer}; -use serde::{Deserialize, Serialize}; -use serde_bytes::{ByteBuf, Bytes}; #[cfg(feature = "raw_value")] -use serde_json::value::RawValue; -use serde_json::{ +use sciformats_serde_json::value::RawValue; +use sciformats_serde_json::{ from_reader, from_slice, from_str, from_value, json, to_string, to_string_pretty, to_value, to_vec, Deserializer, Number, Value, }; +use serde::de::{self, IgnoredAny, IntoDeserializer}; +use serde::ser::{self, SerializeMap, SerializeSeq, Serializer}; +use serde::{Deserialize, Serialize}; +use serde_bytes::{ByteBuf, Bytes}; use std::collections::BTreeMap; #[cfg(feature = "raw_value")] use std::collections::HashMap; @@ -945,7 +945,7 @@ fn test_parse_f64() { #[test] fn test_value_as_f64() { - let v = serde_json::from_str::("1e1000"); + let v = sciformats_serde_json::from_str::("1e1000"); #[cfg(not(feature = "arbitrary_precision"))] assert!(v.is_err()); @@ -974,8 +974,8 @@ fn test_roundtrip_f64() { -1.6727517818542075e58, 3.9287532173373315e299, ] { - let json = serde_json::to_string(&float).unwrap(); - let output: f64 = serde_json::from_str(&json).unwrap(); + let json = sciformats_serde_json::to_string(&float).unwrap(); + let output: f64 = sciformats_serde_json::from_str(&json).unwrap(); assert_eq!(float, output); } } @@ -985,8 +985,8 @@ fn test_roundtrip_f32() { // This number has 1 ULP error if parsed via f64 and converted to f32. // https://github.com/serde-rs/json/pull/671#issuecomment-628534468 let float = 7.038531e-26; - let json = serde_json::to_string(&float).unwrap(); - let output: f32 = serde_json::from_str(&json).unwrap(); + let json = sciformats_serde_json::to_string(&float).unwrap(); + let output: f32 = sciformats_serde_json::from_str(&json).unwrap(); assert_eq!(float, output); } @@ -1006,13 +1006,13 @@ fn test_serialize_char() { #[test] fn test_malicious_number() { #[derive(Serialize)] - #[serde(rename = "$serde_json::private::Number")] + #[serde(rename = "$sciformats_serde_json::private::Number")] struct S { - #[serde(rename = "$serde_json::private::Number")] + #[serde(rename = "$sciformats_serde_json::private::Number")] f: &'static str, } - let actual = serde_json::to_value(&S { f: "not a number" }) + let actual = sciformats_serde_json::to_value(&S { f: "not a number" }) .unwrap_err() .to_string(); assert_eq!(actual, "invalid number at line 1 column 1"); @@ -1626,7 +1626,7 @@ fn test_serialize_map_with_no_len() { #[cfg(not(miri))] #[test] fn test_deserialize_from_stream() { - use serde_json::to_writer; + use sciformats_serde_json::to_writer; use std::net::{TcpListener, TcpStream}; use std::thread; @@ -1769,7 +1769,7 @@ fn test_byte_buf_de_surrogate_pair() { #[cfg(feature = "raw_value")] #[test] fn test_raw_de_invalid_surrogates() { - use serde_json::value::RawValue; + use sciformats_serde_json::value::RawValue; assert!(from_str::>(r#""\ud83c""#).is_ok()); assert!(from_str::>(r#""\ud83c\n""#).is_ok()); @@ -1786,7 +1786,7 @@ fn test_raw_de_invalid_surrogates() { #[cfg(feature = "raw_value")] #[test] fn test_raw_de_surrogate_pair() { - use serde_json::value::RawValue; + use sciformats_serde_json::value::RawValue; assert!(from_str::>(r#""\ud83c\udc00""#).is_ok()); } @@ -2018,16 +2018,16 @@ fn test_deny_non_finite_f32_key() { } let map = treemap!(F32Bits(f32::INFINITY.to_bits()) => "x".to_owned()); - assert!(serde_json::to_string(&map).is_err()); - assert!(serde_json::to_value(map).is_err()); + assert!(sciformats_serde_json::to_string(&map).is_err()); + assert!(sciformats_serde_json::to_value(map).is_err()); let map = treemap!(F32Bits(f32::NEG_INFINITY.to_bits()) => "x".to_owned()); - assert!(serde_json::to_string(&map).is_err()); - assert!(serde_json::to_value(map).is_err()); + assert!(sciformats_serde_json::to_string(&map).is_err()); + assert!(sciformats_serde_json::to_value(map).is_err()); let map = treemap!(F32Bits(f32::NAN.to_bits()) => "x".to_owned()); - assert!(serde_json::to_string(&map).is_err()); - assert!(serde_json::to_value(map).is_err()); + assert!(sciformats_serde_json::to_string(&map).is_err()); + assert!(sciformats_serde_json::to_value(map).is_err()); } #[test] @@ -2047,16 +2047,16 @@ fn test_deny_non_finite_f64_key() { } let map = treemap!(F64Bits(f64::INFINITY.to_bits()) => "x".to_owned()); - assert!(serde_json::to_string(&map).is_err()); - assert!(serde_json::to_value(map).is_err()); + assert!(sciformats_serde_json::to_string(&map).is_err()); + assert!(sciformats_serde_json::to_value(map).is_err()); let map = treemap!(F64Bits(f64::NEG_INFINITY.to_bits()) => "x".to_owned()); - assert!(serde_json::to_string(&map).is_err()); - assert!(serde_json::to_value(map).is_err()); + assert!(sciformats_serde_json::to_string(&map).is_err()); + assert!(sciformats_serde_json::to_value(map).is_err()); let map = treemap!(F64Bits(f64::NAN.to_bits()) => "x".to_owned()); - assert!(serde_json::to_string(&map).is_err()); - assert!(serde_json::to_value(map).is_err()); + assert!(sciformats_serde_json::to_string(&map).is_err()); + assert!(sciformats_serde_json::to_value(map).is_err()); } #[test] @@ -2266,7 +2266,7 @@ fn test_borrow() { #[test] fn null_invalid_type() { - let err = serde_json::from_str::("null").unwrap_err(); + let err = sciformats_serde_json::from_str::("null").unwrap_err(); assert_eq!( format!("{}", err), String::from("invalid type: null, expected a string at line 1 column 4") @@ -2343,23 +2343,23 @@ fn test_borrowed_raw_value() { } let wrapper_from_str: Wrapper = - serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap(); + sciformats_serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap(); assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.get()); - let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap(); + let wrapper_to_string = sciformats_serde_json::to_string(&wrapper_from_str).unwrap(); assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string); - let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap(); + let wrapper_to_value = sciformats_serde_json::to_value(&wrapper_from_str).unwrap(); assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value); let array_from_str: Vec<&RawValue> = - serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap(); + sciformats_serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap(); assert_eq!(r#""a""#, array_from_str[0].get()); assert_eq!("42", array_from_str[1].get()); assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get()); assert_eq!("null", array_from_str[3].get()); - let array_to_string = serde_json::to_string(&array_from_str).unwrap(); + let array_to_string = sciformats_serde_json::to_string(&array_from_str).unwrap(); assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string); } @@ -2397,7 +2397,7 @@ fn test_raw_value_in_map_key() { } let map_from_str: HashMap<&RawMapKey, &RawValue> = - serde_json::from_str(r#" {"\\k":"\\v"} "#).unwrap(); + sciformats_serde_json::from_str(r#" {"\\k":"\\v"} "#).unwrap(); let (map_k, map_v) = map_from_str.into_iter().next().unwrap(); assert_eq!("\"\\\\k\"", map_k.0.get()); assert_eq!("\"\\\\v\"", map_v.get()); @@ -2414,38 +2414,40 @@ fn test_boxed_raw_value() { } let wrapper_from_str: Wrapper = - serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap(); + sciformats_serde_json::from_str(r#"{"a": 1, "b": {"foo": 2}, "c": 3}"#).unwrap(); assert_eq!(r#"{"foo": 2}"#, wrapper_from_str.b.get()); let wrapper_from_reader: Wrapper = - serde_json::from_reader(br#"{"a": 1, "b": {"foo": 2}, "c": 3}"#.as_ref()).unwrap(); + sciformats_serde_json::from_reader(br#"{"a": 1, "b": {"foo": 2}, "c": 3}"#.as_ref()) + .unwrap(); assert_eq!(r#"{"foo": 2}"#, wrapper_from_reader.b.get()); let wrapper_from_value: Wrapper = - serde_json::from_value(json!({"a": 1, "b": {"foo": 2}, "c": 3})).unwrap(); + sciformats_serde_json::from_value(json!({"a": 1, "b": {"foo": 2}, "c": 3})).unwrap(); assert_eq!(r#"{"foo":2}"#, wrapper_from_value.b.get()); - let wrapper_to_string = serde_json::to_string(&wrapper_from_str).unwrap(); + let wrapper_to_string = sciformats_serde_json::to_string(&wrapper_from_str).unwrap(); assert_eq!(r#"{"a":1,"b":{"foo": 2},"c":3}"#, wrapper_to_string); - let wrapper_to_value = serde_json::to_value(&wrapper_from_str).unwrap(); + let wrapper_to_value = sciformats_serde_json::to_value(&wrapper_from_str).unwrap(); assert_eq!(json!({"a": 1, "b": {"foo": 2}, "c": 3}), wrapper_to_value); let array_from_str: Vec> = - serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap(); + sciformats_serde_json::from_str(r#"["a", 42, {"foo": "bar"}, null]"#).unwrap(); assert_eq!(r#""a""#, array_from_str[0].get()); assert_eq!("42", array_from_str[1].get()); assert_eq!(r#"{"foo": "bar"}"#, array_from_str[2].get()); assert_eq!("null", array_from_str[3].get()); let array_from_reader: Vec> = - serde_json::from_reader(br#"["a", 42, {"foo": "bar"}, null]"#.as_ref()).unwrap(); + sciformats_serde_json::from_reader(br#"["a", 42, {"foo": "bar"}, null]"#.as_ref()) + .unwrap(); assert_eq!(r#""a""#, array_from_reader[0].get()); assert_eq!("42", array_from_reader[1].get()); assert_eq!(r#"{"foo": "bar"}"#, array_from_reader[2].get()); assert_eq!("null", array_from_reader[3].get()); - let array_to_string = serde_json::to_string(&array_from_str).unwrap(); + let array_to_string = sciformats_serde_json::to_string(&array_from_str).unwrap(); assert_eq!(r#"["a",42,{"foo": "bar"},null]"#, array_to_string); } @@ -2453,8 +2455,8 @@ fn test_boxed_raw_value() { #[test] fn test_raw_invalid_utf8() { let j = &[b'"', b'\xCE', b'\xF8', b'"']; - let value_err = serde_json::from_slice::(j).unwrap_err(); - let raw_value_err = serde_json::from_slice::>(j).unwrap_err(); + let value_err = sciformats_serde_json::from_slice::(j).unwrap_err(); + let raw_value_err = sciformats_serde_json::from_slice::>(j).unwrap_err(); assert_eq!( value_err.to_string(), @@ -2470,7 +2472,9 @@ fn test_raw_invalid_utf8() { #[test] fn test_serialize_unsized_value_to_raw_value() { assert_eq!( - serde_json::value::to_raw_value("foobar").unwrap().get(), + sciformats_serde_json::value::to_raw_value("foobar") + .unwrap() + .get(), r#""foobar""#, ); } @@ -2530,8 +2534,8 @@ fn test_value_into_deserializer() { fn hash_positive_and_negative_zero() { let rand = std::hash::RandomState::new(); - let k1 = serde_json::from_str::("0.0").unwrap(); - let k2 = serde_json::from_str::("-0.0").unwrap(); + let k1 = sciformats_serde_json::from_str::("0.0").unwrap(); + let k2 = sciformats_serde_json::from_str::("-0.0").unwrap(); if cfg!(feature = "arbitrary_precision") { assert_ne!(k1, k2); assert_ne!(rand.hash_one(k1), rand.hash_one(k2)); diff --git a/tests/ui/missing_colon.rs b/tests/ui/missing_colon.rs index d93b7b907..262d3fdb6 100644 --- a/tests/ui/missing_colon.rs +++ b/tests/ui/missing_colon.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "a" }); diff --git a/tests/ui/missing_comma.rs b/tests/ui/missing_comma.rs index 8818c3e60..7cce8652c 100644 --- a/tests/ui/missing_comma.rs +++ b/tests/ui/missing_comma.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "1": "" "2": "" }); diff --git a/tests/ui/missing_value.rs b/tests/ui/missing_value.rs index 0ba14e22c..c76eaffe6 100644 --- a/tests/ui/missing_value.rs +++ b/tests/ui/missing_value.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "a" : }); diff --git a/tests/ui/not_found.rs b/tests/ui/not_found.rs index 2df6870dc..2bd7c7d09 100644 --- a/tests/ui/not_found.rs +++ b/tests/ui/not_found.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "a" : x }); diff --git a/tests/ui/parse_expr.rs b/tests/ui/parse_expr.rs index e7f1805b1..73f84ed34 100644 --- a/tests/ui/parse_expr.rs +++ b/tests/ui/parse_expr.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "a" : ~ }); diff --git a/tests/ui/parse_key.rs b/tests/ui/parse_key.rs index 858bd7169..6a5afe253 100644 --- a/tests/ui/parse_key.rs +++ b/tests/ui/parse_key.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "".s : true }); diff --git a/tests/ui/unexpected_after_array_element.rs b/tests/ui/unexpected_after_array_element.rs index 226c58cf1..4dab30e29 100644 --- a/tests/ui/unexpected_after_array_element.rs +++ b/tests/ui/unexpected_after_array_element.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!([ true => ]); diff --git a/tests/ui/unexpected_after_map_entry.rs b/tests/ui/unexpected_after_map_entry.rs index 0dfb73155..96beefe0a 100644 --- a/tests/ui/unexpected_after_map_entry.rs +++ b/tests/ui/unexpected_after_map_entry.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "k": true => }); diff --git a/tests/ui/unexpected_colon.rs b/tests/ui/unexpected_colon.rs index e767ea6f7..d5c9d2ab8 100644 --- a/tests/ui/unexpected_colon.rs +++ b/tests/ui/unexpected_colon.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ : true }); diff --git a/tests/ui/unexpected_comma.rs b/tests/ui/unexpected_comma.rs index 338874ed8..ad6f871f2 100644 --- a/tests/ui/unexpected_comma.rs +++ b/tests/ui/unexpected_comma.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use sciformats_serde_json::json; fn main() { json!({ "a" , "b": true }); From c8949d79dc6feefbc7100bb3a9fd7b06de1be9fe Mon Sep 17 00:00:00 2001 From: devrosch Date: Tue, 6 Jan 2026 16:10:10 +0100 Subject: [PATCH 2/3] add initial CD config --- .github/workflows/cd.yml | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 .github/workflows/cd.yml diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 000000000..4b2c08a2c --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,44 @@ +name: CD + +on: + push: + tags: + - 'v*' + workflow_call: + secrets: + CRATES_IO_TOKEN: + required: true + +env: + CARGO_TERM_COLOR: always + +concurrency: + group: "publish" + cancel-in-progress: false + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write # for OIDC token exchange required for Trusted Publishing + environment: crates.io + steps: + - uses: actions/checkout@v5 + - name: Build + run: cargo build --release + - name: Package + run: cargo package + - name: Login to crates.io + run: cargo login ${{ secrets.CRATES_IO_TOKEN }} + - name: "Publish (dry run)" + run: cargo publish --dry-run + # - name: "Publish" + # run: cargo publish + + # - uses: rust-lang/crates-io-auth-action@v1 + # id: auth + # - name: "Publish" + # run: cargo publish + # env: + # CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} \ No newline at end of file From e73b35293447500aed12e5cb385e1c08f64a9542 Mon Sep 17 00:00:00 2001 From: devrosch Date: Tue, 6 Jan 2026 16:14:49 +0100 Subject: [PATCH 3/3] disable scheduled CI --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f36fe42ce..25ba7be6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,7 @@ on: push: pull_request: workflow_dispatch: - schedule: [cron: "40 1 * * *"] + # schedule: [cron: "40 1 * * *"] permissions: contents: read