### Raw String Example Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md An example of a raw string literal in Rust syntax, demonstrating its ability to contain special characters and nested quotes. ```rust r##"This is a "raw string". It can contain quotations or backslashes (\)!"## ``` -------------------------------- ### JSON Example Data Source: https://github.com/ron-rs/ron/blob/master/README.md A sample JSON structure representing scene materials and entities. ```json { "materials": { "metal": { "reflectivity": 1.0 }, "plastic": { "reflectivity": 0.5 } }, "entities": [ { "name": "hero", "material": "metal" }, { "name": "monster", "material": "plastic" } ] } ``` -------------------------------- ### Rust Structs for unwrap_newtypes Example Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Defines the Rust structs used to demonstrate the `unwrap_newtypes` extension. ```rust struct NewType(u32); struct Object { pub new_type: NewType, } ``` -------------------------------- ### RON Example Configuration Source: https://github.com/ron-rs/ron/blob/master/README.md Demonstrates a typical RON configuration structure for game settings, including nested tuples, maps, and enums. Comments are supported. ```ron GameConfig( // optional struct name window_size: (800, 600), window_title: "PAC-MAN", fullscreen: false, mouse_sensitivity: 1.4, key_bindings: { "up": Up, "down": Down, "left": Left, "right": Right, // Uncomment to enable WASD controls /* "W": Up, "S": Down, "A": Left, "D": Right, */ }, difficulty_options: ( start_difficulty: Easy, adaptive: false, ), ) ``` -------------------------------- ### Rust Struct for implicit_some Example Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Defines the Rust struct used to demonstrate the `implicit_some` extension. ```rust struct Object { pub value: Option, } ``` -------------------------------- ### RON Equivalent of JSON Example Source: https://github.com/ron-rs/ron/blob/master/README.md The same scene data represented in RON, highlighting advantages like unquoted field names and optional struct names. ```ron Scene( // class name is optional materials: { // this is a map "metal": ( reflectivity: 1.0, ), "plastic": ( reflectivity: 0.5, ), }, entities: [ // this is an array ( name: "hero", material: "metal", ), ( name: "monster", material: "plastic", ), ], ) ``` -------------------------------- ### Rust Structs for unwrap_variant_newtypes Example Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Defines the Rust structs and enums used to demonstrate the `unwrap_variant_newtypes` extension. ```rust struct Inner { pub a: u8, pub b: bool, } #[derive(Deserialize)] pub enum Enum { A(Inner), B, } ``` -------------------------------- ### RON with explicit_struct_names Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Example of RON structure that is valid with the `explicit_struct_names` extension enabled. ```ron Foo( bar: Bar(42), ) ``` -------------------------------- ### Enable RON Extensions Inline and Programmatically Source: https://context7.com/ron-rs/ron/llms.txt RON extensions can be enabled using inline `#![enable(...)]` syntax within the RON document or programmatically via `Options::with_default_extension`. This example demonstrates `UNWRAP_NEWTYPES`, `IMPLICIT_SOME`, and `EXPLICIT_STRUCT_NAMES`. ```rust use serde::{Deserialize, Serialize}; use ron::{Options, extensions::Extensions}; #[derive(Debug, Deserialize, Serialize, PartialEq)] struct Wrapper(u32); #[derive(Debug, Deserialize, Serialize, PartialEq)] struct Item { count: Wrapper, label: Option, } fn main() { // --- INLINE extension syntax in the RON document --- let ron_inline = r#" #![enable(unwrap_newtypes)] #![enable(implicit_some)] ( count: 5, // bare 5 auto-wraps to Wrapper(5) label: "hello", // bare "hello" auto-wraps to Some("hello") ) "#; let item: Item = ron::from_str(ron_inline).unwrap(); assert_eq!(item.count, Wrapper(5)); assert_eq!(item.label, Some(String::from("hello"))); // --- Programmatic extension via Options --- let opts = Options::default() .with_default_extension(Extensions::UNWRAP_NEWTYPES | Extensions::IMPLICIT_SOME); let item2: Item = opts.from_str("(count: 10, label: \"world\")").unwrap(); assert_eq!(item2.count, Wrapper(10)); // --- EXPLICIT_STRUCT_NAMES requires names at deserialization time --- let opts_explicit = Options::default() .with_default_extension(Extensions::EXPLICIT_STRUCT_NAMES); let ok = opts_explicit.from_str::("Item(count: Wrapper(3), label: None)"); assert!(ok.is_ok()); let fail = opts_explicit.from_str::("(count: Wrapper(3), label: None)"); assert!(fail.is_err()); // Missing struct name "Item" } ``` -------------------------------- ### RON Comments Source: https://github.com/ron-rs/ron/wiki/Specification Comments in RON start with `//` and extend to the end of the line. They can appear on their own line or after code. ```rust // This is a comment. ( field_name: 3.4, //This is another comment. b: 'b', ) ``` -------------------------------- ### Configure RON serialization/deserialization with Options Source: https://context7.com/ron-rs/ron/llms.txt The `Options` builder allows configuring advanced serialization and deserialization behavior, such as enabling default extensions and setting recursion limits. All `Options` methods mirror the top-level convenience functions. ```rust use ron::{Options, extensions::Extensions}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize, PartialEq)] struct Node { value: Option, tag: String, } fn main() { // Build custom options: enable implicit_some and increase recursion limit let options = Options::default() .with_default_extension(Extensions::IMPLICIT_SOME) .with_default_extension(Extensions::UNWRAP_NEWTYPES) .with_recursion_limit(256); // With IMPLICIT_SOME, bare values are automatically wrapped in Some(...) let node: Node = options.from_str(r#"(value: 99, tag: \"test\")"#).unwrap(); assert_eq!(node.value, Some(99)); println!("{:?}", node); // Node { value: Some(99), tag: "test" } // Roundtrip: serialize back (extension header NOT emitted for default_extensions) let serialized = options.to_string(&node).unwrap(); println!("{}", serialized); // (value:99,tag:"test") // Pretty-print with options use ron::ser::PrettyConfig; let pretty = options.to_string_pretty(&node, PrettyConfig::default()).unwrap(); println!("{}", pretty); // ( // value: 99, // tag: "test", // ) // Disable recursion limit entirely (use with serde_stacker for safety) let unlimited = Options::default().without_recursion_limit(); let _ = unlimited.from_str::(r#"(value: None, tag: \"x\")"#).unwrap(); } ``` -------------------------------- ### Rust RON Serialization and Deserialization Source: https://github.com/ron-rs/ron/blob/master/README.md Demonstrates basic RON deserialization from a string into a Rust struct and serialization back to a string, including pretty printing. ```rust use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] struct MyStruct { boolean: bool, float: f32, } fn main() { let x: MyStruct = ron::from_str("(boolean: true, float: 1.23)").unwrap(); println!("RON: {}", ron::to_string(&x).unwrap()); println!("Pretty RON: {}", ron::ser::to_string_pretty( &x, ron::ser::PrettyConfig::default()).unwrap(), ); } ``` -------------------------------- ### Configure RON Pretty Printing with PrettyConfig Source: https://context7.com/ron-rs/ron/llms.txt Customize the output format of RON serialization using `PrettyConfig`. This includes settings for indentation, line endings, separators, and array/struct compactness. Requires `ron::ser::to_string_pretty` and `serde::Serialize`. ```rust use ron::ser::{to_string_pretty, PrettyConfig}; use ron::extensions::Extensions; use serde::Serialize; #[derive(Serialize)] struct Weapon { name: String, damage: u32, elemental: Option, } fn main() { let w = Weapon { name: "Sword".into(), damage: 42, elemental: Some("Fire".into()) }; let cfg = PrettyConfig::new() .depth_limit(3) .indentor("\t") // tab indentation .new_line("\n") // Unix line endings .separator(" ") // space after colon/comma .struct_names(true) // emit struct name .separate_tuple_members(false) .enumerate_arrays(false) .compact_arrays(false) // multi-line arrays .compact_structs(false) // multi-line structs .compact_maps(false) // multi-line maps .escape_strings(true) // use escape sequences in strings .number_suffixes(true) // e.g. 42u32 instead of 42 .extensions(Extensions::IMPLICIT_SOME); // emit #![enable(implicit_some)] let s = to_string_pretty(&w, cfg).unwrap(); println!("{}", s); // #![enable(implicit_some)] // Weapon( // name: "Sword", // damage: 42u32, // elemental: "Fire", // ) } ``` -------------------------------- ### ron::Options Source: https://context7.com/ron-rs/ron/llms.txt Provides a builder pattern for configuring advanced RON serialization and deserialization behaviors, such as enabling default extensions and setting recursion limits. ```APIDOC ## `ron::Options` — Configurable serialization/deserialization builder `Options` is a builder struct for configuring advanced serialization and deserialization behavior. Key settings are `default_extensions` (enable RON extensions without `#![enable(...)]` in the document) and `recursion_limit` (protect against stack overflows). All `Options` methods mirror the top-level convenience functions. ### Example ```rust use ron::{Options, extensions::Extensions}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize, PartialEq)] struct Node { value: Option, tag: String, } fn main() { // Build custom options: enable implicit_some and increase recursion limit let options = Options::default() .with_default_extension(Extensions::IMPLICIT_SOME) .with_default_extension(Extensions::UNWRAP_NEWTYPES) .with_recursion_limit(256); // With IMPLICIT_SOME, bare values are automatically wrapped in Some(...) let node: Node = options.from_str(r#"(value: 99, tag: \"test\")"#).unwrap(); assert_eq!(node.value, Some(99)); println!("{:?}", node); // Node { value: Some(99), tag: "test" } // Roundtrip: serialize back (extension header NOT emitted for default_extensions) let serialized = options.to_string(&node).unwrap(); println!("{}", serialized); // (value:99,tag:"test") // Pretty-print with options use ron::ser::PrettyConfig; let pretty = options.to_string_pretty(&node, PrettyConfig::default()).unwrap(); println!("{}", pretty); // ( // value: 99, // tag: "test", // ) // Disable recursion limit entirely (use with serde_stacker for safety) let unlimited = Options::default().without_recursion_limit(); let _ = unlimited.from_str::(r#"(value: None, tag: \"x\")"#).unwrap(); } ``` ``` -------------------------------- ### Parse and Build RON Values Dynamically Source: https://context7.com/ron-rs/ron/llms.txt Demonstrates parsing a RON string into a dynamic `Value` and programmatically building `Value` instances from Rust types. Useful for handling unknown or dynamic RON structures. ```rust use ron::value::{Value, Map, Number}; fn main() { // --- Parse into a dynamic Value --- let ron_str = r#" Scene( materials: { "metal": (reflectivity: 1.0), "plastic": (reflectivity: 0.5), }, entities: [ (name: "hero", material: "metal"), (name: "monster", material: "plastic"), ], ) "#; let value: Value = ron::from_str(ron_str).unwrap(); println!("{:?}", value); // --- Build a Value programmatically --- let v_bool = Value::from(true); let v_num = Value::from(42_u32); let v_str = Value::from("hello"); let v_opt = Value::from(Some(99_i32)); let v_seq = Value::from(vec![1_i32, 2, 3]); let mut map = Map::new(); map.insert(Value::from("key"), Value::from("value")); let v_map = Value::Map(map); // --- Deserialize a Value into a concrete type --- #[derive(Debug, serde::Deserialize, PartialEq)] struct Entity { name: String, material: String } let entity_val: Value = ron::from_str(r#"(name: "hero", material: "metal")"#).unwrap(); let entity: Entity = entity_val.into_rust().unwrap(); assert_eq!(entity.name, "hero"); // --- Transcode RON → JSON --- let json_out = serde_json::to_string_pretty(&value).unwrap(); println!("{}", json_out); } ``` -------------------------------- ### Extensions Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Describes the EBNF syntax for enabling extensions, which involves a specific marker and a list of extension names. ```ebnf extensions = { "#", ws, "!", ws, "[", ws, extensions_inner, ws, "]", ws }; extensions_inner = "enable", ws, "(", extension_name, { comma, extension_name }, [comma], ws, ")"; ``` -------------------------------- ### Enable unwrap_newtypes Extension Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Add this attribute at the top of your RON document to enable automatic unwrapping of simple tuples. ```rust #![enable(unwrap_newtypes)] ( new_type: 5, ) ``` -------------------------------- ### RON without implicit_some Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Shows the RON document structure required without the `implicit_some` extension. ```ron ( value: Some(5), ) ``` -------------------------------- ### RON Unit Struct Representation Source: https://github.com/ron-rs/ron/wiki/Specification Illustrates the RON syntax for unit structs, which can be represented by their name or by empty parentheses. ```rust struct Unit; ``` ```rust Unit ``` ```rust () ``` -------------------------------- ### RON Cargo.toml Dependencies Source: https://github.com/ron-rs/ron/blob/master/README.md Specifies the necessary RON and Serde dependencies for a Rust project. ```toml [dependencies] ron = "0.12" serde = { version = "1", features = ["derive"] } ``` -------------------------------- ### RON without unwrap_variant_newtypes Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Illustrates the RON document structure required without the `unwrap_variant_newtypes` extension. ```ron ( variant: A(Inner(a: 4, b: true)), ) ``` -------------------------------- ### Integer Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the structure of integers, including optional sign, unsigned part, and optional type suffixes. ```ebnf integer = ["+" | "-"], unsigned, [integer_suffix]; integer_suffix = ("i", "u"), ("8", "16", "32", "64", "128"); ``` -------------------------------- ### RON File Structure Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the basic structure of a RON file, including optional extensions, whitespace, and a single value. ```ebnf RON = [extensions], ws, value, ws; ``` -------------------------------- ### Low-level RON Streaming Serialization Source: https://context7.com/ron-rs/ron/llms.txt Use `ron::ser::Serializer` for fine-grained control over serialization, allowing multiple values to the same writer or retrieval of the underlying writer. Supports compact and pretty-printed output with configurable options. ```Rust use ron::ser::{Serializer, PrettyConfig}; use ron::Options; use serde::Serialize; #[derive(Serialize)] struct Frame { id: u32, data: Vec } fn main() { let mut output = String::new(); // Compact serializer let mut ser = Serializer::new(&mut output, None).unwrap(); Frame { id: 1, data: vec![0xAA, 0xBB] }.serialize(&mut ser).unwrap(); println!("{}", output); // (id:1,data:[170,187]) // Retrieve the writer back let writer: &mut String = ser.into_inner(); // Pretty serializer with options let mut buf = String::new(); let opts = Options::default(); let mut pretty_ser = Serializer::with_options( &mut buf, Some(PrettyConfig::new().compact_arrays(true)), &opts, ).unwrap(); Frame { id: 2, data: vec![1, 2, 3] }.serialize(&mut pretty_ser).unwrap(); println!("{}", buf); // ( // id: 2, // data: [1,2,3], // ) } ``` -------------------------------- ### Capture and Defer RON Fragments with RawValue Source: https://context7.com/ron-rs/ron/llms.txt Illustrates using `RawValue` to capture RON fragments without immediate parsing, enabling lazy deserialization or preserving original text. Useful for templating or handling partially known data structures. ```rust use ron::value::RawValue; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] struct Envelope { kind: String, payload: Box, // defer parsing of this field } fn main() { let ron_str = r#"(kind: "update", payload: (x: 1, y: 2, z: 3))"#; let envelope: Envelope = ron::from_str(ron_str).unwrap(); println!("kind: {}", envelope.kind); println!("raw payload: {}", envelope.payload.get_ron()); // raw payload: (x: 1, y: 2, z: 3) // Validate and create a RawValue from a string let raw = RawValue::from_ron("(a: 1, b: true)").unwrap(); println!("{}", raw.get_ron()); // Deserialize the raw fragment into a concrete type when ready #[derive(Debug, Deserialize)] struct Point3 { x: i32, y: i32, z: i32 } let point: Point3 = envelope.payload.into_rust().unwrap(); println!("{:?}", point); // Point3 { x: 1, y: 2, z: 3 } // Build a RawValue by serializing a Rust value let from_rust = RawValue::from_rust(&point).unwrap(); println!("{}", from_rust.get_ron()); // (x:1,y:2,z:3) // Trim leading/trailing whitespace and comments from a RawValue let padded = RawValue::from_ron(" /* comment */ 42 ").unwrap(); let trimmed = padded.trim(); assert_eq!(trimmed.get_ron(), "42"); } ``` -------------------------------- ### RON without unwrap_newtypes Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Illustrates the RON document structure required without the `unwrap_newtypes` extension. ```ron ( new_type: (5), ) ``` -------------------------------- ### Low-level Streaming Serializer Source: https://context7.com/ron-rs/ron/llms.txt The `Serializer` allows for low-level streaming serialization, enabling multiple values to be written to the same writer or for the underlying writer to be retrieved. ```APIDOC ## `ron::ser::Serializer` — Low-level streaming serializer `Serializer` is the low-level writer that powers all higher-level serialization functions. Construct it directly when you need to serialize multiple values into the same writer or extract the underlying writer afterwards. ```rust use ron::ser::{Serializer, PrettyConfig}; use ron::Options; use serde::Serialize; #[derive(Serialize)] struct Frame { id: u32, data: Vec } fn main() { let mut output = String::new(); // Compact serializer let mut ser = Serializer::new(&mut output, None).unwrap(); Frame { id: 1, data: vec![0xAA, 0xBB] }.serialize(&mut ser).unwrap(); println!("{}", output); // (id:1,data:[170,187]) // Retrieve the writer back let writer: &mut String = ser.into_inner(); // Pretty serializer with options let mut buf = String::new(); let opts = Options::default(); let mut pretty_ser = Serializer::with_options( &mut buf, Some(PrettyConfig::new().compact_arrays(true)), &opts, ).unwrap(); Frame { id: 2, data: vec![1, 2, 3] }.serialize(&mut pretty_ser).unwrap(); println!("{}", buf); // ( // id: 2, // data: [1,2,3], // ) } ``` ``` -------------------------------- ### RON Struct Grammar Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the syntax for unit, tuple, and named structs in RON. Ensure correct formatting for fields and values. ```ebnf struct = unit_struct | tuple_struct | named_struct; unit_struct = ident | "()"; tuple_struct = [ident], ws, tuple; named_struct = [ident], ws, "(", ws, [named_field, { comma, named_field }, [comma]], ")"; named_field = ident, ws, ":", ws, value; ``` -------------------------------- ### RON Optionals (Some and None) Source: https://github.com/ron-rs/ron/wiki/Specification Shows the RON representation for Rust's Option type, using `Some(Value)` for values and `None` for absence. ```rust Some(3.1415926535) ``` ```rust None ``` -------------------------------- ### Serialize Rust value to pretty-printed RON string with ron::ser::to_string_pretty Source: https://context7.com/ron-rs/ron/llms.txt Use `ron::ser::to_string_pretty` to serialize a value into a human-readable, indented RON string. A `PrettyConfig` can be used to control formatting options like depth limit, indentor, and array enumeration. Returns `Result`. ```rust use std::collections::HashMap; use serde::Serialize; use ron::ser::{to_string_pretty, PrettyConfig}; #[derive(Serialize)] struct Config { name: String, values: Vec, map: HashMap<&'static str, bool>, } fn main() { let config = Config { name: String::from("example"), values: vec![1, 2, 3], map: HashMap::from([("enabled", true), ("verbose", false)]), }; let pretty = PrettyConfig::new() .depth_limit(4) .indentor(" ") // 2-space indentation .separate_tuple_members(true) .enumerate_arrays(true) .struct_names(true) .compact_maps(false); let s = to_string_pretty(&config, pretty).unwrap(); println!("{}", s); // Config( // name: "example", // values: [ // /*[0]*/ 1, // /*[1]*/ 2, // /*[2]*/ 3, // ], // map: { // "enabled": true, // "verbose": false, // }, // ) } ``` -------------------------------- ### Serialize Rust value to compact RON string with ron::to_string Source: https://context7.com/ron-rs/ron/llms.txt Use `ron::to_string` to serialize any `serde::Serialize` type into a compact, single-line RON string. No newlines or indentation are added. Returns `Result`. ```rust use serde::Serialize; #[derive(Serialize)] struct Point { x: f32, y: f32, } #[derive(Serialize)] enum Color { Red, Rgb(u8, u8, u8), } fn main() { let pt = Point { x: 1.0, y: -3.5 }; let s = ron::to_string(&pt).unwrap(); println!("{}", s); // (x:1.0,y:-3.5) let color = Color::Rgb(255, 128, 0); let s = ron::to_string(&color).unwrap(); println!("{}", s); // Rgb(255,128,0) let unit_color = Color::Red; println!("{}", ron::to_string(&unit_color).unwrap()); // Red } ``` -------------------------------- ### Byte String Literals in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the syntax for standard and raw byte strings, similar to regular strings but not requiring UTF-8 validity. ```ebnf byte_string = byte_string_std | byte_string_raw; byte_string_std = "b\"", { no_double_quotation_marks | string_escape }, "\""; byte_string_raw = "br", string_raw_content; ``` -------------------------------- ### Tuple Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for tuples, enclosed in parentheses and containing comma-separated values. ```ebnf tuple = "(", [value, { comma, value }, [comma]], ")"; ``` -------------------------------- ### ron::ser::to_string_pretty Source: https://context7.com/ron-rs/ron/llms.txt Serializes a value into a human-readable, indented RON string using `PrettyConfig` for formatting control. Returns `Result`. ```APIDOC ## `ron::ser::to_string_pretty` — Serialize with pretty-printing Serializes a value into a human-readable, indented RON string using a `PrettyConfig` to control formatting options. Returns `Result`. ### Usage Example ```rust use std::collections::HashMap; use serde::Serialize; use ron::ser::{to_string_pretty, PrettyConfig}; #[derive(Serialize)] struct Config { name: String, values: Vec, map: HashMap<&'static str, bool>, } fn main() { let config = Config { name: String::from("example"), values: vec![1, 2, 3], map: HashMap::from([("enabled", true), ("verbose", false)]), }; let pretty = PrettyConfig::new() .depth_limit(4) .indentor(" ") // 2-space indentation .separate_tuple_members(true) .enumerate_arrays(true) .struct_names(true) .compact_maps(false); let s = to_string_pretty(&config, pretty).unwrap(); println!("{}", s); // Config( // name: "example", // values: [ // /*[0]*/ 1, // /*[1]*/ 2, // /*[2]*/ 3, // ], // map: { // "enabled": true, // "verbose": false, // }, // ) } ``` ``` -------------------------------- ### Value Types in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Lists all possible top-level value types that can be represented in a RON file. ```ebnf value = integer | byte | float | string | byte_string | char | bool | option | list | map | tuple | struct | enum_variant; ``` -------------------------------- ### Low-level Streaming Deserializer Source: https://context7.com/ron-rs/ron/llms.txt The `Deserializer<'de>` offers direct access to the RON parser, suitable for advanced use cases like partial input consumption, remaining byte checks, or integration with `DeserializeSeed`. ```APIDOC ## `ron::de::Deserializer` — Low-level streaming deserializer `Deserializer<'de>` provides direct access to the RON parser for advanced use-cases such as consuming partial input, checking remaining bytes, or integrating with `DeserializeSeed`. ```rust use ron::de::Deserializer; use ron::Options; use serde::Deserialize; fn main() { // Deserialize from a string slice let input = "(name: \"Alice\", age: 30)"; let mut de = Deserializer::from_str(input).unwrap(); #[derive(Debug, Deserialize)] struct Person { name: String, age: u32 } let person = Person::deserialize(&mut de).unwrap(); de.end().unwrap(); // assert no trailing characters println!("{:?}", person); // Person { name: "Alice", age: 30 } // Use with_options to apply extensions let opts = Options::default() .with_default_extension(ron::extensions::Extensions::IMPLICIT_SOME); let input2 = "(name: \"Bob\", age: 25)"; #[derive(Debug, Deserialize)] struct PersonOpt { name: String, age: Option } let mut de2 = Deserializer::from_str_with_options(input2, &opts).unwrap(); let p2 = PersonOpt::deserialize(&mut de2).unwrap(); println!("{:?}", p2); // PersonOpt { name: "Bob", age: Some(25) } // Inspect remaining unparsed input let partial = "(x: 1) extra stuff"; let mut de3 = Deserializer::from_str(partial).unwrap(); #[derive(Deserialize)] struct X { x: i32 } let _ = X::deserialize(&mut de3).unwrap(); println!("Remaining: {:?}", de3.remainder()); // " extra stuff" } ``` ``` -------------------------------- ### RON Tuple Struct Representation Source: https://github.com/ron-rs/ron/wiki/Specification Demonstrates tuple structs in RON, which can optionally include the type name before the values enclosed in parentheses. ```rust struct TupleStruct(f32, bool, String); ``` ```rust TupleStruct(3.4, false, "Hey there!") ``` ```rust ( 4.3, true, "Looks different, doesn't it?", ) ``` -------------------------------- ### List Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for lists, enclosed in square brackets and containing comma-separated values. ```ebnf list = "[", [value, { comma, value }, [comma]], "]"; ``` -------------------------------- ### ron::to_string Source: https://context7.com/ron-rs/ron/llms.txt Serializes a `serde::Serialize` type into a compact, single-line RON string. It returns a `Result` and does not include newlines or indentation. ```APIDOC ## `ron::to_string` — Serialize a Rust value into a compact RON string Serializes any `serde::Serialize` type to a compact, single-line RON string. Returns `Result`. No newlines or indentation are added; use `to_string_pretty` for human-readable output. ### Usage Example ```rust use serde::Serialize; #[derive(Serialize)] struct Point { x: f32, y: f32, } #[derive(Serialize)] enum Color { Red, Rgb(u8, u8, u8), } fn main() { let pt = Point { x: 1.0, y: -3.5 }; let s = ron::to_string(&pt).unwrap(); println!("{}", s); // (x:1.0,y:-3.5) let color = Color::Rgb(255, 128, 0); let s = ron::to_string(&color).unwrap(); println!("{}", s); // Rgb(255,128,0) let unit_color = Color::Red; println!("{}", ron::to_string(&unit_color).unwrap()); // Red } ``` ``` -------------------------------- ### Low-level RON Streaming Deserialization Source: https://context7.com/ron-rs/ron/llms.txt Employ `ron::de::Deserializer` for advanced deserialization scenarios, such as processing partial input, verifying remaining data, or integrating with `DeserializeSeed`. Supports custom options and inspection of unparsed input. ```Rust use ron::de::Deserializer; use ron::Options; use serde::Deserialize; fn main() { // Deserialize from a string slice let input = "(name: \"Alice\", age: 30)"; let mut de = Deserializer::from_str(input).unwrap(); #[derive(Debug, Deserialize)] struct Person { name: String, age: u32 } let person = Person::deserialize(&mut de).unwrap(); de.end().unwrap(); // assert no trailing characters println!("{:?}", person); // Person { name: "Alice", age: 30 } // Use with_options to apply extensions let opts = Options::default() .with_default_extension(ron::extensions::Extensions::IMPLICIT_SOME); let input2 = "(name: \"Bob\", age: 25)"; #[derive(Debug, Deserialize)] struct PersonOpt { name: String, age: Option } let mut de2 = Deserializer::from_str_with_options(input2, &opts).unwrap(); let p2 = PersonOpt::deserialize(&mut de2).unwrap(); println!("{:?}", p2); // PersonOpt { name: "Bob", age: Some(25) } // Inspect remaining unparsed input let partial = "(x: 1) extra stuff"; let mut de3 = Deserializer::from_str(partial).unwrap(); #[derive(Deserialize)] struct X { x: i32 } let _ = X::deserialize(&mut de3).unwrap(); println!("Remaining: {:?}", de3.remainder()); // " extra stuff" } ``` -------------------------------- ### Byte Literal Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for byte literals, enclosed in single quotes and prefixed with 'b'. ```ebnf byte = "b", "'", byte_content, "'"; byte_content = ascii | ("\", (escape_ascii | escape_byte)); ``` -------------------------------- ### Deserialize RON string to Rust value with ron::from_str Source: https://context7.com/ron-rs/ron/llms.txt Use `ron::from_str` to parse a RON-formatted string into a Rust type that implements `serde::Deserialize`. Errors include precise line/column information. This is the primary entry point for reading RON data. ```rust use serde::Deserialize; use std::collections::HashMap; #[derive(Debug, Deserialize)] struct Config { boolean: bool, float: f32, map: HashMap, nested: Nested, option: Option, tuple: (u32, u32), } #[derive(Debug, Deserialize)] struct Nested { a: String, b: char, } fn main() { let ron_str = r#"( boolean: true, float: 8.2, // Maps use curly braces with arbitrary key types map: { 1: '1', 2: '4', 3: '9', }, nested: Nested( // struct name is optional a: "Decode me!", b: 'z', ), option: Some("hello"), tuple: (3, 7), // trailing commas are allowed )"#; let config: Config = ron::from_str(ron_str).unwrap(); println!("Config: {:?}", config); // Config: Config { boolean: true, float: 8.2, map: {1: '1', 2: '4', 3: '9'}, // nested: Nested { a: "Decode me!", b: 'z' }, option: Some("hello"), tuple: (3, 7) } } ``` -------------------------------- ### Raw String Literal in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the syntax for raw strings, prefixed with 'r' and allowing content without standard escape interpretations, with context-sensitive delimiters. ```ebnf string_raw = "r", string_raw_content; string_raw_content = ("#", string_raw_content, "#") | "\"", { unicode_non_greedy }, "\""; ``` -------------------------------- ### Map Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for maps (key-value pairs), enclosed in curly braces with comma-separated entries. ```ebnf map = "{", [map_entry, { comma, map_entry }, [comma]], "}"; map_entry = value, ws, ":", ws, value; ``` -------------------------------- ### Standard String Literal in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the syntax for standard strings, enclosed in double quotes, allowing escape sequences. ```ebnf string = string_std | string_raw; string_std = "\"", { no_double_quotation_marks | string_escape }, "\""; ``` -------------------------------- ### Enable explicit_struct_names Extension Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md This extension emits struct names during serialization and requires them during deserialization. ```rust use ron::extensions::Extensions; use ron::options::Options; // Setup the options let options = Options::default().with_default_extension(Extensions::EXPLICIT_STRUCT_NAMES); // Retrieve the contents of the file let file_contents: &str = /* ... */; // Parse the file's contents let foo: Foo = options.from_str(file_contents)?; ``` -------------------------------- ### Optional Type Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for optional types, including 'None' and 'Some' with a contained value. ```ebnf option = "None" | option_some; option_some = "Some", ws, "(", ws, value, ws, ")"; ``` -------------------------------- ### Deserialize RON from a byte slice Source: https://context7.com/ron-rs/ron/llms.txt Use `from_bytes` to deserialize RON from a `&[u8]` byte slice. It validates UTF-8 encoding and returns a `SpannedResult` with location-aware error information. ```rust use serde::Deserialize; use ron::de::from_bytes; #[derive(Debug, Deserialize, PartialEq)] struct Record { id: u64, label: String, } fn main() { let data: &[u8] = b"(id: 42, label: \"hello\")"; let record: Record = from_bytes(data).unwrap(); assert_eq!(record, Record { id: 42, label: String::from("hello") }); println!("{:?}", record); // Record { id: 42, label: "hello" } // Invalid UTF-8 produces a SpannedError with location info let bad: &[u8] = b"(id: 1, label: \xff\xff)"; let err = from_bytes::(bad).unwrap_err(); println!("Error at {}: {}", err.span, err.code); // Error at 1:16: invalid utf-8 sequence of 1 bytes from index 0 } ``` -------------------------------- ### Whitespace and Comments in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Specifies the allowed whitespace characters and the syntax for single-line and nested block comments. ```ebnf ws = { ws_single | comment }; ws_single = "\n" | "\t" | "\r" | " " | U+000B | U+000C | U+0085 | U+200E | U+200F | U+2028 | U+2029; comment = ["//", { no_newline }, "\n"] | ["/*", nested_block_comment, "*/"]; nested_block_comment = { ? any characters except "/*" or "*/" ? }, [ "/*", nested_block_comment, "*/", nested_block_comment ]; ``` -------------------------------- ### Deserialize RON from an io::Read source Source: https://context7.com/ron-rs/ron/llms.txt Use `from_reader` to deserialize RON data from any `std::io::Read` implementor. Available with the `std` feature. Returns `SpannedResult`. ```rust use std::{collections::HashMap, fs::File}; use ron::de::from_reader; use serde::Deserialize; #[derive(Debug, Deserialize)] struct AppConfig { version: u32, name: String, tags: Vec, } fn main() { // Read from a file let f = File::open("config.ron").expect("Failed to open config.ron"); let config: AppConfig = match from_reader(f) { Ok(cfg) => cfg, Err(e) => { eprintln!("Parse error: {}", e); // e.g. "config.ron:3:5: Expected closing `)`" std::process::exit(1); } }; println!("{:?}", config); // Read from an in-memory cursor (useful for testing) use std::io::Cursor; let data = b"(version: 1, name: \"test\", tags: [\"a\", \"b\"])"; let cursor = Cursor::new(data); let cfg: AppConfig = from_reader(cursor).unwrap(); println!("{:?}", cfg); } ``` -------------------------------- ### RON Map Representation Source: https://github.com/ron-rs/ron/wiki/Specification Maps in RON are enclosed in curly braces `{` and `}`. Keys and values are separated by colons, and pairs by commas. Key uniqueness is not enforced by the RON format itself. ```rust { "monkey": "mesh/suzanne.obj", } ``` ```rust { 'a': 97, 'd': 100, } ``` -------------------------------- ### RON Struct with Named Fields Source: https://github.com/ron-rs/ron/wiki/Specification Represents structs with named fields, optionally prefixed by the type name. Trailing commas are permitted. ```rust (field_name: 3.4, b: 'b', ) ``` ```rust (a: false,) ``` ```rust Vector2( x: 42.0, y: 5.0, ) ``` -------------------------------- ### String Escape Sequences in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Specifies the allowed escape sequences within standard strings, including ASCII, byte, and Unicode escapes. ```ebnf string_escape = "\", (escape_ascii | escape_byte | escape_unicode); escape_ascii = "'" | "\"" | "\\" | "n" | "r" | "t" | "0"; escape_byte = "x", digit_hexadecimal, digit_hexadecimal; escape_unicode = "u", digit_hexadecimal, [digit_hexadecimal, [digit_hexadecimal, [digit_hexadecimal, [digit_hexadecimal, [digit_hexadecimal]]]]]; ``` -------------------------------- ### Boolean Literal Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for boolean literals, which are 'true' or 'false'. ```ebnf bool = "true" | "false"; ``` -------------------------------- ### Comma Definition in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the syntax for a comma, including surrounding whitespace. ```ebnf comma = ws, ",", ws; ``` -------------------------------- ### RON Enum Variant Grammar Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Specifies the syntax for different types of enum variants: unit, tuple, and named. Pay attention to the structure for named variants. ```ebnf enum_variant = enum_variant_unit | enum_variant_tuple | enum_variant_named; enum_variant_unit = ident; enum_variant_tuple = ident, ws, tuple; enum_variant_named = ident, ws, "(", [named_field, { comma, named_field }, [comma]], ")"; ``` -------------------------------- ### Enable implicit_some Extension Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Add this attribute to automatically convert any value to `Some(value)` when the deserialized type requires it. ```rust #![enable(implicit_some)] ( value: 5, ) ``` -------------------------------- ### Enable unwrap_variant_newtypes Extension Source: https://github.com/ron-rs/ron/blob/master/docs/extensions.md Add this attribute to automatically unwrap newtype enum variants. ```rust #![enable(unwrap_newtypes)] ( variant: A(a: 4, b: true), ) ``` -------------------------------- ### RON Empty Struct Representation Source: https://github.com/ron-rs/ron/wiki/Specification Shows the RON representation of an empty struct, which uses braces. Note the deserialized form uses parentheses. ```rust struct Empty {} ``` ```rust Empty() ``` -------------------------------- ### Unsigned Number Formats in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Specifies the different formats for unsigned numbers: binary, octal, hexadecimal, and decimal, including digit separators. ```ebnf unsigned = unsigned_binary | unsigned_octal | unsigned_hexadecimal | unsigned_decimal; unsigned_binary = "0b", digit_binary, { digit_binary | "_" }; unsigned_octal = "0o", digit_octal, { digit_octal | "_" }; unsigned_hexadecimal = "0x", digit_hexadecimal, { digit_hexadecimal | "_" }; unsigned_decimal = digit, { digit | "_" }; ``` -------------------------------- ### Float Literal Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF structure for floating-point numbers, including special values like 'inf' and 'NaN', and optional suffixes. ```ebnf float = ["+" | "-"], ("inf" | "NaN" | float_num), [float_suffix]; float_num = (float_int | float_std | float_frac), [float_exp]; float_int = digit, { digit | "_" }; float_std = digit, { digit | "_" }, ".", [digit, { digit | "_" }]; float_frac = ".", digit, { digit | "_" }; float_exp = ("e" | "E"), ["+" | "-"], { digit | "_" }, digit, { digit | "_" }; float_suffix = "f", ("32", "64"); ``` -------------------------------- ### RON List Representation Source: https://github.com/ron-rs/ron/wiki/Specification RON represents lists (like Vec or slices) using square brackets `[` and `]`, with elements separated by commas. Lists are homogeneous. ```rust [1, 2, 3,] ``` ```rust [ 22, 26, 34, 41, 46, 56, ] ``` -------------------------------- ### RON Identifier Grammar Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the rules for standard and raw identifiers in RON. Raw identifiers are prefixed with 'r#' and can include specific characters. ```ebnf ident = ident_std | ident_raw; ident_std = ident_std_first, { ident_std_rest }; ident_std_first = XID_Start | "_"; ident_std_rest = XID_Continue; ident_raw = "r", "#", ident_raw_rest, { ident_raw_rest }; ident_raw_rest = ident_std_rest | "." | "+" | "-"; ``` -------------------------------- ### Character Literal Syntax in EBNF Source: https://github.com/ron-rs/ron/blob/master/docs/grammar.md Defines the EBNF syntax for character literals, enclosed in single quotes. ```ebnf char = "'", (no_apostrophe | "\\" | "\'" ), "'"; ```