### Serialize to AllocVec Example Source: https://docs.rs/postcard/latest/postcard/fn.to_allocvec.html Demonstrates serializing a boolean and a string into a `Vec` using `to_allocvec`. This function requires the `alloc` feature to be enabled. ```rust use postcard::to_allocvec; let ser: Vec = to_allocvec(&true).unwrap(); assert_eq!(ser.as_slice(), &[0x01]); let ser: Vec = to_allocvec("Hi!").unwrap(); assert_eq!(ser.as_slice(), &[0x03, b'H', b'i', b'!']); ``` -------------------------------- ### Serialize Data and Get Size Source: https://docs.rs/postcard/latest/postcard/ser_flavors/struct.Size.html Demonstrates how to use the Size flavor to serialize a value and obtain its byte size. This is useful for pre-allocating buffers or understanding data footprint. ```rust use postcard::{serialize_with_flavor, ser_flavors}; let value = false; let size = serialize_with_flavor(&value, ser_flavors::Size::default()).unwrap(); assert_eq!(size, 1); ``` -------------------------------- ### postcard::to_slice Example Source: https://docs.rs/postcard/latest/postcard/fn.to_slice.html Demonstrates serializing different data types like booleans, strings, and byte arrays into a buffer using `postcard::to_slice`. Shows how the function returns the used portion of the slice and highlights the distinct serialization for `&[u8]` versus `&[u8; N]`. ```rust use postcard::to_slice; let mut buf = [0u8; 32]; let used = to_slice(&true, &mut buf).unwrap(); assert_eq!(used, &[0x01]); let used = to_slice("Hi!", &mut buf).unwrap(); assert_eq!(used, &[0x03, b'H', b'i', b'!']); // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently. let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30]; let used = to_slice(data, &mut buf).unwrap(); assert_eq!(used, &[0x04, 0x01, 0x00, 0x20, 0x30]); let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30]; let used = to_slice(data, &mut buf).unwrap(); assert_eq!(used, &[0x01, 0x00, 0x20, 0x30]); ``` -------------------------------- ### Serialize to std::io::Write Source: https://docs.rs/postcard/latest/postcard/fn.to_io.html Serializes a value to a writer implementing `std::io::Write`. This example demonstrates serializing a boolean and a string to a byte slice. ```rust use postcard::to_io; let mut buf: [u8; 32] = [0; 32]; let mut writer: &mut [u8] = &mut buf; let ser = to_io(&true, &mut writer).unwrap(); to_io("Hi!", ser).unwrap(); assert_eq!(&buf[0..5], &[0x01, 0x03, b'H', b'i', b'!']); ``` -------------------------------- ### Accessing File Metadata with and_then Source: https://docs.rs/postcard/latest/postcard/type.Result.html Demonstrates using `and_then` to chain fallible operations like getting file metadata and its modification time. Handles potential errors like 'NotFound'. ```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); ``` -------------------------------- ### Serialize to embedded_io Write Source: https://docs.rs/postcard/latest/postcard/fn.to_eio.html Serializes a value to an `embedded_io Write` using the `to_eio` function. This example demonstrates serializing a boolean and a string, then asserting the resulting byte sequence. ```rust use postcard::to_eio; let mut buf: [u8; 32] = [0; 32]; let mut writer: &mut [u8] = &mut buf; let ser = to_eio(&true, &mut writer).unwrap(); to_eio("Hi!", ser).unwrap(); assert_eq!(&buf[0..5], &[0x01, 0x03, b'H', b'i', b'!']); ``` -------------------------------- ### Serialize to Extend Source: https://docs.rs/postcard/latest/postcard/fn.to_extend.html Serializes a value into a writer that implements `Extend`. The function returns the modified writer. This example demonstrates serializing a boolean and then a string into a `Vec`. ```rust use postcard::to_extend; let mut vec = Vec::new(); let ser = to_extend(&true, vec).unwrap(); let vec = to_extend("Hi!", ser).unwrap(); assert_eq!(&vec[0..5], &[0x01, 0x03, b'H', b'i', b'!']); ``` -------------------------------- ### Getting references from Result Source: https://docs.rs/postcard/latest/postcard/type.Result.html The `as_ref()` method converts a `&Result` to a `Result<&T, &E>`, providing references to the contained values without consuming the original Result. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Serialize with CRC32 Source: https://docs.rs/postcard/latest/postcard/fn.to_slice_crc32.html Serializes data to a buffer and appends a 32-bit CRC32 checksum. Ensure the buffer is large enough to hold the serialized data plus 4 bytes for the CRC. This example uses the `CRC_32_ISCSI` algorithm. ```rust use crc::{Crc, CRC_32_ISCSI}; let mut buf = [0; 9]; let data: &[u8] = &[0x01, 0x00, 0x20, 0x30]; let crc = Crc::::new(&CRC_32_ISCSI); let used = postcard::to_slice_crc32(data, &mut buf, crc.digest()).unwrap(); assert_eq!(used, &[0x04, 0x01, 0x00, 0x20, 0x30, 0x8E, 0xC8, 0x1A, 0x37]); ``` -------------------------------- ### Get Type ID Source: https://docs.rs/postcard/latest/postcard/de_flavors/struct.Slice.html Gets the `TypeId` of the `Slice` struct. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Any TypeId Method Source: https://docs.rs/postcard/latest/postcard/ser_flavors/struct.Cobs.html Gets the `TypeId` of the current type. This is part of the blanket implementation of the `Any` trait. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Serialize/Deserialize with alloc::vec::Vec Source: https://docs.rs/postcard/latest/postcard/index.html Demonstrates serialization to an alloc::vec::Vec and deserialization back to a struct. Requires the alloc feature. ```rust use core::ops::Deref; use serde::{Serialize, Deserialize}; use postcard::{from_bytes, to_allocvec}; extern crate alloc; use alloc::vec::Vec; #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] struct RefStruct<'a> { bytes: &'a [u8], str_s: &'a str, } let message = "hElLo"; let bytes = [0x01, 0x10, 0x02, 0x20]; let output: Vec = to_allocvec(&RefStruct { bytes: &bytes, str_s: message, }).unwrap(); assert_eq!( &[0x04, 0x01, 0x10, 0x02, 0x20, 0x05, b'h', b'E', b'l', b'L', b'o',], output.deref() ); let out: RefStruct = from_bytes(output.deref()).unwrap(); assert_eq!( out, RefStruct { bytes: &bytes, str_s: message, } ); ``` -------------------------------- ### serialize_struct_variant Source: https://docs.rs/postcard/latest/postcard/struct.Serializer.html Starts the serialization of a struct variant within an enum. This is followed by `serialize_field` calls for the variant's fields and a final `end` call. ```APIDOC ## serialize_struct_variant ### Description Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. This call must be followed by zero or more calls to `serialize_field`, then a call to `end`. ### Method (Implicitly part of a serialization process) ### Parameters * `_name`: &'static str - The name of the enum. * `variant_index`: u32 - The index of the variant. * `_variant`: &'static str - The name of the variant. * `_len`: usize - The number of fields in the variant. ### Response * `Result` - A type that allows for subsequent field serialization. ``` -------------------------------- ### into_ok Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value, but never panics. This is an experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Method `into_ok()` ### Parameters None ### Request Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Response #### Success Response - **T** (type) - The contained Ok value. #### Response Example ```rust "this is fine" ``` ``` -------------------------------- ### HVec::new Source: https://docs.rs/postcard/latest/postcard/ser_flavors/struct.HVec.html Creates a new, empty HVec instance. This is the primary way to initialize the stack-allocated storage for serialization. ```APIDOC ## HVec::new ### Description Creates a new, currently empty, `heapless::Vec` to be used for storing serialized output data. ### Method ```rust pub fn new() -> Self ``` ### Parameters None ### Returns A new, empty `HVec` instance. ``` -------------------------------- ### Slice::new Source: https://docs.rs/postcard/latest/postcard/de_flavors/struct.Slice.html Creates a new `Slice` flavor instance from a given byte buffer. ```APIDOC ## impl<'de> Slice<'de> ### pub fn new(sli: &'de [u8]) -> Self Create a new Slice from the given buffer. ``` -------------------------------- ### Compute Serialized Size of a Value Source: https://docs.rs/postcard/latest/postcard/experimental/fn.serialized_size.html Use this function to get the size in bytes that a value will occupy when serialized with postcard. The type `T` must implement `Serialize` and `?Sized`. ```rust pub fn serialized_size(value: &T) -> Result where T: Serialize + ?Sized, ``` -------------------------------- ### Obtain Deserializer from Bytes Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Creates a `Deserializer` specifically for byte slices using the `Slice` flavor. This is a common way to start deserializing data from a byte buffer. ```rust pub fn from_bytes(input: &'de [u8]) -> Self ``` -------------------------------- ### Flavor Provided Method: try_take_n_temp Source: https://docs.rs/postcard/latest/postcard/de_flavors/trait.Flavor.html Attempts to take the next `ct` bytes, without guaranteeing zero-copy. Use this instead of `try_take_n` when zero-copy is not required, to avoid potential temporary buffer allocations. ```rust fn try_take_n_temp<'a>(&'a mut self, ct: usize) -> Result<&'a [u8]> where 'de: 'a { ... } ``` -------------------------------- ### Serialize/Deserialize with heapless::Vec Source: https://docs.rs/postcard/latest/postcard/index.html Demonstrates serialization to a heapless::Vec and deserialization back to a struct. Requires the heapless feature. ```rust use core::ops::Deref; use serde::{Serialize, Deserialize}; use postcard::{from_bytes, to_vec}; use heapless::Vec; #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] struct RefStruct<'a> { bytes: &'a [u8], str_s: &'a str, } let message = "hElLo"; let bytes = [0x01, 0x10, 0x02, 0x20]; let output: Vec = to_vec(&RefStruct { bytes: &bytes, str_s: message, }).unwrap(); assert_eq!( &[0x04, 0x01, 0x10, 0x02, 0x20, 0x05, b'h', b'E', b'l', b'L', b'o',], output.deref() ); let out: RefStruct = from_bytes(output.deref()).unwrap(); assert_eq!( out, RefStruct { bytes: &bytes, str_s: message, } ); ``` -------------------------------- ### Postcard Crate Dependencies Source: https://docs.rs/postcard/latest/postcard/index.html Shows the necessary dependencies for the Postcard crate in Cargo.toml, including disabling default serde features for no_std compatibility. ```toml [dependencies] postcard = "1.0.0" # By default, `serde` has the `std` feature enabled, which makes it unsuitable for embedded targets # disabling default-features fixes this serde = { version = "1.0.*", default-features = false } ``` -------------------------------- ### Serialize to slice with COBS encoding Source: https://docs.rs/postcard/latest/postcard/fn.to_slice_cobs.html Use `to_slice_cobs` to serialize a value into a buffer and get the used portion of the buffer. The output includes the COBS encoded data and a null terminator. ```rust use postcard::to_slice_cobs; let mut buf = [0u8; 32]; let used = to_slice_cobs(&false, &mut buf).unwrap(); assert_eq!(used, &[0x01, 0x01, 0x00]); let used = to_slice_cobs("1", &mut buf).unwrap(); assert_eq!(used, &[0x03, 0x01, b'1', 0x00]); let used = to_slice_cobs("Hi!", &mut buf).unwrap(); assert_eq!(used, &[0x05, 0x03, b'H', b'i', b'!', 0x00]); let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30]; let used = to_slice_cobs(data, &mut buf).unwrap(); assert_eq!(used, &[0x03, 0x04, 0x01, 0x03, 0x20, 0x30, 0x00]); ``` -------------------------------- ### EIOReader::new Constructor Source: https://docs.rs/postcard/latest/postcard/de_flavors/io/eio/struct.EIOReader.html Creates a new EIOReader instance. The provided buffer must be large enough to hold all data read during deserialization. ```rust pub fn new(reader: T, buff: &'de mut [u8]) -> Self ``` -------------------------------- ### new Source: https://docs.rs/postcard/latest/postcard/ser_flavors/struct.ExtendFlavor.html Creates a new ExtendFlavor instance from a given core::iter::Extend iterator. ```APIDOC ### impl ExtendFlavor #### pub fn new(iter: T) -> Self Create a new `Self` flavor from a given `core::iter::Extend` ```rust pub fn new(iter: T) -> Self; ``` ``` -------------------------------- ### Into Ok Value (Never Panics) Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value. This is a nightly-only experimental API that never panics. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Mutably Iterating Over Ok Value in Rust Result Source: https://docs.rs/postcard/latest/postcard/type.Result.html Shows how to get a mutable iterator over the contained value if the `Result` is `Ok`. The `iter_mut` method allows modifying the `Ok` value through the iterator. ```Rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### into Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Calls `U::from(self)` for type conversion. ```APIDOC ## fn into(self) -> U ### Description Calls `U::from(self)`. This method is part of the `Into` trait and facilitates type conversions by leveraging the corresponding `From` implementation. ### Method N/A (Method of the `Into` trait) ### Parameters None ``` -------------------------------- ### Create WriteFlavor Instance Source: https://docs.rs/postcard/latest/postcard/ser_flavors/io/struct.WriteFlavor.html Instantiates a new WriteFlavor by wrapping a std::io::Write compatible type. ```rust pub fn new(writer: T) -> Self ``` -------------------------------- ### Iterating Over Ok Value in Rust Result Source: https://docs.rs/postcard/latest/postcard/type.Result.html Demonstrates how to get an iterator that yields the contained value if the `Result` is `Ok`. The `iter` method is useful for treating a `Result` like a collection with at most one element. ```Rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Into Implementation Source: https://docs.rs/postcard/latest/postcard/ser_flavors/crc/struct.CrcModifier.html Allows converting a CrcModifier into another type that can be formed from it. ```APIDOC ## impl Into for T where U: From, ### fn into(self) -> U Calls `U::from(self)`. ``` -------------------------------- ### Sum of Iterator of Results Source: https://docs.rs/postcard/latest/postcard/type.Result.html Calculates the sum of elements in an iterator where each element is a Result. If any element is an Err, it's returned immediately. Otherwise, the sum of all Ok values is returned. This example specifically rejects negative numbers. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Using expect for Error Handling in Rust Source: https://docs.rs/postcard/latest/postcard/type.Result.html Demonstrates the `expect` method to retrieve the `Ok` value or panic with a custom message if the `Result` is `Err`. Use `expect` when a failure to be `Ok` represents an unrecoverable program state. ```Rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```Rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### unwrap_or Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained `Ok` value or a provided default. Arguments are eagerly evaluated. ```APIDOC ## pub fn unwrap_or(self, default: T) -> T Returns the contained `Ok` value or a provided default. Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use `unwrap_or_else`, which is lazily evaluated. ### Parameters #### Path Parameters - **default** (T) - The default value to return if `self` is `Err`. ### Examples ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` ``` -------------------------------- ### Create Slice Instance Source: https://docs.rs/postcard/latest/postcard/de_flavors/struct.Slice.html Creates a new Slice deserialization flavor from a given byte buffer. This is the entry point for deserializing from a slice. ```rust pub fn new(sli: &'de [u8]) -> Self ``` -------------------------------- ### ok Source: https://docs.rs/postcard/latest/postcard/type.Result.html Converts from `Result` to `Option`, consuming the result and discarding the error if any. ```APIDOC ## ok ### Description Converts from `Result` to `Option`, consuming the result and discarding the error if any. ### Method `ok` ### Parameters None ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ### Response #### Success Response - **Option**: `Some(T)` if the result was `Ok`, `None` if the result was `Err`. #### Response Example ```json Some(2) ``` ``` -------------------------------- ### TryFrom Implementation Source: https://docs.rs/postcard/latest/postcard/ser_flavors/crc/struct.CrcModifier.html Enables attempting to create a CrcModifier from another type, with error handling. ```APIDOC ## impl TryFrom for T where U: Into, ### type Error = Infallible The type returned in the event of a conversion error. ### fn try_from(value: U) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Basic Usage of serialize_with_flavor with Cobs and Slice Source: https://docs.rs/postcard/latest/postcard/fn.serialize_with_flavor.html Demonstrates how to serialize a byte slice using the COBS encoding flavor with a slice as the underlying storage. Ensure the buffer is large enough to hold the serialized data. The `Cobs` flavor adds a zero byte at the end of the output. ```rust use postcard::{ serialize_with_flavor, ser_flavors::{Cobs, Slice}, }; let mut buf = [0u8; 32]; let data: &[u8] = &[0x01, 0x00, 0x20, 0x30]; let buffer = &mut [0u8; 32]; let res = serialize_with_flavor::<[u8], Cobs, &mut [u8]>( data, Cobs::try_new(Slice::new(buffer)).unwrap(), ).unwrap(); assert_eq!(res, &[0x03, 0x04, 0x01, 0x03, 0x20, 0x30, 0x00]); ``` -------------------------------- ### serialize_seq Source: https://docs.rs/postcard/latest/postcard/struct.Serializer.html Begin to serialize a variably sized sequence. This call must be followed by zero or more calls to `serialize_element`, then a call to `end`. ```APIDOC ## serialize_seq ### Description Begin to serialize a variably sized sequence. This call must be followed by zero or more calls to `serialize_element`, then a call to `end`. ### Method `(self, len: Option) -> Result` ``` -------------------------------- ### to_extend Source: https://docs.rs/postcard/latest/postcard/index.html Serialize a `T` to a `core::iter::Extend`. ```APIDOC ## to_extend ### Description Serialize a `T` to a `core::iter::Extend`. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **()** - Indicates successful serialization. #### Response Example None ``` -------------------------------- ### Deserializer::from_flavor Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Obtains a Deserializer instance from a given flavor. This is a generic way to create a Deserializer, allowing for different deserialization strategies. ```APIDOC ## Deserializer::from_flavor ### Description Obtain a Deserializer from a slice of bytes. ### Method `Self::from_flavor(flavor: F) -> Self` ### Parameters * `flavor` (F) - The flavor to use for deserialization. ``` -------------------------------- ### try_from Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Performs a fallible conversion from one type to another. ```APIDOC ## fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. This method is part of the `TryFrom` trait, allowing for fallible type conversions. ### Method N/A (Method of the `TryFrom` trait) ### Parameters * **value** (U) - The value to be converted. ``` -------------------------------- ### AllocVec::new() Constructor Source: https://docs.rs/postcard/latest/postcard/ser_flavors/type.StdVec.html Creates a new, empty `alloc::vec::Vec` for storing serialized output. This requires the `alloc` crate feature. ```rust pub fn new() -> Self ``` -------------------------------- ### serialize_with_flavor Source: https://docs.rs/postcard/latest/postcard/index.html `serialize_with_flavor()` has three generic parameters, `T, F, O`. ```APIDOC ## serialize_with_flavor ### Description `serialize_with_flavor()` has three generic parameters, `T, F, O`. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **Serialized Output** - The serialized data. #### Response Example None ``` -------------------------------- ### from Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Returns the argument unchanged. Used for type conversion. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. This is a core method for the `From` trait, enabling direct type conversions. ### Method N/A (Method of the `From` trait) ### Parameters * **t** (T) - The value to be converted. ``` -------------------------------- ### Deserialize from a byte slice using Slice flavor Source: https://docs.rs/postcard/latest/postcard/de_flavors/index.html Demonstrates how to use the `Slice` flavor to deserialize data directly from a `[u8]` slice. This is useful when the serialized data is available as a byte array and no other modifications are needed. ```rust use postcard::{ de_flavors::Slice, Deserializer, }; use serde::Deserialize; #[derive(Deserialize, Debug, PartialEq)] struct Tup(u8, u8, u8); let msg = [0x04, 0x00, 0x04, 0x01, 0x02, 0x03]; let slice = Slice::new(&msg); let mut deserializer = Deserializer::from_flavor(slice); let t = Tup::deserialize(&mut deserializer).unwrap(); assert_eq!(t, Tup(4, 0, 0)); let remainder = deserializer.finalize().unwrap(); assert_eq!(remainder, &[1, 2, 3]); ``` -------------------------------- ### Serialize Data to heapless::Vec Source: https://docs.rs/postcard/latest/postcard/fn.to_vec.html Demonstrates serializing various data types (boolean, string, byte slices) into a `heapless::Vec` using the `to_vec` function. Note the different handling of `&[u8]` and `&[u8; N]`. ```rust use postcard::to_vec; use heapless::Vec; use core::ops::Deref; let ser: Vec = to_vec(&true).unwrap(); assert_eq!(ser.deref(), &[0x01]); let ser: Vec = to_vec("Hi!").unwrap(); assert_eq!(ser.deref(), &[0x03, b'H', b'i', b'!']); // NOTE: postcard handles `&[u8]` and `&[u8; N]` differently. let data: &[u8] = &[0x01u8, 0x00, 0x20, 0x30]; let ser: Vec = to_vec(data).unwrap(); assert_eq!(ser.deref(), &[0x04, 0x01, 0x00, 0x20, 0x30]); let data: &[u8; 4] = &[0x01u8, 0x00, 0x20, 0x30]; let ser: Vec = to_vec(data).unwrap(); assert_eq!(ser.deref(), &[0x01, 0x00, 0x20, 0x30]); ``` -------------------------------- ### try_into Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Performs a fallible conversion from one type to another. ```APIDOC ## fn try_into(self) -> Result>::Error> ### Description Performs the conversion. This method is part of the `TryInto` trait, enabling fallible type conversions by leveraging the corresponding `TryFrom` implementation. ### Method N/A (Method of the `TryInto` trait) ### Parameters None ``` -------------------------------- ### MaxSize for five-element tuple Source: https://docs.rs/postcard/latest/postcard/experimental/max_size/trait.MaxSize.html Implementation of MaxSize for a five-element tuple. The maximum size is the sum of the elements' MaxSize. ```rust impl MaxSize for (A, B, C, D, E) { const POSTCARD_MAX_SIZE: usize } ``` -------------------------------- ### expect Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## expect ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`, with a panic message including the passed message and the content of the `Err`. ### Method `expect` ### Parameters - `msg`: The message to include in the panic if the `Result` is an `Err`. ### Returns The contained `Ok` value. ### Panics Panics if the value is an `Err`. ### Example ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ### Recommended Message Style We recommend that `expect` messages are used to describe the reason you _expect_ the `Result` should be `Ok`. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` ``` -------------------------------- ### serialize_i32 Source: https://docs.rs/postcard/latest/postcard/struct.Serializer.html Serialize an `i32` value. ```APIDOC ## serialize_i32 ### Description Serialize an `i32` value. ### Method `(self, v: i32) -> Result<()>` ``` -------------------------------- ### Unwrap or Default Value Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value or a default value if Err. Useful for parsing user input. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### serialize_map Source: https://docs.rs/postcard/latest/postcard/struct.Serializer.html Begins the serialization of a map. This method should be followed by calls to `serialize_key` and `serialize_value`, and finally `end`. ```APIDOC ## serialize_map ### Description Begin to serialize a map. This call must be followed by zero or more calls to `serialize_key` and `serialize_value`, then a call to `end`. ### Method (Implicitly part of a serialization process) ### Parameters * `len`: Option - The expected number of key-value pairs in the map. ### Response * `Result` - A type that allows for subsequent key-value pair serialization. ``` -------------------------------- ### unwrap Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## unwrap ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`. Panics are meant for unrecoverable errors, and may abort the entire program. ### Method `unwrap` ### Parameters None ### Returns The contained `Ok` value. ### Panics Panics if the value is an `Err`. ### Note Instead, prefer to use the `?` (try) operator, or pattern matching to handle the `Err` case explicitly, or call `unwrap_or`, `unwrap_or_else`, or `unwrap_or_default`. ``` -------------------------------- ### TryInto Implementation Source: https://docs.rs/postcard/latest/postcard/ser_flavors/crc/struct.CrcModifier.html Allows attempting to convert a CrcModifier into another type, with error handling. ```APIDOC ## impl TryInto for T where U: TryFrom, ### type Error = >::Error The type returned in the event of a conversion error. ### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Converting Result to Option with Ok value Source: https://docs.rs/postcard/latest/postcard/type.Result.html The `ok()` method converts a `Result` into an `Option`. It consumes the Result and returns `Some(T)` if the Result was `Ok`, otherwise `None`. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### IOReader::new Source: https://docs.rs/postcard/latest/postcard/de_flavors/io/io/struct.IOReader.html Creates a new IOReader instance. It requires a reader that implements the `std::io::Read` trait and a mutable byte slice buffer. The buffer must be large enough to accommodate all data read during the deserialization process. ```APIDOC ## IOReader::new ### Description Creates a new `IOReader` from a reader and a buffer. `buff` must have enough space to hold all data read during the deserialisation. ### Signature ```rust pub fn new(reader: T, buff: &'de mut [u8]) -> Self ``` ### Parameters #### Path Parameters - **reader** (T): A type implementing `std::io::Read`. - **buff** (&'de mut [u8]): A mutable byte slice buffer with sufficient capacity. ### Returns - Self: A new `IOReader` instance. ``` -------------------------------- ### Obtain Deserializer from Flavor Source: https://docs.rs/postcard/latest/postcard/struct.Deserializer.html Creates a `Deserializer` instance from a given `Flavor`. This is useful when you have a specific deserialization plugin to use. ```rust pub fn from_flavor(flavor: F) -> Self ``` -------------------------------- ### to_eio Source: https://docs.rs/postcard/latest/postcard/index.html Serialize a `T` to an `embedded_io Write`. ```APIDOC ## to_eio ### Description Serialize a `T` to an `embedded_io Write`. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **()** - Indicates successful serialization. #### Response Example None ``` -------------------------------- ### as_ref Source: https://docs.rs/postcard/latest/postcard/type.Result.html Converts from `&Result` to `Result<&T, &E>`, producing a new `Result` containing references. ```APIDOC ## as_ref ### Description Converts from `&Result` to `Result<&T, &E>`, producing a new `Result` containing references into the original, leaving the original in place. ### Method `as_ref` ### Parameters None ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ### Response #### Success Response - **Result<&T, &E>**: A `Result` containing references to the contained value or error. #### Response Example ```json Ok(2) ``` ``` -------------------------------- ### EIOReader::new Source: https://docs.rs/postcard/latest/postcard/de_flavors/io/eio/struct.EIOReader.html Creates a new EIOReader instance. It takes a generic reader `T` that implements `embedded_io::Read` and a mutable byte slice buffer `buff`. The buffer must be large enough to hold all data read during deserialization. ```APIDOC ## pub fn new(reader: T, buff: &'de mut [u8]) -> Self ### Description Create a new `EIOReader` from a reader and a buffer. `buff` must have enough space to hold all data read during the deserialisation. ### Parameters #### Path Parameters - **reader** (T): A type implementing `embedded_io::Read`. - **buff** (&'de mut [u8]): A mutable byte slice buffer. ### Returns - Self: A new `EIOReader` instance. ``` -------------------------------- ### MaxSize for () Source: https://docs.rs/postcard/latest/postcard/experimental/max_size/trait.MaxSize.html Implementation of MaxSize for the unit type. The maximum serialization size for the unit type is 0 bytes. ```rust impl MaxSize for () { const POSTCARD_MAX_SIZE: usize = 0usize; } ``` -------------------------------- ### Create New Slice Flavor Source: https://docs.rs/postcard/latest/postcard/ser_flavors/struct.Slice.html Creates a new `Slice` flavor instance using a provided mutable byte slice as the backing buffer. ```rust pub fn new(buf: &'a mut [u8]) -> Self ``` -------------------------------- ### Flavor Required Method: try_take_n Source: https://docs.rs/postcard/latest/postcard/de_flavors/trait.Flavor.html Attempts to take the next `ct` bytes from the serialized message. This method supports zero-copy deserialization by borrowing directly from the input. ```rust fn try_take_n(&mut self, ct: usize) -> Result<&'de [u8]>; ``` -------------------------------- ### CrcModifier::new Source: https://docs.rs/postcard/latest/postcard/ser_flavors/crc/struct.CrcModifier.html Creates a new CrcModifier flavor. This flavor is available only when the `use-crc` crate feature is enabled. ```APIDOC ## `CrcModifier::new` ### Description Creates a new CRC modifier flavor. ### Method `new` ### Signature `pub fn new(bee: B, digest: Digest<'a, W>) -> Self` ### Parameters * `bee`: An existing flavor of type `B` that implements the `Flavor` trait. * `digest`: A `Digest` object with a width type `W` that implements the `Width` trait, used for CRC calculation. ### Returns A new `CrcModifier` instance. ``` -------------------------------- ### unwrap_or_default Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value or a default value if the Result is Err. ```APIDOC ## unwrap_or_default ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ### Method `unwrap_or_default()` ### Parameters None ### Request Example ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` ### Response #### Success Response - **T** (type) - The contained Ok value or the default value if the Result is Err. #### Response Example ```rust 1909 // or 0 for bad input ``` ``` -------------------------------- ### From Implementation Source: https://docs.rs/postcard/latest/postcard/ser_flavors/crc/struct.CrcModifier.html Enables creating a CrcModifier from a value of the same type. ```APIDOC ## impl From for T ### fn from(t: T) -> T Returns the argument unchanged. ``` -------------------------------- ### unwrap Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the contained Ok value. Panics if the value is an Err, with a panic message provided by the Err's value. ```APIDOC ## unwrap ### Description Returns the contained `Ok` value. Panics if the value is an `Err`, with a panic message provided by the `Err`’s value. ### Method `unwrap()` ### Parameters None ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ### Response #### Success Response - **T** (type) - The contained Ok value. #### Response Example ```rust 2 ``` ### Error Handling Panics if the `Result` is an `Err`. ``` -------------------------------- ### Flavor Provided Method: size_hint Source: https://docs.rs/postcard/latest/postcard/de_flavors/trait.Flavor.html Returns an optional hint for the number of remaining bytes. Primarily for optimization, it should not be trusted for critical logic like bounds checks. ```rust fn size_hint(&self) -> Option { ... } ``` -------------------------------- ### serialize_i64 Source: https://docs.rs/postcard/latest/postcard/struct.Serializer.html Serialize an `i64` value. ```APIDOC ## serialize_i64 ### Description Serialize an `i64` value. ### Method `(self, v: i64) -> Result<()>` ``` -------------------------------- ### MaxSize for six-element tuple Source: https://docs.rs/postcard/latest/postcard/experimental/max_size/trait.MaxSize.html Implementation of MaxSize for a six-element tuple. The maximum size is the sum of the elements' MaxSize. ```rust impl MaxSize for (A, B, C, D, E, F) { const POSTCARD_MAX_SIZE: usize } ``` -------------------------------- ### Flavor Trait Implementation for EIOReader Source: https://docs.rs/postcard/latest/postcard/de_flavors/io/eio/struct.EIOReader.html This section details the implementation of the `Flavor` trait for `EIOReader`. It includes methods for finalizing deserialization, accessing data remnants, obtaining bytes, and checking size hints. ```APIDOC ### impl<'de, T> Flavor<'de> for EIOReader<'de, T> #### fn finalize(self) -> Result<(T, &'de mut [u8])> ##### Description Return the remaining (unused) bytes in the Deserializer. #### type Remainder = (T, &'de mut [u8]) ##### Description The remaining data of this flavor after deserializing has completed. #### type Source = &'de [u8] ##### Description The source of data retrieved for deserialization. #### fn pop(&mut self) -> Result ##### Description Obtain the next byte for deserialization. #### fn size_hint(&self) -> Option ##### Description Returns the number of bytes remaining in the message, if known. #### fn try_take_n(&mut self, ct: usize) -> Result<&'de [u8]> ##### Description Attempt to take the next `ct` bytes from the serialized message. #### fn try_take_n_temp<'a>(&'a mut self, ct: usize) -> Result<&'a [u8]> ##### Description Attempt to take the next `ct` bytes from the serialized message. ``` -------------------------------- ### MaxSize for nalgebra Matrix Source: https://docs.rs/postcard/latest/postcard/experimental/max_size/trait.MaxSize.html Implementation of MaxSize for nalgebra Matrix types, available on the `nalgebra-v0_33` feature. The maximum size is determined by the matrix dimensions and element type. ```rust impl MaxSize for Matrix, Const, ArrayStorage> where T: MaxSize + Scalar, Available on **crate feature`nalgebra-v0_33`** only. Source§ #### const POSTCARD_MAX_SIZE: usize ``` -------------------------------- ### Serialize to a Slice using Postcard Source: https://docs.rs/postcard/latest/postcard/ser_flavors/index.html Demonstrates using the `Slice` flavor to store serialized data directly into a mutable `[u8]` slice. This is useful for in-place serialization without dynamic allocation. ```rust use postcard::{ serialize_with_flavor, ser_flavors::Slice, }; let mut buf = [0u8; 32]; let data: &[u8] = &[0x01, 0x00, 0x20, 0x30]; let buffer = &mut [0u8; 32]; let res = serialize_with_flavor::<[u8], Slice, &mut [u8]>( data, Slice::new(buffer) ).unwrap(); assert_eq!(res, &[0x04, 0x01, 0x00, 0x20, 0x30]); ``` -------------------------------- ### Converting Result to Result<&str, &u32> Source: https://docs.rs/postcard/latest/postcard/type.Result.html Illustrates converting a `Result` containing a `String` to a `Result` containing a `&str` using `as_deref`. This is useful when you need to work with string slices instead of owned strings within a `Result`. ```Rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### And: Combine Results (Eager Evaluation) Source: https://docs.rs/postcard/latest/postcard/type.Result.html Returns the second Result if the first is Ok, otherwise returns the first Err. Arguments are eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ```