### cbor! Macro Usage Example Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-top-level.md Constructing a Value tree using the cbor! macro. The macro returns a Result that must be handled. ```rust use ciborium::cbor; let value = cbor!({ "code" => 415, "message" => null, "continue" => false, "extra" => { "numbers" => [8.2341e+4, 0.251425] }, }) .unwrap(); // Result assert!(value.is_map()); ``` -------------------------------- ### Catching deserialization errors Source: https://github.com/enarx/ciborium/blob/main/_autodocs/errors.md Example showing how to handle different deserialization error variants using a match statement. ```rust use ciborium::de::{from_reader, Error}; let payload: &[u8] = &[0x1e]; // reserved major-0 additional info match from_reader::(payload) { Ok(v) => println!("value: {v}"), Err(Error::Syntax(offset)) => println!("malformed bytes at offset {offset}"), Err(Error::Semantic(offset, msg)) => println!("semantic error at {offset:?}: {msg}"), Err(Error::Io(e)) => println!("read error: {e:?}"), Err(Error::RecursionLimitExceeded) => println!("input nested too deeply"), } ``` -------------------------------- ### Implement Write trait for custom Sink Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Example of implementing the Write trait for a custom type, suitable for embedded scenarios like hardware FIFOs or log buffers. ```rust use ciborium_io::Write; struct Sink; impl Write for Sink { type Error = (); fn write_all(&mut self, data: &[u8]) -> Result<(), ()> { // e.g. push data into a hardware FIFO or a log buffer Ok(()) } fn flush(&mut self) -> Result<(), ()> { Ok(()) } } ``` -------------------------------- ### Catching ciborium::ser::Error Source: https://github.com/enarx/ciborium/blob/main/_autodocs/errors.md Example of matching on serialization errors returned by into_writer. ```rust use ciborium::ser::{into_writer, Error}; let mut out = Vec::new(); match into_writer(&std::collections::HashMap::::new(), &mut out) { Ok(()) => (), Err(Error::Io(e)) => eprintln!("io: {e:?}"), Err(Error::Value(msg)) => eprintln!("value rejected: {msg}"), } ``` -------------------------------- ### Enable all features for docs.rs Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Configuration to ensure documentation builds include all features for all crates. ```toml [package.metadata.docs.rs] all-features = true ``` -------------------------------- ### Catching ciborium::value::Error Source: https://github.com/enarx/ciborium/blob/main/_autodocs/errors.md Example of matching on errors during Value deserialization. ```rust use ciborium::value::{Value, Error}; let v = Value::Bool(true); match v.deserialized::() { Ok(s) => println!("{s}"), Err(Error::Custom(msg)) => println!("could not convert value: {msg}"), } ``` -------------------------------- ### Initialize Deserializer with deserializer_from_reader_with_buffer Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Creates a Deserializer instance that allows driving serde::de::Deserializer manually to deserialize multiple values. ```rust // ciborium/src/de/mod.rs:844 pub fn deserializer_from_reader_with_buffer( reader: R, scratch_buffer: &mut [u8], ) -> Deserializer<'_, R> where R::Error: core::fmt::Debug; ``` -------------------------------- ### Build and inspect Value with Serde round-trip Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Demonstrates creating a Value from a vector, performing in-memory serialization and deserialization, and constructing a tagged value. ```rust use ciborium::value::Value; use serde::{Deserialize, Serialize}; let v: Value = vec!["a", "b"].into(); // via From> assert!(v.is_array()); // in-memory conversion let json_like = Value::serialized(&(1u32, true)).unwrap(); let back: (u32, bool) = json_like.deserialized().unwrap(); assert_eq!(back, (1, true)); // tagged value (tag 61 must be constructed explicitly; plain From never produces Tag) let tagged = Value::Tag(61, Box::new(Value::Bytes(b"hello".to_vec()))); assert_eq!(tagged.as_tag(), Some((61, &Value::Bytes(b"hello".to_vec())))); ``` -------------------------------- ### Initialize Deserializer with deserializer_from_reader_with_buffer_and_recursion_limit Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Creates a Deserializer instance with both a custom buffer and an explicit recursion limit. ```rust // ciborium/src/de/mod.rs:864 pub fn deserializer_from_reader_with_buffer_and_recursion_limit( reader: R, scratch_buffer: &mut [u8], recurse_limit: usize, ) -> Deserializer<'_, R> where R::Error: core::fmt::Debug; ``` -------------------------------- ### Capturing tags with AllowAny and RequireAny Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-tag.md Shows how to capture arbitrary tags using AllowAny and RequireAny wrappers. ```rust use ciborium::tag::{AllowAny, RequireAny}; use ciborium::{de::from_reader, ser::into_vec}; // untagged input round-trips with the tag erased let any = AllowAny::(None, 7); let bytes = into_vec(&any).unwrap(); assert_eq!(bytes, vec![0x07]); // tagged input keeps its tag let any = AllowAny::(Some(6), 7); let bytes = into_vec(&any).unwrap(); assert_eq!(bytes, vec![0xc6, 0x07]); let req: RequireAny = from_reader(&bytes[..]).unwrap(); assert_eq!(req.0, 6); assert_eq!(req.1, 7); ``` -------------------------------- ### Workspace rust-toolchain.toml configuration Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Defines the minimal toolchain profile and required components for the workspace. ```toml [toolchain] profile = "minimal" components = ["rustfmt", "clippy"] ``` -------------------------------- ### ciborium-io Cargo features Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Configuration for the ciborium-io crate, managing embedded-io support and std/allocator features. ```toml [dependencies] embedded-io = { version = "0.7.1", optional = true } [features] alloc = [] std = ["alloc"] embedded-io = ["dep:embedded-io"] ``` -------------------------------- ### Encode a map with segmented text using Encoder Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Shows how to initialize an Encoder and push map headers and segmented text values to a buffer. ```rust use ciborium_ll::{Encoder, Header}; let mut buffer = [0u8; 19]; let mut encoder = Encoder::from(&mut buffer[..]); encoder.push(Header::Map(Some(1))).unwrap(); encoder.push(Header::Positive(7)).unwrap(); encoder.text("Hello, World!", 7).unwrap(); // segments of 7 bytes encoder.flush().unwrap(); assert_eq!(b"\xa1\x07\x7f\x67Hello, \x66World!\xff", &buffer[..]); ``` -------------------------------- ### Use custom Sink with high-level API Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Demonstrates using the custom Sink implementation with the high-level Ciborium serialization API in a no_std environment. ```rust use ciborium::{de::from_reader, ser::into_writer}; let mut log = Sink; into_writer(&"hello", &mut log).unwrap(); // W: ciborium_io::Write ``` -------------------------------- ### EIOReader::from Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Creates a new EIOReader from an existing embedded_io::Read implementation. ```APIDOC ## EIOReader::from ### Description Creates a new EIOReader instance that wraps an embedded_io::Read implementation, allowing it to be used as a ciborium_io::Read. ### Signature pub fn from(reader: &'a mut R) -> Self ### Parameters - **reader** (&'a mut R) - Required - A mutable reference to a type implementing embedded_io::Read. ``` -------------------------------- ### Preserve and access map order Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Shows how to construct a Value::Map and manipulate its contents using as_map and as_map_mut. ```rust use ciborium::value::Value; let mut m = Value::Map(vec![ (Value::Text("first".into()), Value::Integer(1.into())), (Value::Text("second".into()), Value::Bool(true)), ]); assert_eq!(m.as_map().unwrap().len(), 2); m.as_map_mut().unwrap().clear(); assert!(m.is_map() && m.as_map().unwrap().is_empty()); ``` -------------------------------- ### Decode segmented text with Decoder Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Demonstrates how to use the Decoder to pull headers and process segmented text data in chunks. ```rust use ciborium_ll::{Decoder, Header}; use ciborium_io::Read as _; let input = b"\x6dHello, World!"; // 0x6d = text(13) let mut decoder = Decoder::from(&input[..]); match decoder.pull().unwrap() { Header::Text(len) => { let mut segments = decoder.text(len); while let Some(mut segment) = segments.pull().unwrap() { let mut buffer = [0u8; 7]; while let Some(chunk) = segment.pull(&mut buffer[..]).unwrap() { println!("chunk: {chunk:?}"); } } } other => panic!("unexpected: {other:?}"), } ``` -------------------------------- ### push Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Pushes a single header back into the input buffer. ```APIDOC ## pub fn push(&mut self, item: Header) ### Description Pushes a single header back into the input buffer. Panics if a header is already buffered. ``` -------------------------------- ### Serialize a typed struct with serde derive Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ser.md Demonstrates how to use the Serialize derive macro to encode a struct into a writer or a vector. ```rust use ciborium::ser::{into_writer, into_vec}; use serde::Serialize; #[derive(Serialize)] struct Point { x: i32, y: i32 } let p = Point { x: -5, y: 7 }; let mut out = Vec::new(); into_writer(&p, &mut out).unwrap(); let bytes = into_vec(&p).unwrap(); // std only assert_eq!(bytes, out); ``` -------------------------------- ### ciborium-ll Cargo features Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Configuration for the ciborium-ll crate, including half-precision float support and allocator features. ```toml [dependencies] half = { version = "2.6", default-features = false, optional = true } [features] default = ["half"] alloc = [] std = ["alloc", "half/std"] ``` -------------------------------- ### embedded-io adapter structures Source: https://github.com/enarx/ciborium/blob/main/_autodocs/types.md Adapter structures for embedded-io devices, used when the embedded-io feature is enabled. ```rust // eio.rs:6, 31 (feature "embedded-io") pub struct EIOWriter<'a, W>(&'a mut W); pub struct EIOReader<'a, R>(&'a mut R); ``` -------------------------------- ### Handle big integer fallback to tags Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value-support.md Demonstrates how values that do not fit into an Integer type are converted to tags. ```rust use ciborium::value::{Integer, Value}; // Fits -> Integer let small: Integer = 42u32.into(); let v = Value::from(small); assert!(v.is_integer()); // Does not fit u64 -> cannot be an Integer; Value::from(u128) uses Tag(2) let big: Value = (u128::MAX >> 1).into(); assert!(big.is_tag()); ``` -------------------------------- ### EIOWriter::from Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Creates a new EIOWriter from an existing embedded_io::Write implementation. ```APIDOC ## EIOWriter::from ### Description Creates a new EIOWriter instance that wraps an embedded_io::Write implementation, allowing it to be used as a ciborium_io::Write. ### Signature pub fn from(writer: &'a mut W) -> Self ### Parameters - **writer** (&'a mut W) - Required - A mutable reference to a type implementing embedded_io::Write. ``` -------------------------------- ### offset Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Returns the current byte offset. ```APIDOC ## pub fn offset(&mut self) -> usize ### Description Returns the current byte offset, which starts at 0 at construction. ``` -------------------------------- ### Using AllowExact for optional tagged fields Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-tag.md Demonstrates using AllowExact to handle fields that optionally carry a specific tag, such as an RFC 3339 date string. ```rust use ciborium::tag::AllowExact; use ciborium::{de::from_reader, ser::into_vec}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] struct Event { name: String, when: AllowExact, // tag 0 = date/time string; absent allowed } let e = Event { name: "launch".into(), when: AllowExact("2024-05-01T00:00:00Z".into()) }; let bytes = into_vec(&e).unwrap(); // when is written as c0 78 13 "2024-05-01T00:00:00Z" (66 bytes) let back: Event = from_reader(&bytes[..]).unwrap(); assert_eq!(e, back); ``` -------------------------------- ### Deserialize with from_reader Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Deserializes a whole CBOR document using a 4 KB stack scratch buffer and a recursion limit of 256. ```rust // ciborium/src/de/mod.rs:790 pub fn from_reader(reader: R) -> Result> where R::Error: core::fmt::Debug; ``` -------------------------------- ### Set crate-level linting attributes Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Standard linting configuration applied to ciborium and ciborium-ll crates. ```rust #![deny(missing_docs)] #![deny(clippy::all)] #![deny(clippy::cargo)] ``` -------------------------------- ### from_reader Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Deserializes a whole CBOR document from a reader using a default 4 KB stack scratch buffer and a recursion limit of 256. ```APIDOC ## fn from_reader(reader: R) -> Result> ### Description Deserializes a whole CBOR document using a 4 KB stack scratch buffer and a recursion limit of 256. Byte slices are valid readers. ### Parameters - **reader** (R: ciborium_io::Read) - Required - Source of CBOR bytes ### Return - **Result>** - The deserialized object or an error. ``` -------------------------------- ### into_writer Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ser.md Serializes a value into a writer using the Ciborium serializer. ```APIDOC ## into_writer ### Description Serializes a given value into the provided writer using CBOR encoding. ### Usage ```rust use ciborium::ser::into_writer; let mut out = Vec::new(); into_writer(&vec![1u64, 2, 30], &mut out).unwrap(); ``` ``` -------------------------------- ### Decode from a byte slice Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Demonstrates basic decoding of a CBOR byte slice into a Rust vector. ```rust use ciborium::de::from_reader; // CBOR: 0x83 0x01 0x02 0x03 -> [1, 2, 3] let bytes = [0x83u8, 0x01, 0x02, 0x03]; let value: Vec = from_reader(&bytes[..]).unwrap(); assert_eq!(value, vec![1, 2, 3]); ``` -------------------------------- ### Decoder methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Core methods for interacting with the Decoder, including pulling headers, pushing headers back, and reading segments. ```rust pub fn pull(&mut self) -> Result>; // :108 pub fn push(&mut self, item: Header); // :123 pub fn offset(&mut self) -> usize; // :133 pub fn bytes<'a>(&'a mut self, len: Option) -> Segments<'a, R, crate::seg::Bytes>; // :149 pub fn text<'a>(&'a mut self, len: Option) -> Segments<'a, R, crate::seg::Text>; // :169 ``` -------------------------------- ### Declare embedded-io adapter structs Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Adapter structs for bridging embedded-io traits to ciborium-io traits, gated by the embedded-io feature. ```rust // ciborium-io/src/eio.rs pub mod eio; // lib.rs:27, gated on feature "embedded-io" pub struct EIOWriter<'a, W>(&'a mut W); // eio.rs:6 pub struct EIOReader<'a, R>(&'a mut R); // eio.rs:31 ``` -------------------------------- ### ciborium Cargo features Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Configuration for the main ciborium crate, defining default features and std support. ```toml [features] default = ["std"] std = ["ciborium-io/std", "serde/std"] ``` -------------------------------- ### Encode CBOR Map with Text Source: https://github.com/enarx/ciborium/blob/main/ciborium-ll/README.md Demonstrates encoding a CBOR map containing a positive integer and a text string, including proper segmentation and flushing the encoder. ```rust use ciborium_ll::{Encoder, Header}; use ciborium_io::Write as _; let mut buffer = [0u8; 19]; let mut encoder = Encoder::from(&mut buffer[..]); // Write the structure encoder.push(Header::Map(Some(1))).unwrap(); encoder.push(Header::Positive(7)).unwrap(); encoder.text("Hello, World!", 7).unwrap(); // Validate our output encoder.flush().unwrap(); assert_eq!(b"\xa1\x07\x7f\x67Hello, \x66World!\xff", &buffer[..]); ``` -------------------------------- ### deserializer_from_reader_with_buffer_and_recursion_limit Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Creates a Deserializer instance with a custom buffer and recursion limit. ```APIDOC ## fn deserializer_from_reader_with_buffer_and_recursion_limit(reader: R, scratch_buffer: &mut [u8], recurse_limit: usize) -> Deserializer<'_, R> ### Description Creates a Deserializer with an explicit recursion limit and scratch buffer. ### Parameters - **reader** (R: ciborium_io::Read) - Required - Source of CBOR bytes - **scratch_buffer** (&mut [u8]) - Required - Scratch space - **recurse_limit** (usize) - Required - Maximum nesting depth ### Return - **Deserializer<'_, R>** - A deserializer instance. ``` -------------------------------- ### cbor! Macro Definition Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-top-level.md The macro definition for constructing Value trees from JSON-like syntax. ```rust // lib.rs:133 #[macro_export] macro_rules! cbor { // ... } ``` -------------------------------- ### canonical_into_writer and canonical_into_vec functions Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value-support.md Serializes a serde value to RFC 8949 Deterministic Encoding, suitable for signatures, hashing, and canonical storage. ```rust // canonical.rs:161 pub fn canonical_into_writer( value: &T, writer: W, ) -> Result<(), crate::ser::Error> where W::Error: core::fmt::Debug; // canonical.rs:178 (std only) #[cfg(feature = "std")] pub fn canonical_into_vec( value: &T, ) -> Result, crate::ser::Error< as ciborium_io::Write>::Error>> ``` -------------------------------- ### Handling tag mismatch errors Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-tag.md Illustrates how RequireExact rejects data when the provided tag does not match the expected tag. ```rust use ciborium::tag::RequireExact; use ciborium::de::from_reader; use ciborium::de::Error; // tag 7 over a bool, but RequireExact<_, 6> demands tag 6 let bytes = [0xc7, 0xf5]; let result: Result, _> = from_reader(&bytes[..]); assert!(matches!( result, Err(Error::Semantic(None, msg)) if msg == "required tag not found" )); ``` -------------------------------- ### Configure no_std support Source: https://github.com/enarx/ciborium/blob/main/_autodocs/configuration.md Conditional compilation attributes used to support no_std environments and allocate memory when required. ```rust #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc ``` -------------------------------- ### Canonical ordering of keys Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value-support.md Shows how CanonicalValue sorts keys in a BTreeSet based on canonical ordering rules. ```rust use ciborium::value::{canonical_into_vec, CanonicalValue, Value}; use std::collections::BTreeSet; let mut set = BTreeSet::new(); set.insert(CanonicalValue::from(Value::Integer(1.into()))); set.insert(CanonicalValue::from(Value::Integer((-1i64).into()))); // canonical order [0x01, 0x20]: +1 sorts before -1 (same length, positive < negative) ``` -------------------------------- ### Deserialize with from_reader_with_buffer Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Deserializes a CBOR document with a caller-controlled scratch buffer. ```rust // ciborium/src/de/mod.rs:802 pub fn from_reader_with_buffer( reader: R, scratch_buffer: &mut [u8], ) -> Result> where R::Error: core::fmt::Debug; ``` -------------------------------- ### Integer variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Integer variant. ```rust pub fn is_integer(&self) -> bool; // :63 pub fn as_integer(&self) -> Option; // :78 (returns a copy; Integer is Copy) pub fn into_integer(self) -> Result; // :97 ``` -------------------------------- ### AllowAny Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-tag.md A wrapper struct that supports any tag or no tag at all. The tag is optional on input and re-emitted on output. ```APIDOC ## AllowAny ### Description A wrapper struct that allows for any tag or no tag at all. The tag is optional on input and, if present, re-emitted on output. ### Structure `pub struct AllowAny(pub Option, pub V);` ### Behavior - **Deserialize**: If input is tagged, it results in `AllowAny(Some(t), v)`. If input is untagged, it results in `AllowAny(None, v)`. - **Serialize**: If `Some(t)` is provided, it serializes as `Tag(t)` followed by the value. If `None` is provided, it serializes as the plain value. ``` -------------------------------- ### Crate Module Declarations Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-top-level.md The module tree structure defined at the crate root. ```rust pub mod de; pub mod ser; pub mod tag; pub mod value; ``` -------------------------------- ### Segment methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Methods for reading data from a segment. ```rust pub fn left(&self) -> usize; // :126 unread bytes + parser-saved bytes pub fn pull<'a>(&mut self, buffer: &'a mut [u8]) -> Result, Error>; // :134 ``` -------------------------------- ### Handle serialization errors Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ser.md Shows how to catch Error::Value when a custom Serialize implementation returns an error. ```rust use ciborium::ser::{into_writer, Error}; use serde::ser::{Error as _, Serializer}; struct Boom; impl serde::Serialize for Boom { fn serialize(&self, _s: S) -> Result<(), S::Error> { Err(S::Error::custom("boom")) } } let mut sink = Vec::new(); match into_writer(&Boom, &mut sink) { Err(Error::Value(msg)) => println!("serialization rejected: {msg}"), other => panic!("unexpected: {other:?}"), } ``` -------------------------------- ### Bool variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Bool variant. ```rust pub fn is_bool(&self) -> bool; // :298 pub fn as_bool(&self) -> Option; // :312 (returns a copy) pub fn into_bool(self) -> Result; // :331 ``` -------------------------------- ### cibor! Macro Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-top-level.md The cbor! macro allows for the construction of a Value tree using a JSON-like syntax. It returns a Result. ```APIDOC ## cbor! Macro ### Description Builds a `Value` tree from a JSON-like syntax. The macro returns `Result`. ### Syntax Rules - `{ "key" => value, ... }` — a `Value::Map`. - `[ item, ... ]` — a `Value::Array`. - Any plain expression `$val` is wrapped with `Value::serialized(&$val)`. - The identifier `null` resolves to `Value::Null`. ### Example ```rust use ciborium::cbor; let value = cbor!({ "code" => 415, "message" => null, "continue" => false, "extra" => { "numbers" => [8.2341e+4, 0.251425] }, }) .unwrap(); ``` ``` -------------------------------- ### Text variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Text variant. ```rust pub fn is_text(&self) -> bool; // :230 pub fn as_text(&self) -> Option<&str>; // :245 pub fn as_text_mut(&mut self) -> Option<&mut String>; // :263 pub fn into_text(self) -> Result; // :282 ``` -------------------------------- ### Map variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Map variant. ```rust pub fn is_map(&self) -> bool; // :523 pub fn as_map(&self) -> Option<&Vec<(Value, Value)>>; // :548 pub fn as_map_mut(&mut self) -> Option<&mut Vec<(Value, Value)>>; // :571 pub fn into_map(self) -> Result, Self>; // :594 ``` -------------------------------- ### CBOR Constants Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Constants for simple CBOR types and tags defined in the library. ```rust // lib.rs:146-160 pub mod simple { pub const FALSE: u8 = 20; pub const TRUE: u8 = 21; pub const NULL: u8 = 22; pub const UNDEFINED: u8 = 23; } pub mod tag { pub const BIGPOS: u64 = 2; pub const BIGNEG: u64 = 3; } ``` -------------------------------- ### Implement EIOReader for embedded-io Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Implementation of the Read trait for EIOReader, mapping methods to embedded_io::Read. ```rust impl<'a, R> EIOReader<'a, R> { pub fn from(reader: &'a mut R) -> Self; // eio.rs:35 } impl<'a, R> Read for EIOReader<'a, R> where R: embedded_io::Read, { type Error = embedded_io::ReadExactError; // read_exact -> embedded_io::Read::read_exact } ``` -------------------------------- ### into_writer Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ser.md Serializes a value into a provided writer. ```APIDOC ## fn into_writer(value: &T, writer: W) -> Result<(), Error> ### Description Serializes the provided value into the specified writer using CBOR encoding. ### Parameters - **value** (&T where T: ?Sized + serde::Serialize) - Required - The value to encode. - **writer** (W: ciborium_io::Write) - Required - Destination; byte-slice buffers, std::io::Write types, and Vec are supported. ### Return - **Result<(), Error>** - Returns Ok(()) on success, or an Error if serialization fails. ``` -------------------------------- ### Manual multi-value stream decoding Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Deserializes multiple consecutive items from a stream using a buffer and a deserializer instance. ```rust use ciborium::de::deserializer_from_reader_with_buffer; use serde::Deserialize; let mut buf = [0u8; 4096]; let mut de = deserializer_from_reader_with_buffer(&b"\x01\x18\x64"[..], &mut buf); let a: u8 = Deserialize::deserialize(&mut de).unwrap(); let b: u16 = Deserialize::deserialize(&mut de).unwrap(); assert_eq!((a, b), (1, 100)); ``` -------------------------------- ### pull Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Reads the next header from the input stream. ```APIDOC ## pub fn pull(&mut self) -> Result> ### Description Reads the next header from the input. Syntax errors return Error::Syntax(offset) where offset is the stream offset before the item. ``` -------------------------------- ### Float variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Float variant. ```rust pub fn is_float(&self) -> bool; // :180 pub fn as_float(&self) -> Option; // :195 (returns a copy) pub fn into_float(self) -> Result; // :214 ``` -------------------------------- ### Implement EIOWriter for embedded-io Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-io.md Implementation of the Write trait for EIOWriter, mapping methods to embedded_io::Write. ```rust impl<'a, W> EIOWriter<'a, W> { pub fn from(writer: &'a mut W) -> Self; // eio.rs:10 } impl<'a, W> Write for EIOWriter<'a, W> where W: embedded_io::Write, { type Error = W::Error; // write_all -> embedded_io::Write::write_all // flush -> embedded_io::Write::flush } ``` -------------------------------- ### Value::serialized Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Serializes a Serde-compatible type into a Ciborium Value tree. ```APIDOC ## Value::serialized ### Description Serializes a value that implements `serde::Serialize` into a `Value` tree. ### Signature `pub fn serialized(value: &T) -> Result` ### Parameters - **value** (&T) - Required - The data structure to serialize. ### Returns - **Result** - Returns the `Value` tree on success, or a `ciborium::value::Error` on failure. ``` -------------------------------- ### from_reader_with_buffer Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Deserializes a CBOR document using a caller-provided scratch buffer. ```APIDOC ## fn from_reader_with_buffer(reader: R, scratch_buffer: &mut [u8]) -> Result> ### Description Same semantics as from_reader, but with caller-controlled scratch space. A larger buffer reduces reads at the cost of memory. ### Parameters - **reader** (R: ciborium_io::Read) - Required - Source of CBOR bytes - **scratch_buffer** (&mut [u8]) - Required - Temporary scratch space ### Return - **Result>** - The deserialized object or an error. ``` -------------------------------- ### Crate-root re-exports Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ciborium-ll.md Public re-exports from the crate root, including Decoder, Encoder, Header, and segment stream types. ```rust pub use dec::*; // Decoder, Error pub use enc::*; // Encoder pub use hdr::*; // Header pub use seg::{Segment, Segments}; // segment stream types ``` -------------------------------- ### Bytes variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Bytes variant. ```rust pub fn is_bytes(&self) -> bool; // :113 pub fn as_bytes(&self) -> Option<&Vec>; // :127 pub fn as_bytes_mut(&mut self) -> Option<&mut Vec>; // :145 pub fn into_bytes(self) -> Result, Self>; // :164 ``` -------------------------------- ### Array variant methods Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-value.md Methods for interacting with the Array variant. ```rust pub fn is_array(&self) -> bool; // :436 pub fn as_array(&self) -> Option<&Vec>; // :456 pub fn as_array_mut(&mut self) -> Option<&mut Vec>; // :479 pub fn into_array(self) -> Result, Self>; // :503 ``` -------------------------------- ### into_vec Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-ser.md Serializes a value into a new Vec (std feature only). ```APIDOC ## fn into_vec(value: &T) -> Result, Error> ### Description Convenience wrapper that serializes a value into a fresh Vec. ### Parameters - **value** (&T where T: ?Sized + serde::Serialize) - Required - The value to encode. ### Return - **Result, Error>** - Returns the serialized bytes in a Vec on success, or an Error if serialization fails. ``` -------------------------------- ### Error handling with a buffer Source: https://github.com/enarx/ciborium/blob/main/_autodocs/api-de.md Uses from_reader_with_buffer to handle decoding errors when working with a provided scratch buffer. ```rust use ciborium::de::from_reader_with_buffer; use ciborium::de::Error; let input = b"\x9b\x01\x02\x03"; // truncated indefinite array let mut scratch = [0u8; 64 * 1024]; match from_reader_with_buffer::, _>(&input[..], &mut scratch) { Ok(v) => println!("decoded: {v:?}"), Err(Error::Io(e)) => println!("read failure: {e:?}"), Err(e) => println!("decode failure (offset/reason): {e:?}"), } ``` -------------------------------- ### CBOR Serialization to a Writer Source: https://github.com/enarx/ciborium/blob/main/README.md Use `into_writer` to serialize data into CBOR format and write it to any type that implements `Write`. Byte slices can also be used as writers. ```rust use ciborium::ser::into_writer; let value = serde_json::json!({ "hello": "world" }); let mut writer = Vec::new(); into_writer(&value, &mut writer).unwrap(); println!("{:?}", writer); ```