### Example of new Source: https://docs.rs/struson/latest/struson/reader/simple/struct.SimpleJsonReader.html Example showing how to create a new SimpleJsonReader from a reader. ```rust pub fn new(reader: R) -> Self ``` -------------------------------- ### Example of from_json_reader Source: https://docs.rs/struson/latest/struson/reader/simple/struct.SimpleJsonReader.html Example showing how to create a SimpleJsonReader from an existing JsonReader with custom settings. ```rust let json = r#"\n [ 1, 2, ] "#.as_bytes(); let json_reader = SimpleJsonReader::from_json_reader( JsonStreamReader::new_custom( json, ReaderSettings { allow_trailing_comma: true, // For all other settings use the default ..Default::default() }, ) ); ``` -------------------------------- ### WriterSettings struct example Source: https://docs.rs/struson/latest/src/struson/writer/stream_writer.rs.html Example of how to use WriterSettings with default values for unspecified fields. ```rust # use struson::writer::WriterSettings WriterSettings { pretty_print: true, // For all other settings use the default ..Default::default() } ``` -------------------------------- ### Example of creating ReaderSettings with default values Source: https://docs.rs/struson/latest/struson/reader/struct.ReaderSettings.html An example showing how to create ReaderSettings, using default values for unchanged settings with `..Default::default()`. ```rust ReaderSettings { allow_comments: true, // For all other settings use the default ..Default::default() } ``` -------------------------------- ### Deserialization Example Source: https://docs.rs/struson/latest/src/struson/serde/mod.rs.html This example demonstrates how to deserialize JSON data into a Rust struct using `JsonStreamReader` and `deserialize_next`. ```rust # use struson::reader::* # use struson::reader::json_path::* # use serde::* // In this example JSON data comes from a string; // normally it would come from a file or a network connection let json = r#"{"outer": {"text": "some text", "number": 5}}"#; let mut json_reader = JsonStreamReader::new(json.as_bytes()); // Skip outer data using the regular JsonReader methods json_reader.seek_to(&json_path!["outer"])?; #[derive(Deserialize, PartialEq, Debug)] struct MyStruct { text: String, number: u64, } let value: MyStruct = json_reader.deserialize_next()?; // Skip the remainder of the JSON document json_reader.skip_to_top_level()?; // Ensures that there is no trailing data json_reader.consume_trailing_whitespace()?; assert_eq!( value, MyStruct { text: "some text".to_owned(), number: 5 } ); # Ok::<(), Box>(()) ``` -------------------------------- ### begin_object method Source: https://docs.rs/struson/latest/src/struson/writer/stream_writer.rs.html Starts a JSON object. ```rust fn begin_object(&mut self) -> Result<(), IoError> { self.on_container_start(StackValue::Object)?; self.expects_member_name = true; self.writer.write(b"{") } ``` -------------------------------- ### Serialization Example Source: https://docs.rs/struson/latest/src/struson/serde/mod.rs.html This example demonstrates how to serialize a Rust struct into JSON using `JsonStreamWriter` and `serialize_value`. ```rust # use struson::writer::* # use serde::* // In this example JSON bytes are stored in a Vec; // normally they would be written to a file or network connection let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); // Start writing the enclosing data using the regular JsonWriter methods json_writer.begin_object()?; json_writer.name("outer")?; #[derive(Serialize)] struct MyStruct { text: String, number: u64, } let value = MyStruct { text: "some text".to_owned(), number: 5, }; // Serialize the value as next JSON value json_writer.serialize_value(&value)?; // Write the remainder of the enclosing data json_writer.end_object()?; // Ensures that the JSON document is complete and flushes the buffer json_writer.finish_document()?; let json = String::from_utf8(writer)?; assert_eq!( json, r#"{"outer":{"text":"some text","number":5}}"# ); # Ok::<(), Box>(()) ``` -------------------------------- ### Search Tricks Source: https://docs.rs/struson/latest/help.html Examples of how to use prefixes and other techniques to refine search queries in Rustdoc. ```text fn: struct: enum: trait: type: macro: constant: vec -> usize -> vec String, enum:Cow -> bool "string" -> [u8] [] -> Option vec::Vec ``` -------------------------------- ### Example of seek_to Source: https://docs.rs/struson/latest/struson/reader/simple/struct.SimpleJsonReader.html Example demonstrating how to use seek_to to navigate to a specific element in the JSON document and then read it. ```rust let mut json_reader = SimpleJsonReader::new( r#"{"bar": true, "foo": ["a", "b", "c"]}"#.as_bytes() ); json_reader.seek_to(&json_path!["foo", 2])?; // Can now consume the value to which the call seeked to let value = json_reader.read_string()?; assert_eq!(value, "c"); ``` -------------------------------- ### Example of creating SimpleJsonWriter from JsonWriter Source: https://docs.rs/struson/latest/struson/writer/simple/struct.SimpleJsonWriter.html Example showing how to create a SimpleJsonWriter from an existing JsonWriter. ```rust let mut writer = Vec::::new(); let json_writer = SimpleJsonWriter::from_json_writer( JsonStreamWriter::new_custom( &mut writer, WriterSettings { pretty_print: true, ..Default::default() }, ) ); ``` -------------------------------- ### begin_array method Source: https://docs.rs/struson/latest/src/struson/writer/stream_writer.rs.html Starts a JSON array. ```rust fn begin_array(&mut self) -> Result<(), IoError> { self.on_container_start(StackValue::Array)?; // Clear this because it is only relevant for objects; will be restored when entering parent object (if any) again self.expects_member_name = false; self.writer.write(b"[") } ``` -------------------------------- ### Example of using StringValueWriter Source: https://docs.rs/struson/latest/struson/writer/trait.StringValueWriter.html Demonstrates mixing write_all and write_str calls with StringValueWriter. ```Rust let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); let mut string_writer = json_writer.string_value_writer()?; // Mixes `write_all` and `write_str` calls string_writer.write_all("one, ".as_bytes())?; string_writer.write_str("two, ")?; string_writer.write_all("three ".as_bytes())?; string_writer.write_str("and four")?; string_writer.finish_value()?; json_writer.finish_document()?; let json = String::from_utf8(writer)?; assert_eq!(json, "\"one, two, three and four\""); ``` -------------------------------- ### Example usage of json_path macro Source: https://docs.rs/struson/latest/struson/macro.json_path.html An example demonstrating how to use the json_path macro to create a JSON path and assert its correctness. ```rust let json_path = json_path!["outer", 3, "inner"]; assert_eq!( json_path, [ ObjectMember("outer".to_owned()), ArrayItem(3), ObjectMember("inner".to_owned()), ] ); ``` -------------------------------- ### SimpleJsonWriter Example Source: https://docs.rs/struson/latest/src/struson/writer/simple.rs.html Example demonstrating how to use SimpleJsonWriter to write JSON to a Vec. ```rust use struson::writer::simple::*; // In this example JSON bytes are stored in a Vec; // normally they would be written to a file or network connection let mut writer = Vec::::new(); let json_writer = SimpleJsonWriter::new(&mut writer); json_writer.write_object(|object_writer| { object_writer.write_number_member("a", 1)?; object_writer.write_bool_member("b", true)?; Ok(()) })?; let json = String::from_utf8(writer)?; assert_eq!(json, r#"{"a":1,"b":true}"#); Ok::<(), Box>(()) ``` -------------------------------- ### Example usage of SimpleJsonReader Source: https://docs.rs/struson/latest/struson/reader/simple/struct.SimpleJsonReader.html Example demonstrating how to use SimpleJsonReader to read an array of strings from a JSON string. ```rust let json_reader = SimpleJsonReader::new(r#"["a", "short", "example"]"#.as_bytes()); let mut words = Vec::::new(); json_reader.read_array_items(|item_reader| { let word = item_reader.read_string()?; words.push(word); Ok(()) })?; assert_eq!(words, vec!["a", "short", "example"]); ``` -------------------------------- ### StringValueWriter Example Source: https://docs.rs/struson/latest/src/struson/writer/mod.rs.html Example demonstrating the usage of StringValueWriter to write a JSON string value. ```rust use struson::writer::*; use std::io::Write; let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); ``` -------------------------------- ### Panic Handling Example Source: https://docs.rs/struson/latest/src/struson/utf8.rs.html Example of catching a panic and extracting the panic value, specifically a String. ```Rust if let Err(panic_value) = std::panic::catch_unwind(f) { match panic_value.downcast::() { Ok(message) => *message, Err(panic_value) => { panic!("Panic value should have been a String, but is: {panic_value:?}") } } } else { panic!("Expression should have panicked"); } ``` -------------------------------- ### Container Start Handling Source: https://docs.rs/struson/latest/src/struson/reader/stream_reader.rs.html Handles the start of a new container (object or array), updating the expected value type and pushing a new value onto the stack. ```Rust fn on_container_start( &mut self, expected_value_type: ValueType, stack_value: StackValue, ) -> Result<(), ReaderError> { self.start_expected_value_type(expected_value_type, true)?; self.stack.push(stack_value); // The new container is initially empty self.is_empty = true; Ok(()) } ``` -------------------------------- ### seek_to example Source: https://docs.rs/struson/latest/src/struson/reader/simple.rs.html Demonstrates how to use `seek_to` to navigate to a specific JSON element and then consume it. ```rust # use struson::reader::simple::* # use struson::reader::json_path::* let mut json_reader = SimpleJsonReader::new( r#"{"bar": true, "foo": ["a", "b", "c"]}"#.as_bytes() ); json_reader.seek_to(&json_path!["foo", 2])?; // Can now consume the value to which the call seeked to let value = json_reader.read_string()?; assert_eq!(value, "c"); # Ok::<(), Box>(()) ``` -------------------------------- ### Example of using JsonStreamWriter Source: https://docs.rs/struson/latest/src/struson/writer/mod.rs.html This example demonstrates how to use JsonStreamWriter to write a JSON document to a Vec. ```rust # use struson::writer::* # # // In this example JSON bytes are stored in a Vec; # // normally they would be written to a file or network connection # let mut writer = Vec::::new(); # let mut json_writer = JsonStreamWriter::new(&mut writer); # # json_writer.begin_object()?; # json_writer.name("a")?; # # json_writer.begin_array()?; # json_writer.number_value(1)?; # json_writer.bool_value(true)?; # json_writer.end_array()?; # # json_writer.end_object()?; # // Ensures that the JSON document is complete and flushes the buffer # json_writer.finish_document()?; # # let json = String::from_utf8(writer)?; # assert_eq!(json, r#"{"a":[1,true]}""#); # Ok::<(), Box>(()) ``` -------------------------------- ### Simple API - Writing Source: https://docs.rs/struson/latest/index.html Example of writing a JSON object using the simple API. ```rust use struson::writer::simple::* // In this example JSON bytes are stored in a Vec; // normally they would be written to a file or network connection let mut writer = Vec::::new(); let json_writer = SimpleJsonWriter::new(&mut writer); json_writer.write_object(|object_writer| { object_writer.write_number_member("a", 1)?; object_writer.write_bool_member("b", true)?; Ok(()) })?; let json = String::from_utf8(writer)?; assert_eq!(json, r#"{"a":1,"b":true}"#); ``` -------------------------------- ### Example usage of SimpleJsonWriter Source: https://docs.rs/struson/latest/struson/writer/simple/struct.SimpleJsonWriter.html Example demonstrating how to use SimpleJsonWriter to write JSON data to a Vec. ```rust let mut writer = Vec::::new(); let json_writer = SimpleJsonWriter::new(&mut writer); json_writer.write_object(|object_writer| { object_writer.write_number_member("a", 1)?; object_writer.write_bool_member("b", true)?; Ok(()) })?; let json = String::from_utf8(writer)?; assert_eq!(json, r#"{"a":1,"b":true}"#); ``` -------------------------------- ### Tuple Struct Serialization Example Source: https://docs.rs/struson/latest/src/struson/serde/ser.rs.html Demonstrates serializing tuple structs, similar to tuples but with a name. ```rust assert_serialized_cmp!( |s| { let mut tuple = s.serialize_tuple_struct("name", 2)?; tuple.serialize_field(&1)?; tuple.serialize_field(&2)?; tuple.end() }, "[1,2]" ); ``` -------------------------------- ### Multi JSON Path Macro Usage Example Source: https://docs.rs/struson/latest/src/struson/reader/simple.rs.html Example demonstrating how to use the `multi_json_path` macro to create a JSON path for matching all awards from any book in a list, including optional members and non-empty arrays. ```rust # use struson::reader::simple::multi_json_path::* # use struson::reader::simple::multi_json_path::MultiJsonPathPiece::* let json_path = multi_json_path![ "books", [*], // match all books ?"awards", // match the optional "awards" member [+], // match all awards (requiring non-empty array) ]; assert_eq!( json_path, [ ObjectMember("books".to_owned()), AllArrayItems { allow_empty: true }, OptionalObjectMember("awards".to_owned()), AllArrayItems { allow_empty: false }, ] ); ``` -------------------------------- ### Tuple Serialization Example Source: https://docs.rs/struson/latest/src/struson/serde/ser.rs.html Illustrates serializing tuples of different sizes, including an empty tuple. ```rust assert_serialized_cmp!( |s| { let mut tuple = s.serialize_tuple(2)?; tuple.serialize_element(&1)?; tuple.serialize_element(&2)?; tuple.end() }, "[1,2]" ); ``` -------------------------------- ### Example usage Source: https://docs.rs/struson/latest/struson/reader/simple/multi_json_path/macro.multi_json_path.html An example demonstrating how to use the multi_json_path macro to match all awards any book has received, including assertions. ```rust let json_path = multi_json_path![ "books", [*], // match all books ?"awards", // match the optional "awards" member [+], // match all awards (requiring non-empty array) ]; assert_eq!( json_path, [ ObjectMember("books".to_owned()), AllArrayItems { allow_empty: true }, OptionalObjectMember("awards".to_owned()), AllArrayItems { allow_empty: false }, ] ); ``` -------------------------------- ### Struct Serialization Example Source: https://docs.rs/struson/latest/src/struson/serde/ser.rs.html Demonstrates serializing a struct with multiple fields, including skipping a field. ```rust assert_serialized_cmp!( |s| { let mut struc = s.serialize_struct("name", 2)?; struc.serialize_field("key1", &1)?; struc.skip_field("skipped")?; struc.serialize_field("key2", &2)?; struc.end() }, r#"{"key1":1,"key2":2}"#.to_owned() ); ``` -------------------------------- ### Serialization Example Source: https://docs.rs/struson/latest/struson/serde/index.html Serializes a struct to a JSON writer, demonstrating the use of `serialize_value`. ```Rust // In this example JSON bytes are stored in a Vec; // normally they would be written to a file or network connection let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); // Start writing the enclosing data using the regular JsonWriter methods json_writer.begin_object()?; json_writer.name("outer")?; #[derive(Serialize)] struct MyStruct { text: String, number: u64, } let value = MyStruct { text: "some text".to_owned(), number: 5, }; // Serialize the value as next JSON value json_writer.serialize_value(&value)?; // Write the remainder of the enclosing data json_writer.end_object()?; // Ensures that the JSON document is complete and flushes the buffer json_writer.finish_document()?; let json = String::from_utf8(writer)?; assert_eq!( json, r#"{"outer":{"text":"some text","number":5}}""# ); ``` -------------------------------- ### Malformed Array Examples Source: https://docs.rs/struson/latest/src/struson/reader/stream_reader.rs.html Illustrates various malformed array scenarios and the expected parsing errors. ```rust let mut json_reader = new_reader("[1 2]"); json_reader.begin_array()?; assert_eq!("1", json_reader.next_number_as_string()?); assert_parse_error_with_path( None, json_reader.has_next(), SyntaxErrorKind::MissingComma, &json_path![1], 3, ); let mut json_reader = new_reader("[1: 2]"); json_reader.begin_array()?; assert_eq!("1", json_reader.next_number_as_string()?); assert_parse_error_with_path( None, json_reader.has_next(), SyntaxErrorKind::UnexpectedColon, &json_path![1], 2, ); let mut json_reader = new_reader(r#"["a": 1]"#); json_reader.begin_array()?; assert_eq!("a", json_reader.next_string()?); assert_parse_error_with_path( None, json_reader.has_next(), SyntaxErrorKind::UnexpectedColon, &json_path![1], 4, ); let mut json_reader = new_reader("[1}"); json_reader.begin_array()?; assert_eq!("1", json_reader.next_number_as_string()?); assert_parse_error_with_path( None, json_reader.has_next(), SyntaxErrorKind::UnexpectedClosingBracket, &json_path![1], 2, ); assert_parse_error_with_path( None, json_reader.end_array(), SyntaxErrorKind::UnexpectedClosingBracket, &json_path![1], 2, ); ``` -------------------------------- ### Struct Variant Serialization Example Source: https://docs.rs/struson/latest/src/struson/serde/ser.rs.html Shows how to serialize a struct variant, including adding fields to it. ```rust assert_serialized_cmp!( |s| { let mut struc = s.serialize_struct_variant("name", 1, "variant", 2)?; struc.serialize_field("key1", &1)?; struc.skip_field("skipped")?; struc.serialize_field("key2", &2)?; struc.end() }, r#"{"variant":{"key1":1,"key2":2}}"#.to_owned() ); ``` -------------------------------- ### Getting Current Position Source: https://docs.rs/struson/latest/src/struson/reader/mod.rs.html Example showing how to use `current_position` to get the reader's location within the JSON data, optionally including the JSON path for better error reporting. ```rust # use struson::reader::* # let mut json_reader = JsonStreamReader::new( # r#"["1|2", "3|2", "8"]"#.as_bytes() # ); # json_reader.begin_array()?; # # while json_reader.has_next()? { # let pos = json_reader.current_position(true); # let encoded_point = json_reader.next_str()?; # # # #[expect(unused_variables)] # if let Some((x, y)) = encoded_point.split_once('|') { # // ... # } else { # // Includes the JSON reader position for easier troubleshooting # println!("Malformed point '{}', at {}", encoded_point, pos); # # assert_eq!(pos.to_string(), "path '$[2]', line 0, column 15 (data pos 15)"); # } # } # # Ok::<(), Box>(()) ``` -------------------------------- ### Keyboard Shortcuts Source: https://docs.rs/struson/latest/help.html A list of keyboard shortcuts for navigating and interacting with Rustdoc. ```text `?` Show this help dialog `S` / `/` Focus the search field `↑` Move up in search results `↓` Move down in search results `←` / `→` Switch result tab (when results focused) `⏎` Go to active search result `+` / `=` Expand all sections `-` Collapse all sections `_` Collapse all sections, including impl blocks ``` -------------------------------- ### Consuming and returning the name of the next JSON object member Source: https://docs.rs/struson/latest/src/struson/reader/mod.rs.html Example showing how to use `next_name` to get the name of a JSON object member. ```rust # use struson::reader::* let mut json_reader = JsonStreamReader::new(r#"{"a": 1}"#.as_bytes()); json_reader.begin_object()?; assert_eq!(json_reader.next_name()?, "a"); # Ok::<(), Box>(()) ``` -------------------------------- ### Writing a finite number value Source: https://docs.rs/struson/latest/src/struson/writer/mod.rs.html This example demonstrates writing a standard integral number value. ```rust # use struson::writer::* let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); json_writer.number_value(123)?; json_writer.finish_document()?; let json = String::from_utf8(writer)?; assert_eq!(json, "123"); ``` -------------------------------- ### Reading a JSON number as a string Source: https://docs.rs/struson/latest/struson/reader/trait.JsonReader.html Example showing how to read a JSON number value and get its string representation using `next_number_as_str`. ```rust let mut json_reader = JsonStreamReader::new("12.0e5".as_bytes()); assert_eq!(json_reader.next_number_as_str()?, "12.0e5"); ``` -------------------------------- ### UTF-8 Byte Checks Source: https://docs.rs/struson/latest/src/struson/utf8.rs.html Functions to check if a byte is part of a UTF-8 encoded character (1-byte, 2-byte start, 3-byte start, 4-byte start, or continuation). ```Rust /// Maximum number of UTF-8 bytes needed to encode one Unicode `char` pub(crate) const MAX_BYTES_PER_CHAR: usize = 4; /// Whether the byte is a 1 byte UTF-8 encoded char; that means the byte itself represents an ASCII character pub(crate) fn is_1byte(b: u8) -> bool { b <= 0x7F } const _2BYTE_MASK: u8 = 0b1110_0000; /// Bit mask which matches the value bits of the 2 byte start const _2BYTE_MASK_VAL: u8 = !_2BYTE_MASK; /// Whether the byte is the start of a 2 byte UTF-8 encoded char pub(crate) fn is_2byte_start(b: u8) -> bool { // 110x_xxxx (b & _2BYTE_MASK) == 0b1100_0000 } const _3BYTE_MASK: u8 = 0b1111_0000; /// Bit mask which matches the value bits of the 3 byte start const _3BYTE_MASK_VAL: u8 = !_3BYTE_MASK; /// Whether the byte is the start of a 3 byte UTF-8 encoded char pub(crate) fn is_3byte_start(b: u8) -> bool { // 1110_xxxx (b & _3BYTE_MASK) == 0b1110_0000 } const _4BYTE_MASK: u8 = 0b1111_1000; /// Bit mask which matches the value bits of the 4 byte start const _4BYTE_MASK_VAL: u8 = !_4BYTE_MASK; /// Whether the byte is the start of a 4 byte UTF-8 encoded char pub(crate) fn is_4byte_start(b: u8) -> bool { // 1111_0xxx (b & _4BYTE_MASK) == 0b1111_0000 } const CONT_MASK: u8 = 0b1100_0000; /// Bit mask which matches the value bits of the continuation byte const CONT_MASK_VAL: u8 = !CONT_MASK; /// Whether the byte is a continuation byte of a char which is UTF-8 encoded as 2, 3 or 4 bytes; /// that means it is not the first byte for those multi-byte UTF-8 chars pub(crate) fn is_continuation(b: u8) -> bool { // 10xx_xxxx (b & CONT_MASK) == 0b1000_0000 } ``` -------------------------------- ### Compact JSON example Source: https://docs.rs/struson/latest/struson/writer/struct.WriterSettings.html An example of how compact JSON output looks. ```json {"a":[1,2]} ``` -------------------------------- ### Object Trailing Comma Example Source: https://docs.rs/struson/latest/src/struson/reader/stream_reader.rs.html Shows an example of an object with a leading comma, which is an invalid syntax. ```rust let mut json_reader = new_reader("{,}"); json_reader.begin_object()?; assert_parse_error_with_path( None, json_reader.has_next(), SyntaxErrorKind::UnexpectedComma, &json_path![""], 1, ); ``` -------------------------------- ### Example: Serde Serialization Source: https://docs.rs/struson/latest/struson/writer/simple/trait.ValueWriter.html Shows how to serialize a Rust struct into JSON using the `write_serialize` method with Serde integration. ```rust let mut writer = Vec::::new(); let json_writer = SimpleJsonWriter::new(&mut writer); #[derive(Serialize)] struct MyStruct { text: String, number: u64, } let value = MyStruct { text: "some text".to_owned(), number: 5, }; json_writer.write_serialize(&value)?; let json = String::from_utf8(writer)?; assert_eq!( json, r#"{"text":"some text","number":5}"# ); ``` -------------------------------- ### Example Usage Source: https://docs.rs/struson/latest/struson/serde/struct.JsonReaderDeserializer.html Example of using JsonReaderDeserializer with a JsonStreamReader to deserialize JSON data from a string. ```Rust let json = r#"{"text": "some text", "number": 5}"#; let mut json_reader = JsonStreamReader::new(json.as_bytes()); let mut deserializer = JsonReaderDeserializer::new(&mut json_reader); #[derive(Deserialize, PartialEq, Debug)] struct MyStruct { text: String, number: u64, } let value = MyStruct::deserialize(&mut deserializer)?; // Ensures that there is no trailing data json_reader.consume_trailing_whitespace()?; assert_eq!( value, MyStruct { text: "some text".to_owned(), number: 5 } ); ``` -------------------------------- ### Map Serialization Example Source: https://docs.rs/struson/latest/src/struson/serde/ser.rs.html Demonstrates serializing various types as map keys and values, including primitive types, options, and custom structs. ```rust map.serialize_value(&0)?; map.serialize_key(&1.23_f32)?; map.serialize_value(&0)?; map.serialize_key(&'a')?; map.serialize_value(&0)?; map.serialize_key(&Some("value"))?; map.serialize_value(&0)?; struct UnitVariant; impl Serialize for UnitVariant { fn serialize( &self, serializer: S, ) -> Result { serializer.serialize_unit_variant("name", 1, "UnitVariant") } } map.serialize_key(&UnitVariant)?; map.serialize_value(&0)?; struct NewtypeStruct; impl Serialize for NewtypeStruct { fn serialize( &self, serializer: S, ) -> Result { serializer.serialize_newtype_struct("name", "NewtypeStruct") } } map.serialize_key(&NewtypeStruct)?; map.serialize_value(&0)?; map.end() ``` -------------------------------- ### Using WriterSettings with Default::default() Source: https://docs.rs/struson/latest/struson/writer/struct.WriterSettings.html Example of how to use WriterSettings with default values for unchanged settings. ```rust WriterSettings { pretty_print: true, // For all other settings use the default ..Default::default() } ``` -------------------------------- ### has_next method example Source: https://docs.rs/struson/latest/struson/reader/simple/struct.ArrayReader.html Example of using the `has_next` method to iterate through a JSON array. ```rust let json_reader = SimpleJsonReader::new("[1, 2]".as_bytes()); json_reader.read_array(|array_reader| { while array_reader.has_next()? { let value = array_reader.read_number_as_string()?; println!("{value}"); } Ok(()) })?; ``` -------------------------------- ### Pretty Print Example Source: https://docs.rs/struson/latest/src/struson/writer/stream_writer.rs.html Demonstrates how to use `JsonStreamWriter` with `pretty_print` enabled and a custom separator for multiple top-level values. ```Rust #[test] fn pretty_print() -> TestResult { let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new_custom( &mut writer, WriterSettings { pretty_print: true, multi_top_level_value_separator: Some("#".to_owned()), ..Default::default() }, ); json_writer.begin_array()?; json_writer.begin_array()?; json_writer.end_array()?; json_writer.begin_array()?; json_writer.number_value(1)?; json_writer.end_array()?; json_writer.begin_object()?; json_writer.name("a")?; json_writer.begin_array()?; json_writer.begin_object()?; json_writer.name("b")?; json_writer.number_value(2)?; json_writer.end_object()?; json_writer.begin_object()?; json_writer.end_object()?; json_writer.end_array()?; json_writer.name("c")?; json_writer.number_value(3)?; json_writer.end_object()?; json_writer.end_array()?; json_writer.begin_array()?; json_writer.number_value(4)?; json_writer.end_array()?; json_writer.finish_document()?; assert_eq!( "[\n [],\n [\n 1\n ],\n {\n \"a\": [\n {\n \"b\": 2\n },\n {}\n ],\n \"c\": 3\n }\n]#[" " 4\n]", String::from_utf8(writer)? ); Ok(()) } ``` -------------------------------- ### Pretty printed JSON example Source: https://docs.rs/struson/latest/struson/writer/struct.WriterSettings.html An example of how pretty printed JSON output looks. ```json { "a": [ 1, 2 ] } ``` -------------------------------- ### String Reader - Initial Read Source: https://docs.rs/struson/latest/src/struson/reader/stream_reader.rs.html Demonstrates the initial read operation on a string reader, including reading with an empty buffer and a buffer of size one. ```rust let mut json_reader = new_reader("[\"test\u{10FFFF}\", true, \"ab\"]"); json_reader.begin_array()?; let mut reader = json_reader.next_string_reader()?; // Reading with empty buffer let mut buf = []; assert_eq!(0, reader.read(&mut buf)?); let mut buf = [0_u8; 1]; let mut bytes = Vec::new(); for _ in 0..8 { ``` -------------------------------- ### Creating a SimpleJsonWriter with custom settings Source: https://docs.rs/struson/latest/src/struson/writer/simple.rs.html This example shows how to create a `SimpleJsonWriter` with custom `WriterSettings`, including pretty printing. ```rust let mut writer = Vec::::new(); # #[expect(unused_variables)] let json_writer = SimpleJsonWriter::from_json_writer( JsonStreamWriter::new_custom( &mut writer, WriterSettings { pretty_print: true, // For all other settings use the default ..Default::default() }, ) ); ``` -------------------------------- ### Multiple top-level values example Source: https://docs.rs/struson/latest/struson/writer/struct.WriterSettings.html Example of writing multiple top-level values with a custom separator. ```text 123 ### true ### [] ``` -------------------------------- ### Creating a SimpleJsonWriter with default settings Source: https://docs.rs/struson/latest/src/struson/writer/simple.rs.html This example demonstrates creating a `SimpleJsonWriter` using the `new` method, which utilizes default `WriterSettings`. ```rust pub fn new(writer: W) -> Self { SimpleJsonWriter::from_json_writer(JsonStreamWriter::new(writer)) } ``` -------------------------------- ### Example Usage Source: https://docs.rs/struson/latest/struson/serde/struct.JsonWriterSerializer.html Example demonstrating how to use JsonWriterSerializer to serialize a struct to JSON bytes stored in a Vec. ```Rust let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); let mut serializer = JsonWriterSerializer::new(&mut json_writer); #[derive(Serialize)] struct MyStruct { text: String, number: u64, } let value = MyStruct { text: "some text".to_owned(), number: 5, }; value.serialize(&mut serializer)?; // Ensures that the JSON document is complete and flushes the buffer json_writer.finish_document()?; let json = String::from_utf8(writer)?; assert_eq!( json, r#"{"text":"some text","number":5}""# ); ``` -------------------------------- ### Example of read_string_with_reader Source: https://docs.rs/struson/latest/struson/reader/simple/trait.ValueReader.html An example demonstrating how to use `read_string_with_reader` to read a JSON string value in a streaming manner. ```rust let json_reader = SimpleJsonReader::new("\"text with \\" quote\"".as_bytes()); json_reader.read_string_with_reader(|mut string_reader| { let mut buf = [0_u8; 1]; while string_reader.read(&mut buf)? > 0 { println!("Read byte: {}", buf[0]); } Ok(()) })?; ``` -------------------------------- ### Creating a SimpleJsonReader from an existing JsonReader Source: https://docs.rs/struson/latest/src/struson/reader/simple.rs.html This example shows how to create a SimpleJsonReader by wrapping an existing JsonReader, with custom reader settings. ```rust # use struson::reader::* # use struson::reader::simple::* let json = r#" [ 1, 2, ] "#.as_bytes(); # #[expect(unused_variables)] let json_reader = SimpleJsonReader::from_json_reader( JsonStreamReader::new_custom( json, ReaderSettings { allow_trailing_comma: true, // For all other settings use the default ..Default::default() }, ) ); ``` -------------------------------- ### Test Case: has_next() at Start of Document Source: https://docs.rs/struson/latest/src/struson/reader/stream_reader.rs.html This test verifies that calling `has_next()` before any value has been started results in a panic with the expected error message. ```Rust let mut json_reader = JsonStreamReader::new_custom( "[1]".as_bytes(), ReaderSettings { allow_multiple_top_level: true, ..Default::default() }, ); let _ = json_reader.has_next(); } ``` -------------------------------- ### Example Usage of JsonWriter Source: https://docs.rs/struson/latest/struson/writer/trait.JsonWriter.html An example demonstrating how to use the JsonWriter trait to construct a JSON object with an array. ```rust // In this example JSON bytes are stored in a Vec; // normally they would be written to a file or network connection let mut writer = Vec::::new(); let mut json_writer = JsonStreamWriter::new(&mut writer); json_writer.begin_object()?; json_writer.name("a")?; json_writer.begin_array()?; json_writer.number_value(1)?; json_writer.bool_value(true)?; json_writer.end_array()?; json_writer.end_object()?; // Ensures that the JSON document is complete and flushes the buffer json_writer.finish_document()?; let json = String::from_utf8(writer)?; assert_eq!(json, r#"{"a":[1,true]}"#); ```