### Initialize YAML Mapping Start Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Initializes a YAML mapping start event, handling tag and style. Errors during initialization are checked. ```rust Event::MappingStart(mut mapping) => { let anchor = ptr::null(); let tag = mapping.tag.as_mut().map_or_else(ptr::null, |tag| { tag.push('\0'); tag.as_ptr() }); let implicit = tag.is_null(); let style = sys::YAML_ANY_MAPPING_STYLE; sys::yaml_mapping_start_event_initialize( sys_event, anchor, tag, implicit, style, ) } ``` -------------------------------- ### Basic YAML Serialization Example Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates serializing a `BTreeMap` into YAML format using `serde_norway::Serializer`. This example shows how to create a serializer, serialize data, and verify the output. ```rust use anyhow::Result; use serde::Serialize; use std::collections::BTreeMap; fn main() -> Result<()> { let mut buffer = Vec::new(); let mut ser = serde_norway::Serializer::new(&mut buffer); let mut object = BTreeMap::new(); object.insert("k", 107); object.serialize(&mut ser)?; object.insert("J", 74); object.serialize(&mut ser)?; assert_eq!(buffer, b"k: 107\n---\nJ: 74\nk: 107\n"); Ok(()) } ``` -------------------------------- ### Serialize Tuple Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Initiates the serialization of a tuple by emitting a sequence start marker and returning the serializer itself to handle tuple elements. ```rust fn serialize_tuple(self, _len: usize) -> Result { self.emit_sequence_start()?; Ok(self) ``` -------------------------------- ### Serialize Sequence Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initiates the serialization of a sequence or tuple by emitting the start marker. This is called before serializing the elements. ```rust fn serialize_seq(self, _len: Option) -> Result { self.emit_sequence_start()?; Ok(self) } ``` ```rust fn serialize_tuple(self, _len: usize) -> Result { self.emit_sequence_start()?; Ok(self) } ``` ```rust fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { self.emit_sequence_start()?; Ok(self) } ``` -------------------------------- ### Initialize YAML Sequence Start Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Initializes a YAML sequence start event, handling tag and style. Errors during initialization are checked. ```rust Event::SequenceStart(mut sequence) => { let anchor = ptr::null(); let tag = sequence.tag.as_mut().map_or_else(ptr::null, |tag| { tag.push('\0'); tag.as_ptr() }); let implicit = tag.is_null(); let style = sys::YAML_ANY_SEQUENCE_STYLE; sys::yaml_sequence_start_event_initialize( sys_event, anchor, tag, implicit, style, ) } ``` -------------------------------- ### Flush pending mapping start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search= Checks the current state and emits a `MappingStart` event if the state indicates a pending mapping that needs to be started. It transitions the state to `NothingInParticular` after emitting. ```rust fn flush_mapping_start(&mut self) -> Result<()> { if let State::CheckForTag = self.state { self.state = State::NothingInParticular; self.emit_mapping_start()?; } else if let State::CheckForDuplicateTag = self.state { ``` -------------------------------- ### Serialize Struct Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initiates the serialization of a struct by emitting the start marker for a mapping. This is called before serializing the struct's fields. ```rust fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { self.emit_mapping_start()?; } ``` -------------------------------- ### Emit YAML Mapping Start Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Emits the start of a YAML mapping, optionally with a tag. It ensures any pending mapping is flushed and the document has started. ```rust fn emit_mapping_start(&mut self) -> Result<()> { self.flush_mapping_start()?; self.value_start()?; let tag = self.take_tag(); self.emitter.emit(Event::MappingStart(Mapping { tag }))?; Ok(()) } ``` -------------------------------- ### Value Search Examples Source: https://docs.rs/serde_norway/latest/serde_norway/value/enum.Value.html?search= Demonstrates various ways to search within the Value enum. These examples show how to specify search targets like standard library types or type transformations. ```APIDOC ## Value Search Examples ### Description Provides examples of search queries that can be used to find specific types or patterns within the Value enum. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### MappingStart Struct Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/parser.rs.html?search=std%3A%3Avec Represents the start of a YAML mapping, including an optional anchor and tag. ```APIDOC ## MappingStart Struct ### Description Represents the start of a YAML mapping. It can optionally have an anchor and a tag. ### Fields * `anchor`: `Option` - An optional anchor for the mapping. * `tag`: `Option` - An optional tag for the mapping. ``` -------------------------------- ### Serialize Tuple Struct Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Initiates the serialization of a tuple struct by emitting a sequence start marker and returning the serializer itself to handle tuple struct elements. ```rust fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { self.emit_sequence_start()?; Ok(self) ``` -------------------------------- ### Serialize Tuple Start - Serde Norway Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=std%3A%3Avec Initiates the serialization of a tuple. This is similar to sequence serialization, emitting the start of a YAML sequence. ```rust fn serialize_tuple(self, _len: usize) -> Result { self.emit_sequence_start()?; Ok(self) } ``` -------------------------------- ### Emit YAML Sequence Start Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Emits the start of a YAML sequence, optionally with a tag. It ensures any pending mapping is flushed and the document has started. ```rust fn emit_sequence_start(&mut self) -> Result<()> { self.flush_mapping_start()?; self.value_start()?; let tag = self.take_tag(); self.emitter.emit(Event::SequenceStart(Sequence { tag }))?; Ok(()) } ``` -------------------------------- ### SequenceStart Struct Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/parser.rs.html?search=std%3A%3Avec Represents the start of a YAML sequence, including an optional anchor and tag. ```APIDOC ## SequenceStart Struct ### Description Represents the start of a YAML sequence. It can optionally have an anchor and a tag. ### Fields * `anchor`: `Option` - An optional anchor for the sequence. * `tag`: `Option` - An optional tag for the sequence. ``` -------------------------------- ### Flush Pending Mapping Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html If the current state is `CheckForTag`, this method emits a `MappingStart` event and transitions the state to `NothingInParticular`. This is used to ensure mappings are correctly started before emitting other events. ```rust fn flush_mapping_start(&mut self) -> Result<()> { if let State::CheckForTag = self.state { self.state = State::NothingInParticular; self.emit_mapping_start()?; } Ok(()) } ``` -------------------------------- ### Serialize Tuple Struct Start - Serde Norway Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=std%3A%3Avec Initiates the serialization of a tuple struct. It emits the start of a YAML sequence, treating the tuple struct as a sequence. ```rust fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { self.emit_sequence_start()?; Ok(self) } ``` -------------------------------- ### Mark Start of a Value Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Increments the depth counter and emits `DocumentStart` if this is the top-level value. ```rust fn value_start(&mut self) -> Result<()> { if self.depth == 0 { self.emitter.emit(Event::DocumentStart)?; } self.depth += 1; Ok(()) } ``` -------------------------------- ### Indexing YAML Sequences and Mappings with get() Source: https://docs.rs/serde_norway/latest/serde_norway/enum.Value.html Demonstrates how to access elements within YAML sequences (using usize) and mappings (using string keys) with the `get` method. Returns `None` if the index is invalid or the type does not match. ```rust use serde_norway::Value; let object: Value = serde_norway::from_str(r#"{ A: 65, B: 66, C: 67 }"#)?; let x = object.get("A").unwrap(); assert_eq!(x, 65); let sequence: Value = serde_norway::from_str(r#"[ "A", "B", "C" ]"#)?; let x = sequence.get(2).unwrap(); assert_eq!(x, &Value::String("C".into())); assert_eq!(sequence.get("A"), None); ``` -------------------------------- ### Example Usage of Serializer Source: https://docs.rs/serde_norway/latest/serde_norway/struct.Serializer.html Demonstrates how to create a `Serializer`, serialize a `BTreeMap` with multiple entries, and assert the resulting YAML output. Requires `anyhow` and `serde` crates. ```rust use anyhow::Result; use serde::Serialize; use std::collections::BTreeMap; fn main() -> Result<()> { let mut buffer = Vec::new(); let mut ser = serde_norway::Serializer::new(&mut buffer); let mut object = BTreeMap::new(); object.insert("k", 107); object.serialize(&mut ser)?; object.insert("J", 74); object.serialize(&mut ser)?; assert_eq!(buffer, b"k: 107\n---\nJ: 74\nk: 107\n"); Ok(()) } ``` -------------------------------- ### Serialization and Deserialization Examples Source: https://docs.rs/serde_norway/latest/index.html Demonstrates basic serialization to YAML string and deserialization back to a Rust type using `to_string` and `from_str`. ```APIDOC ## Functions ### `to_string` Serialize the given data structure as a String of YAML. ### `from_str` Deserialize an instance of type `T` from a string of YAML text. ``` -------------------------------- ### Parser Initialization and Event Parsing Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/parser.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a new `Parser` instance with input data and how to retrieve the next `Event` from the parser. It also includes error handling for parsing operations. ```APIDOC ## Parser Represents a YAML parser that processes input data to generate events. ### Methods #### `new(input: Cow<'input, [u8]>) -> Parser<'input>` Creates a new `Parser` instance initialized with the provided input data. - **input** (`Cow<'input, [u8]>`): The input data to be parsed, represented as a byte slice. #### `next(&mut self) -> Result<(Event<'input>, Mark)>` Parses and returns the next `Event` from the input stream along with its starting `Mark`. - **Returns**: A `Result` containing a tuple of `Event` and `Mark` on success, or an `Error` on failure. ### Events #### `Event<'input>` An enum representing the different types of YAML events that can be parsed. - `StreamStart` - `StreamEnd` - `DocumentStart` - `DocumentEnd` - `Alias(Anchor)` - `Scalar(Scalar<'input>)` - `SequenceStart(SequenceStart)` - `SequenceEnd` - `MappingStart(MappingStart)` - `MappingEnd` ### Data Structures #### `Scalar<'input>` Represents a scalar value in YAML. - **anchor**: `Option` - The anchor associated with the scalar. - **tag**: `Option` - The tag associated with the scalar. - **value**: `Box<[u8]>` - The byte slice representing the scalar's value. - **style**: `ScalarStyle` - The style of the scalar (e.g., Plain, SingleQuoted). - **repr**: `Option<&'input [u8]>` - The raw byte representation of the scalar in the input. #### `SequenceStart` Represents the start of a YAML sequence. - **anchor**: `Option` - The anchor associated with the sequence. - **tag**: `Option` - The tag associated with the sequence. #### `MappingStart` Represents the start of a YAML mapping. - **anchor**: `Option` - The anchor associated with the mapping. - **tag**: `Option` - The tag associated with the mapping. #### `Anchor` Represents an anchor in YAML. - **Inner value**: `Box<[u8]>` - The byte slice representing the anchor name. #### `ScalarStyle` An enum representing the different styles of scalar values. - `Plain` - `SingleQuoted` - `DoubleQuoted` - `Literal` - `Folded` ``` -------------------------------- ### Serialize Sequence Start - Serde Norway Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=std%3A%3Avec Initiates the serialization of a sequence (like Vec or arrays). It emits the start of a YAML sequence. ```rust fn serialize_seq(self, _len: Option) -> Result { self.emit_sequence_start()?; Ok(self) } ``` -------------------------------- ### Emitter::new Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Constructs a new Emitter instance. It initializes the libyaml emitter, sets Unicode and width, and configures the output handler. ```APIDOC ## Emitter::new ### Description Constructs a new `Emitter` instance, setting up the underlying libyaml emitter with Unicode support and a default width. It also configures a custom write handler for output. ### Method `pub fn new(write: Box) -> Emitter<'a>` ### Parameters * `write`: A boxed implementation of `io::Write` trait for the output destination. ``` -------------------------------- ### Serialize Tuple Variant Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html?search=u32+-%3E+bool Initiates the serialization of a tuple variant of an enum. It sets the state to `FoundTag` and then starts emitting the sequence. ```rust fn serialize_tuple_variant( self, _enm: &'static str, _idx: u32, variant: &'static str, _len: usize, ) -> Result { if let State::FoundTag(_) = self.state { return Err(error::new(ErrorImpl::SerializeNestedEnum)); } self.state = State::FoundTag(variant.to_owned()); self.emit_sequence_start()?; Ok(self) } ``` -------------------------------- ### Initialize libyaml Emitter Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Creates a new Emitter instance, setting up the libyaml emitter and configuring it for UTF-8 output and unlimited line width. It requires a mutable reference to an object implementing `io::Write` for output. ```rust pub fn new(write: Box) -> Emitter<'a> { let owned = Owned::::new_uninit(); let pin = unsafe { let emitter = addr_of_mut!((*owned.ptr).sys); if sys::yaml_emitter_initialize(emitter).fail { panic!("malloc error: {}", libyaml::Error::emit_error(emitter)); } sys::yaml_emitter_set_unicode(emitter, true); sys::yaml_emitter_set_width(emitter, -1); addr_of_mut!((*owned.ptr).write).write(write); addr_of_mut!((*owned.ptr).write_error).write(None); sys::yaml_emitter_set_output(emitter, write_handler, owned.ptr.cast()); Owned::assume_init(owned) }; Emitter { pin } } ``` -------------------------------- ### Emitter::new Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html Initializes a new YAML emitter. It takes a writer that implements `io::Write` and sets up the underlying libyaml emitter, configuring it for UTF-8 output and disabling line wrapping. ```APIDOC ## Emitter::new ### Description Initializes a new YAML emitter. It takes a writer that implements `io::Write` and sets up the underlying libyaml emitter, configuring it for UTF-8 output and disabling line wrapping. ### Signature ```rust pub fn new(write: Box) -> Emitter<'a> ``` ### Parameters * `write`: A boxed writer implementing `io::Write` where the YAML output will be sent. ``` -------------------------------- ### Get Mutable Reference to Sequence Source: https://docs.rs/serde_norway/latest/src/serde_norway/value/mod.rs.html?search=std%3A%3Avec Use `as_sequence_mut` to get a mutable reference to the sequence if the Value is a sequence. Allows modification of the sequence. ```rust # use serde_norway::{Value, Number}; let mut v: Value = serde_norway::from_str("[1]").unwrap(); let s = v.as_sequence_mut().unwrap(); s.push(Value::Number(Number::from(2))); assert_eq!(s, &vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))]); ``` ```rust # use serde_norway::Value; let mut v: Value = serde_norway::from_str("false").unwrap(); assert_eq!(v.as_sequence_mut(), None); ``` -------------------------------- ### Get Mutable Mapping Reference Source: https://docs.rs/serde_norway/latest/serde_norway/enum.Value.html Use `as_mapping_mut` to get a mutable reference to a mapping if the Value is of that type. Returns `None` otherwise. ```rust let mut v: Value = serde_norway::from_str("a: 42").unwrap(); let m = v.as_mapping_mut().unwrap(); m.insert(Value::String("b".into()), Value::Number(Number::from(21))); let mut expected = Mapping::new(); expected.insert(Value::String("a".into()), Value::Number(Number::from(42))); expected.insert(Value::String("b".into()), Value::Number(Number::from(21))); assert_eq!(m, &expected); ``` ```rust let mut v: Value = serde_norway::from_str("false").unwrap(); assert_eq!(v.as_mapping_mut(), None); ``` -------------------------------- ### Emitter Initialization and Usage Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search=std%3A%3Avec Demonstrates how to initialize an Emitter and emit various YAML events. The Emitter is responsible for writing YAML output to an io::Write trait object. ```APIDOC ## Emitter ### Description The `Emitter` struct provides an interface for emitting YAML data. It wraps a `libyaml` emitter and handles the output to a provided `io::Write` implementation. ### Methods * **`new(write: Box) -> Emitter<'a>`** * Initializes a new `Emitter` instance. * Takes ownership of a `Box` for output. * Panics if `libyaml` initialization fails (e.g., due to memory allocation errors). * Configures the emitter for UTF-8 encoding and sets the output width to unlimited (-1). * **`emit(&mut self, event: Event) -> Result<(), Error>`** * Emits a single `Event` to the configured output. * Returns `Ok(())` on success or an `Error` if the emission fails. ### Event Types The `Event` enum represents different YAML structures that can be emitted: * `StreamStart` * `StreamEnd` * `DocumentStart` * `DocumentEnd` * `Scalar(Scalar<'a>)` * `SequenceStart(Sequence)` * `SequenceEnd` * `MappingStart(Mapping)` * `MappingEnd` ### Data Structures * **`Scalar<'a>`**: Represents a scalar value. * `tag`: An optional `String` for the scalar's tag. * `value`: A string slice (`&'a str`) containing the scalar's value. * `style`: A `ScalarStyle` enum indicating how the scalar should be represented (e.g., `Plain`, `SingleQuoted`, `Literal`). * **`Sequence`**: Represents the start of a sequence. * `tag`: An optional `String` for the sequence's tag. * **`Mapping`**: Represents the start of a mapping. * `tag`: An optional `String` for the mapping's tag. ### Error Handling The `Emitter` can return an `Error` enum which can be either: * `Libyaml(libyaml::error::Error)`: An error originating from the underlying `libyaml` library. * `Io(io::Error)`: An I/O error encountered during writing. ``` -------------------------------- ### Check and Get Mapping Reference Source: https://docs.rs/serde_norway/latest/serde_norway/enum.Value.html Use `as_mapping` to get an immutable reference to the mapping if the `Value` is a mapping. Returns `None` otherwise. ```rust let v: Value = serde_norway::from_str("a: 42").unwrap(); let mut expected = Mapping::new(); expected.insert(Value::String("a".into()),Value::Number(Number::from(42))); assert_eq!(v.as_mapping(), Some(&expected)); ``` ```rust let v: Value = serde_norway::from_str("false").unwrap(); assert_eq!(v.as_mapping(), None); ``` -------------------------------- ### Check and Get Sequence Reference Source: https://docs.rs/serde_norway/latest/serde_norway/enum.Value.html Use `as_sequence` to get an immutable reference to the sequence if the `Value` is a sequence. Returns `None` otherwise. ```rust let v: Value = serde_norway::from_str("[1, 2]").unwrap(); assert_eq!(v.as_sequence(), Some(&vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))])); ``` ```rust let v: Value = serde_norway::from_str("false").unwrap(); assert_eq!(v.as_sequence(), None); ``` -------------------------------- ### take Source: https://docs.rs/serde_norway/latest/serde_norway/mapping/struct.IntoIter.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that yields the first `n` elements. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters * `n`: The maximum number of elements to yield. ``` -------------------------------- ### Example Usage of to_value Source: https://docs.rs/serde_norway/latest/serde_norway/fn.to_value.html?search= Demonstrates converting a string literal to a `serde_norway::Value` and asserting its correctness. This shows a basic successful conversion. ```rust let val = serde_norway::to_value("s").unwrap(); assert_eq!(val, Value::String("s".to_owned())); ``` -------------------------------- ### Get entry for YAML map Source: https://docs.rs/serde_norway/latest/src/serde_norway/mapping.rs.html Use `Mapping::entry()` to get an `Entry` enum, which allows for conditional insertion or manipulation of map values. ```rust pub fn entry(&mut self, k: Value) -> Entry { match self.map.entry(k) { indexmap::map::Entry::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }), indexmap::map::Entry::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }), } } ``` -------------------------------- ### Serialize Struct in Rust Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Implements the `serialize_struct` method for the `Serializer`. This is called when a struct needs to be serialized. It starts by emitting the mapping start and returns the serializer itself. ```rust fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { self.emit_mapping_start()?; Ok(self) } ``` -------------------------------- ### Parser::new Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/parser.rs.html?search=std%3A%3Avec Initializes a new YAML parser with the given input. It sets up the parser, configures UTF-8 encoding, and prepares it to read from the input string. ```APIDOC ## Parser::new ### Description Initializes a new YAML parser with the given input. It sets up the parser, configures UTF-8 encoding, and prepares it to read from the input string. ### Signature ```rust pub fn new(input: Cow<'input, [u8]>) -> Parser<'input> ``` ### Parameters * `input` - A `Cow<'input, [u8]>` representing the YAML input data. ``` -------------------------------- ### Creating Vec from Raw Parts with Allocator Source: https://docs.rs/serde_norway/latest/serde_norway/type.Sequence.html?search= Demonstrates creating a `Vec` from a raw pointer, length, capacity, and an allocator. This is a nightly-only API and requires careful adherence to safety invariants. ```rust #![feature(allocator_api)] use std::alloc::System; let mut v = Vec::with_capacity_in(3, System); v.push(1); v.push(2); v.push(3); // Deconstruct the vector into parts. let (p, len, cap, alloc) = v.into_parts_with_alloc(); unsafe { // Overwrite memory with 4, 5, 6 for i in 0..len { p.add(i).write(4 + i); } // Put everything back together into a Vec let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone()); assert_eq!(rebuilt, [4, 5, 6]); } ``` -------------------------------- ### Getting Boolean Value Source: https://docs.rs/serde_norway/latest/src/serde_norway/value/mod.rs.html?search=u32+-%3E+bool Extracts the boolean value from a Serde Norway Value if it is a boolean, returning None otherwise. This is the primary way to get a boolean value. ```rust use serde_norway::Value; let v: Value = serde_norway::from_str("true").unwrap(); assert_eq!(v.as_bool(), Some(true)); ``` ```rust use serde_norway::Value; let v: Value = serde_norway::from_str("42").unwrap(); assert_eq!(v.as_bool(), None); ``` -------------------------------- ### Emit YAML Scalar Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Emits a YAML scalar event, optionally including a tag. It first flushes any pending mapping start and ensures the document has started. ```rust fn emit_scalar(&mut self, mut scalar: Scalar) -> Result<()> { self.flush_mapping_start()?; if let Some(tag) = self.take_tag() { scalar.tag = Some(tag); } self.value_start()?; self.emitter.emit(Event::Scalar(scalar))?; self.value_end() } ``` -------------------------------- ### Parser Initialization and Event Parsing Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/parser.rs.html?search= Provides methods to create a new `Parser` instance with input data and to retrieve the next `Event` from the input stream. It handles the underlying libyaml C API calls for parsing. ```APIDOC ## `Parser::new` ### Description Initializes a new `Parser` instance with the provided input data. It sets up the underlying libyaml parser and configures it for UTF-8 encoding. ### Method `pub fn new(input: Cow<'input, [u8]>) -> Parser<'input>` ### Parameters * `input` (Cow<'input, [u8]>) - The input data to be parsed, as a byte slice. ## `Parser::next` ### Description Retrieves the next `Event` from the parser's input stream. This method advances the parser state and returns the next YAML event along with its starting mark. ### Method `pub fn next(&mut self) -> Result<(Event<'input>, Mark)>` ### Returns - `Result<(Event<'input>, Mark)>` - An `Ok` variant containing a tuple of the next `Event` and its `Mark`, or an `Err` variant if a parsing error occurred. ``` -------------------------------- ### Check and Get Mutable Sequence Reference Source: https://docs.rs/serde_norway/latest/serde_norway/enum.Value.html Use `as_sequence_mut` to get a mutable reference to the sequence if the `Value` is a sequence. This allows modification of the sequence. Returns `None` otherwise. ```rust let mut v: Value = serde_norway::from_str("[1]").unwrap(); let s = v.as_sequence_mut().unwrap(); s.push(Value::Number(Number::from(2))); assert_eq!(s, &vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))]); ``` ```rust let mut v: Value = serde_norway::from_str("false").unwrap(); assert_eq!(v.as_sequence_mut(), None); ``` -------------------------------- ### Creating a Vec from External Allocation Source: https://docs.rs/serde_norway/latest/serde_norway/type.Sequence.html This example shows how to create a `Vec` using memory allocated manually with `std::alloc::alloc`. It demonstrates writing a value to the allocated memory and then constructing the `Vec` using `Vec::from_raw_parts`, specifying the element type, initial length, and capacity. This is useful when interfacing with C code or custom allocators. ```rust use std::alloc::{alloc, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = alloc(layout).cast::(); if mem.is_null() { return; } mem.write(1_000_000); Vec::from_raw_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### pub fn from_parts_in Source: https://docs.rs/serde_norway/latest/serde_norway/type.Sequence.html?search= Creates a `Vec` directly from a `NonNull` pointer, a length, a capacity, and an allocator. This is an experimental nightly-only API. ```APIDOC ## pub fn from_parts_in ### Description Creates a `Vec` directly from a `NonNull` pointer, a length, a capacity, and an allocator. ### Method `from_parts_in` ### Parameters - `ptr` (*NonNull*): The non-null pointer to the allocated memory. - `length` (*usize*): The number of elements currently in the vector. - `capacity` (*usize*): The total capacity of the allocated memory. - `alloc` (*A*): The allocator used for the memory. ### Safety This function is highly unsafe and requires careful adherence to several invariants regarding the pointer, its allocation, size, alignment, and initialization of elements. Violating these invariants can lead to memory corruption or undefined behavior. ### Request Example ```rust #![feature(allocator_api)] use std::alloc::System; let mut v = Vec::with_capacity_in(3, System); v.push(1); v.push(2); v.push(3); // Deconstruct the vector into parts. let (p, len, cap, alloc) = v.into_parts_with_alloc(); unsafe { // Overwrite memory with 4, 5, 6 for i in 0..len { p.add(i).write(4 + i); } // Put everything back together into a Vec let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone()); assert_eq!(rebuilt, [4, 5, 6]); } ``` ### Using memory that was allocated elsewhere: ```rust #![feature(allocator_api)] use std::alloc::{AllocError, Allocator, Global, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = match Global.allocate(layout) { Ok(mem) => mem.cast::(), Err(AllocError) => return, }; mem.write(1_000_000); Vec::from_parts_in(mem, 1, 16, Global) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` ``` -------------------------------- ### Initialize libyaml Parser in Rust Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/parser.rs.html Creates a new YAML parser instance, initializes the underlying libyaml parser, sets the encoding to UTF-8, and configures the input string. Panics on memory allocation errors. ```rust pub fn new(input: Cow<'input, [u8]>) -> Parser<'input> { let owned = Owned::::new_uninit(); let pin = unsafe { let parser = addr_of_mut!((*owned.ptr).sys); if sys::yaml_parser_initialize(parser).fail { panic!("malloc error: {}", Error::parse_error(parser)); } sys::yaml_parser_set_encoding(parser, sys::YAML_UTF8_ENCODING); sys::yaml_parser_set_input_string(parser, input.as_ptr(), input.len() as u64); addr_of_mut!((*owned.ptr).input).write(input); Owned::assume_init(owned) }; Parser { pin } } ``` -------------------------------- ### Initialize YAML Mapping End Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Initializes a YAML mapping end event. ```rust Event::MappingEnd => sys::yaml_mapping_end_event_initialize(sys_event) ``` -------------------------------- ### Indexing into Value with get() Source: https://docs.rs/serde_norway/latest/serde_norway/value/enum.Value.html?search=u32+-%3E+bool Use the `get` method to index into YAML sequences or maps. It returns `None` if the index type doesn't match the value type or if the key/index doesn't exist. ```rust use serde_norway::Value; let object: Value = serde_norway::from_str(r#"{ A: 65, B: 66, C: 67 }"#)?; let x = object.get("A").unwrap(); assert_eq!(x, 65); let sequence: Value = serde_norway::from_str(r#"[ "A", "B", "C" ]"#)?; let x = sequence.get(2).unwrap(); assert_eq!(x, &Value::String("C".into())); assert_eq!(sequence.get("A"), None); ``` -------------------------------- ### TryInto Implementation for IntoValues Source: https://docs.rs/serde_norway/latest/serde_norway/mapping/struct.IntoValues.html Shows how IntoValues can be converted into other types using TryInto, with error handling. ```APIDOC ## TryInto for IntoValues ### Description This implementation allows attempting to convert `IntoValues` into another type `U`. ### Type Aliases #### Error - `Error` (>::Error) - The type returned in the event of a conversion error. ### Methods #### fn try_into(self) -> Result>::Error> - **Description**: Attempts to perform the conversion from `IntoValues` to type `U`. ``` -------------------------------- ### Serialize Map Start with State Handling Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Initiates the serialization of a map. It handles special state logic for maps with a single entry, potentially related to tag checking, before emitting the mapping start. ```rust fn serialize_map(self, len: Option) -> Result { if len == Some(1) { self.state = if let State::FoundTag(_) = self.state { self.emit_mapping_start()?; State::CheckForDuplicateTag } else { State::CheckForTag }; } else { self.emit_mapping_start()?; } Ok(self) ``` -------------------------------- ### Serialize Tuple Variant Start Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Initiates the serialization of a tuple variant of an enum. It checks for nested enum serialization, sets the state to FoundTag, emits a sequence start, and returns the serializer for variant elements. ```rust fn serialize_tuple_variant( self, _enm: &'static str, _idx: u32, variant: &'static str, _len: usize, ) -> Result { if let State::FoundTag(_) = self.state { return Err(error::new(ErrorImpl::SerializeNestedEnum)); } self.state = State::FoundTag(variant.to_owned()); self.emit_sequence_start()?; Ok(self) ``` -------------------------------- ### Get a value from a YAML map by key Source: https://docs.rs/serde_norway/latest/src/serde_norway/mapping.rs.html?search=std%3A%3Avec Use `get(index)` to retrieve an immutable reference to the value associated with the given key. Returns `None` if the key is not found. The `Index` trait is used to specify the key. ```rust pub fn get(&self, index: I) -> Option<&Value> { index.index_into(self) } ``` -------------------------------- ### Serializer::new Source: https://docs.rs/serde_norway/latest/src/serde_norway/ser.rs.html Creates a new YAML serializer that writes to the provided `io::Write` object. It initializes the emitter and starts a YAML stream. ```APIDOC ## `Serializer::new(writer: W)` ### Description Creates a new YAML serializer that writes to the provided `io::Write` object. It initializes the emitter and starts a YAML stream. ### Method `pub fn new(writer: W) -> Self` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let mut buffer = Vec::new(); let mut ser = serde_norway::Serializer::new(&mut buffer); ``` ### Response #### Success Response - `Self` (serde_norway::Serializer): A new instance of the Serializer. #### Response Example None ``` -------------------------------- ### Recursive Singleton Map Serialization Example Source: https://docs.rs/serde_norway/latest/src/serde_norway/with.rs.html?search=u32+-%3E+bool Demonstrates applying `singleton_map_recursive` to a struct field containing enums. This transforms enums into singleton maps during serialization. The example shows both serialization to YAML and deserialization back to the original struct. ```rust #[derive(Serialize, Deserialize, PartialEq, Debug)] enum Enum { Int(i32), } #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Inner { a: Enum, bs: Vec, } #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Outer { tagged_style: Inner, #[serde(with = "serde_norway::with::singleton_map_recursive")] singleton_map_style: Inner, } fn main() { let object = Outer { tagged_style: Inner { a: Enum::Int(0), bs: vec![Enum::Int(1)], }, singleton_map_style: Inner { a: Enum::Int(2), bs: vec![Enum::Int(3)], }, }; let yaml = serde_norway::to_string(&object).unwrap(); print!("{}", yaml); let deserialized: Outer = serde_norway::from_str(&yaml).unwrap(); assert_eq!(object, deserialized); } ``` -------------------------------- ### Emitter Methods Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Provides documentation for the public methods of the Emitter, including `emit`, `flush`, and `into_inner`. ```APIDOC ## pub fn emit(&mut self, event: Event<'_>) -> Result<(), Error> ### Description Emits a YAML event using the libyaml emitter. Handles the initialization of various event types (SequenceStart, SequenceEnd, MappingStart, MappingEnd) and then calls `yaml_emitter_emit` to process the event. ### Method `emit` ### Parameters - `event` (Event<'_>) - The YAML event to emit. ### Return Value - `Result<(), Error>` - Ok(()) if the event was emitted successfully, or an Err containing a `Libyaml` or `Io` error if emission failed. ## pub fn flush(&mut self) -> Result<(), Error> ### Description Flushes the internal libyaml emitter buffer, ensuring all pending YAML output is written. ### Method `flush` ### Return Value - `Result<(), Error>` - Ok(()) if the flush was successful, or an Err containing an `Io` error if flushing failed. ## pub fn into_inner(self) -> Box ### Description Consumes the emitter and returns the underlying `io::Write` object. This is useful for retrieving the writer after the emitter is no longer needed. ### Method `into_inner` ### Return Value - `Box` - The owned writer object. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/serde_norway/latest/serde_norway/enum.Value.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the `type_id` method to get the `TypeId` of a type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### try_with_capacity_in Source: https://docs.rs/serde_norway/latest/serde_norway/type.Sequence.html?search= Constructs a new, empty `Vec` with at least the specified capacity and allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn try_with_capacity_in( capacity: usize, alloc: A, ) -> Result, TryReserveError> ### Description Constructs a new, empty `Vec` with at least the specified capacity with the provided allocator. The vector will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is zero, the vector will not allocate. ### Errors Returns an error if the capacity exceeds `isize::MAX` _bytes_ , or if the allocator reports allocation failure. ``` -------------------------------- ### Get Mutable Pointer to Vector Buffer Source: https://docs.rs/serde_norway/latest/serde_norway/type.Sequence.html Use `as_mut_ptr` to get a raw mutable pointer to the vector's buffer. Ensure the vector outlives the pointer and be mindful of potential reallocations invalidating the pointer. This method is safe to mix with other pointer access methods due to aliasing guarantees. ```rust let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` ```rust unsafe { let mut v = vec![0]; let ptr1 = v.as_mut_ptr(); ptr1.write(1); let ptr2 = v.as_mut_ptr(); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` ```rust use std::mem::{ManuallyDrop, MaybeUninit}; let mut v = ManuallyDrop::new(vec![0, 1, 2]); let ptr = v.as_mut_ptr(); let capacity = v.capacity(); let slice_ptr: *mut [MaybeUninit] = std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity); drop(unsafe { Box::from_raw(slice_ptr) }); ``` -------------------------------- ### Create and compare Tag instances Source: https://docs.rs/serde_norway/latest/src/serde_norway/value/tagged.rs.html Illustrates creating Tag instances with and without the leading '!' and demonstrates their equality comparison. Tags are considered equal if their string representations, after removing a leading '!', are the same. The `to_string()` method always includes the '!'. ```rust use serde_norway::value::Tag; assert_eq!(Tag::new("!Thing"), Tag::new("Thing")); let tag = Tag::new("Thing"); assert!(tag == "Thing"); assert!(tag == "!Thing"); assert!(tag.to_string() == "!Thing"); let tag = Tag::new("!Thing"); assert!(tag == "Thing"); assert!(tag == "!Thing"); assert!(tag.to_string() == "!Thing"); ``` -------------------------------- ### Mapping Struct Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html Represents the start of a YAML mapping, potentially with an associated tag. ```APIDOC ## Mapping Struct ### Description Represents the start of a YAML mapping, potentially with an associated tag. ### Fields * `tag`: An optional `String` representing the tag of the mapping. ``` -------------------------------- ### Sequence Struct Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html Represents the start of a YAML sequence, potentially with an associated tag. ```APIDOC ## Sequence Struct ### Description Represents the start of a YAML sequence, potentially with an associated tag. ### Fields * `tag`: An optional `String` representing the tag of the sequence. ``` -------------------------------- ### Creating and Comparing Tag Values Source: https://docs.rs/serde_norway/latest/serde_norway/value/struct.Tag.html?search= Demonstrates how to create Tag instances with and without the leading '!', and how to compare them. The `Tag::new` function handles the optional '!' gracefully. The `PartialEq` implementation allows comparison with strings and string slices. ```rust use serde_norway::value::Tag; assert_eq!(Tag::new("!Thing"), Tag::new("Thing")); let tag = Tag::new("Thing"); assert!(tag == "Thing"); assert!(tag == "!Thing"); assert!(tag.to_string() == "!Thing"); let tag = Tag::new("!Thing"); assert!(tag == "Thing"); assert!(tag == "!Thing"); assert!(tag.to_string() == "!Thing"); ``` -------------------------------- ### Get Key from VacantEntry Source: https://docs.rs/serde_norway/latest/src/serde_norway/mapping.rs.html Retrieves a reference to the key associated with a vacant entry. ```rust pub fn key(&self) -> &Value { self.vacant.key() } ``` -------------------------------- ### Getting Metadata with and_then Source: https://docs.rs/serde_norway/latest/serde_norway/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates using `and_then` with file path metadata operations. Note that path handling can differ across operating systems. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### OccupiedEntry::get_mut Method Source: https://docs.rs/serde_norway/latest/src/serde_norway/mapping.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a mutable reference to the value in an occupied entry. ```rust impl<'a> OccupiedEntry<'a> { /// Gets a mutable reference to the value in the entry. #[inline] pub fn get_mut(&mut self) -> &mut Value { self.occupied.get_mut() } } ``` -------------------------------- ### Struct Serialization and Deserialization Source: https://docs.rs/serde_norway/latest/index.html Shows how to use Serde derive macros with structs for serialization and deserialization to YAML. ```APIDOC ## Using Serde derive Structs serialize in the obvious way: ```rust use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Point { x: f64, y: f64, } fn main() -> Result<(), serde_norway::Error> { let point = Point { x: 1.0, y: 2.0 }; let yaml = serde_norway::to_string(&point)?; assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); let deserialized_point: Point = serde_norway::from_str(&yaml)?; assert_eq!(point, deserialized_point); Ok(()) } ``` ``` -------------------------------- ### new_in Source: https://docs.rs/serde_norway/latest/serde_norway/type.Sequence.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructs a new, empty `Vec` with the specified allocator. This is a nightly-only experimental API. ```APIDOC ## new_in ### Description Constructs a new, empty `Vec`. The vector will not allocate until elements are pushed onto it. ### Method `new_in(alloc: A)` ### Parameters - `alloc` (A): The allocator to use for the vector. ### Returns - `Vec`: A new, empty vector with the specified allocator. ### Note This is a nightly-only experimental API. (`allocator_api`) ### Example ```rust #![feature(allocator_api)] use std::alloc.System; let vec: Vec = Vec::new_in(System); ``` ``` -------------------------------- ### Type ID Implementation Source: https://docs.rs/serde_norway/latest/serde_norway/mapping/struct.OccupiedEntry.html?search=u32+-%3E+bool Gets the TypeId of the OccupiedEntry. This is part of the Any trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### key() - Get Entry Key Source: https://docs.rs/serde_norway/latest/serde_norway/mapping/enum.Entry.html?search= Retrieves a reference to the key associated with this entry. ```APIDOC ## key() ### Description Returns a reference to this entry’s key. ### Method `key(&self) -> &Value` ``` -------------------------------- ### Basic Usage of from_value Source: https://docs.rs/serde_norway/latest/serde_norway/fn.from_value.html?search= Demonstrates basic deserialization of a `serde_norway::Value::String` into a Rust `String`. ```rust let val = Value::String("foo".to_owned()); let s: String = serde_norway::from_value(val).unwrap(); assert_eq!("foo", s); ``` -------------------------------- ### Initialize YAML Sequence End Event Source: https://docs.rs/serde_norway/latest/src/serde_norway/libyaml/emitter.rs.html?search= Initializes a YAML sequence end event. ```rust Event::SequenceEnd => sys::yaml_sequence_end_event_initialize(sys_event) ```