Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Zerompk
https://docs.rs/zerompk/0.7.1/zerompk/
Admin
Zerompk is a Rust library for zero-copy MessagePack serialization and deserialization.
Tokens:
11,885
Snippets:
112
Trust Score:
9.1
Update:
1 month ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Implementing ToMessagePack for a Custom Struct Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Write.html Example showing how to implement the ToMessagePack trait for a custom struct using the Write trait methods. ```rust use zerompk::{ToMessagePack, Write, Result}; struct Point { x: i32, y: i32, } impl ToMessagePack for Point { fn write<W: Write>(&self, writer: &mut W) -> Result<()> { writer.write_array_len(2)?; writer.write_i32(self.x)?; writer.write_i32(self.y)?; Ok(()) } } ``` -------------------------------- ### Chain fallible operations with and_then Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Use and_then to chain operations that return a Result. The provided examples demonstrate handling successful values, overflow errors, and existing error states. ```rust assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` ```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 a struct to MessagePack Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.write_msgpack.html Demonstrates serializing a custom struct into a byte buffer using a cursor. ```rust #[derive(zerompk::ToMessagePack)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; let mut buf = Vec::new(); let mut cursor = std::io::Cursor::new(&mut buf); zerompk::write_msgpack(&mut cursor, &point).unwrap(); } ``` -------------------------------- ### expect Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Ok value, or panics if the result is Err. ```APIDOC ## pub fn expect(self, msg: &str) -> T ### 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`. ``` -------------------------------- ### Serialize a struct to MessagePack Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.to_msgpack.html Demonstrates serializing a custom struct into a fixed-size byte buffer using the to_msgpack function. ```rust #[derive(zerompk::ToMessagePack)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; let mut buf = [0u8; 10]; let bytes_written = zerompk::to_msgpack(&point, &mut buf).unwrap(); assert_eq!(bytes_written, 3); assert_eq!(&buf[..bytes_written], &[0x92, 0x01, 0x02]); } ``` -------------------------------- ### Deserializing a struct with read_msgpack Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.read_msgpack.html Demonstrates deserializing a custom struct from a byte vector using an I/O cursor. ```rust #[derive(zerompk::FromMessagePack)] struct Point { x: i32, y: i32, } fn main() { let vec = vec![0x92, 0x01, 0x02]; let mut cursor = std::io::Cursor::new(vec); let point: Point = zerompk::read_msgpack(&mut cursor).unwrap(); assert_eq!(point.x, 1); assert_eq!(point.y, 2); } ``` -------------------------------- ### Unwrap Result or Default Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the Ok value or the default value of the type if the result is Err. ```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); ``` -------------------------------- ### pub fn unwrap_or_default(self) -> T Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Ok value or a default value if the result is an Err. ```APIDOC ## pub fn unwrap_or_default(self) -> T ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ### Examples ```rust let good_year_from_input = "1909"; let good_year = good_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); ``` ``` -------------------------------- ### pub fn unwrap(self) -> T Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn unwrap(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`, with a panic message provided by the `Err`’s value. ### Examples ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.unwrap(), 2); ``` ``` -------------------------------- ### pub fn and_then<U, F>(self, op: F) -> Result<U, E> Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Calls op if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and_then<U, F>(self, op: F) -> Result<U, E> ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. This function can be used for control flow based on `Result` values. ``` -------------------------------- ### Serialize a struct to MessagePack Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.to_msgpack_vec.html Demonstrates serializing a custom struct that derives ToMessagePack into a byte vector. ```rust #[derive(zerompk::ToMessagePack)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; let msgpack: Vec<u8> = zerompk::to_msgpack_vec(&point).unwrap(); assert_eq!(msgpack, vec![0x92, 0x01, 0x02]); } ``` -------------------------------- ### Deserializing sequential values with read_msgpack_bufread Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.read_msgpack_bufread.html Demonstrates reading multiple consecutive MessagePack values from a BufReader without losing data. ```rust let data = [0x01, 0x02]; let mut reader = std::io::BufReader::new(data.as_slice()); let first: u8 = zerompk::read_msgpack_bufread(&mut reader).unwrap(); let second: u8 = zerompk::read_msgpack_bufread(&mut reader).unwrap(); assert_eq!((first, second), (1, 2)); ``` -------------------------------- ### Chain Result with And Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the provided result if the current result is Ok, otherwise returns the Err value. ```rust let x: Result<u32, &str> = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result<u32, &str> = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result<u32, &str> = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result<u32, &str> = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Into Ok Value Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Extracts the Ok value without risk of panicking, useful for infallible Result types. ```rust fn only_good_news() -> Result<String, !> { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Deserializing a struct from MessagePack Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.from_msgpack.html Demonstrates how to derive FromMessagePack for a custom struct and deserialize it from a byte vector. ```rust #[derive(zerompk::FromMessagePack)] struct Point { x: i32, y: i32, } fn main() { let msgpack = vec![0x92, 0x01, 0x02]; let point: Point = zerompk::from_msgpack(&msgpack).unwrap(); assert_eq!(point.x, 1); assert_eq!(point.y, 2); } ``` -------------------------------- ### pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns res if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. Arguments passed to `and` are eagerly evaluated. ``` -------------------------------- ### Fallback to alternative Result with or Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the alternative Result if the current one is an Err. Note that arguments are evaluated eagerly. ```rust let x: Result<u32, &str> = Ok(2); let y: Result<u32, &str> = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result<u32, &str> = Err("early error"); let y: Result<u32, &str> = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result<u32, &str> = Err("not a 2"); let y: Result<u32, &str> = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result<u32, &str> = Ok(2); let y: Result<u32, &str> = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### pub fn to_msgpack<T: ToMessagePack>(value: &T, buf: &mut [u8]) -> Result<usize> Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.to_msgpack.html Serializes a value of type T into the provided buffer, returning the number of bytes written. Serialization can fail if the implementation returns an error or if the buffer is too small. ```APIDOC ## Function: to_msgpack ### Description Serializes a value of type `T` into the provided buffer, returning the number of bytes written. ### Signature `pub fn to_msgpack<T: ToMessagePack>(value: &T, buf: &mut [u8]) -> Result<usize>` ### Parameters - **value** (&T) - The value to serialize, must implement `ToMessagePack`. - **buf** (&mut [u8]) - The mutable byte buffer to write the serialized data into. ### Returns - **Result<usize>** - Returns the number of bytes written on success, or an error if serialization fails or the buffer is too small. ### Example ```rust #[derive(zerompk::ToMessagePack)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; let mut buf = [0u8; 10]; let bytes_written = zerompk::to_msgpack(&point, &mut buf).unwrap(); assert_eq!(bytes_written, 3); assert_eq!(&buf[..bytes_written], &[0x92, 0x01, 0x02]); } ``` ``` -------------------------------- ### pub fn write_msgpack<T: ToMessagePack, W: Write>(writer: &mut W, value: &T) -> Result<()> Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.write_msgpack.html Serializes a value of type T into the I/O stream. Serialization can fail if T's implementation of ToMessagePack returns an error, or if the underlying I/O operation fails. ```APIDOC ## Function: write_msgpack ### Description Serializes a value of type `T` into the I/O stream. ### Signature `pub fn write_msgpack<T: ToMessagePack, W: Write>(writer: &mut W, value: &T) -> Result<()>` ### Parameters - **writer** (&mut W) - The I/O stream to write the serialized data to. - **value** (&T) - The value to be serialized, which must implement the `ToMessagePack` trait. ### Errors Serialization can fail if `T`’s implementation of `ToMessagePack` returns an error, or if the underlying I/O operation fails. ### Example ```rust #[derive(zerompk::ToMessagePack)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; let mut buf = Vec::new(); let mut cursor = std::io::Cursor::new(&mut buf); zerompk::write_msgpack(&mut cursor, &point).unwrap(); } ``` ``` -------------------------------- ### Write Trait Definition Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Write.html The core trait definition outlining all required methods for MessagePack serialization. ```rust pub trait Write { Show 18 methods // Required methods fn write_nil(&mut self) -> Result<()>; fn write_boolean(&mut self, b: bool) -> Result<()>; fn write_u8(&mut self, u: u8) -> Result<()>; fn write_u16(&mut self, u: u16) -> Result<()>; fn write_u32(&mut self, u: u32) -> Result<()>; fn write_u64(&mut self, u: u64) -> Result<()>; fn write_i8(&mut self, i: i8) -> Result<()>; fn write_i16(&mut self, i: i16) -> Result<()>; fn write_i32(&mut self, i: i32) -> Result<()>; fn write_i64(&mut self, i: i64) -> Result<()>; fn write_f32(&mut self, f: f32) -> Result<()>; fn write_f64(&mut self, f: f64) -> Result<()>; fn write_string(&mut self, s: &str) -> Result<()>; fn write_binary(&mut self, data: &[u8]) -> Result<()>; fn write_timestamp(&mut self, seconds: i64, nanoseconds: u32) -> Result<()>; fn write_array_len(&mut self, len: usize) -> Result<()>; fn write_map_len(&mut self, len: usize) -> Result<()>; fn write_ext(&mut self, type_id: i8, data: &[u8]) -> Result<()>; } ``` -------------------------------- ### Collect Result from Iterator Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Demonstrates collecting an iterator of Results into a Result of a collection, short-circuiting on the first error. ```rust let v = vec![1, 2]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### pub fn unwrap_err(self) -> E Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Err value, panicking if the result is an Ok. ```APIDOC ## pub fn unwrap_err(self) -> E ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`, with a custom panic message provided by the `Ok`’s value. ``` -------------------------------- ### Convert Result to Option Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Methods to convert Result into Option by either keeping the Ok value or the Err value. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result<u32, &str> = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.err(), None); let x: Result<u32, &str> = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Map Result to Default or Fallback Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Methods to handle Result by providing a default value or a fallback function. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Expect Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the Ok value or panics with a provided message if the result is Err. ```rust let x: Result<u32, &str> = 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`"); ``` -------------------------------- ### Reference Conversion for Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Methods to obtain references to the inner values of a Result. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result<u32, &str> = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result<i32, i32>) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result<i32, i32> = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result<i32, i32> = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Implement depth tracking for nested structures Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Read.html Use increment_depth and decrement_depth within FromMessagePack implementations to track recursion depth and prevent stack overflows. ```rust use zerompk::{Read, FromMessagePack, Result}; struct Outer { inner: Inner, } struct Inner { value: i32, } impl<'de> FromMessagePack<'de> for Outer { fn read<R: Read<'de>>(reader: &mut R) -> Result<Self> { reader.increment_depth()?; let inner = Inner::read(reader)?; reader.decrement_depth(); Ok(Self { inner }) } } impl<'de> FromMessagePack<'de> for Inner { fn read<R: Read<'de>>(reader: &mut R) -> Result<Self> { reader.increment_depth()?; let value = reader.read_i32()?; reader.decrement_depth(); Ok(Self { value }) } } ``` -------------------------------- ### Inspect Ok Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Executes a closure with a reference to the Ok value without modifying the result. ```rust let x: u8 = "4" .parse::<u8>() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Methods to copy or clone the contents of a Result containing a reference. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### to_msgpack Source: https://docs.rs/zerompk/0.7.1/zerompk/index.html Serializes a value of type T into the provided buffer. ```APIDOC ## to_msgpack<T, W>(value: &T, writer: W) -> Result<usize> ### Description Serializes a value of type T into the provided buffer, returning the number of bytes written. ### Parameters - **value** (&T) - Required - The value to serialize. - **writer** (W) - Required - The buffer or writer to serialize into. ``` -------------------------------- ### pub fn expect_err(self, msg: &str) -> E Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Err value, panicking if the result is an Ok. ```APIDOC ## pub fn expect_err(self, msg: &str) -> E ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`, with a panic message including the passed message, and the content of the `Ok`. ``` -------------------------------- ### as_deref_mut Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Converts from Result<T, E> to Result<&mut <T as DerefMut>::Target, &mut E>. ```APIDOC ## pub fn as_deref_mut(&mut self) -> Result<&mut <T as DerefMut>::Target, &mut E> ### Description Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`. Coerces the `Ok` variant of the original `Result` via `DerefMut` and returns the new `Result`. ``` -------------------------------- ### Provide default value with unwrap_or Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained value or a provided default. Use unwrap_or_else for lazy evaluation of the default. ```rust let default = 2; let x: Result<u32, &str> = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result<u32, &str> = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### inspect Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Calls a function with a reference to the contained value if Ok, returning the original result. ```APIDOC ## pub fn inspect<F>(self, f: F) -> Result<T, E> ### Description Calls a function with a reference to the contained value if `Ok`. Returns the original result. ``` -------------------------------- ### as_deref Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Converts from Result<T, E> to Result<&<T as Deref>::Target, &E>. ```APIDOC ## pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E> ### Description Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`. Coerces the `Ok` variant of the original `Result` via `Deref` and returns the new `Result`. ``` -------------------------------- ### write_msgpack Source: https://docs.rs/zerompk Serializes a value of type T into the I/O stream. ```APIDOC ## write_msgpack ### Description Serializes a value of type `T` into the I/O stream. ### Signature `pub fn write_msgpack<W, T>(writer: W, value: &T) -> Result<()> where W: Write` ``` -------------------------------- ### Chain Result with And Then Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Calls a function if the result is Ok, allowing for lazy evaluation and complex control flow. ```rust fn sq_then_to_string(x: u32) -> Result<String, &'static str> { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### pub fn read_msgpack<'a, R: Read, T: FromMessagePack<'a>>(reader: R) -> Result<T> Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.read_msgpack.html Deserializes a value of type T from the provided I/O stream. The type T must implement the FromMessagePack trait. ```APIDOC ## read_msgpack ### Description Deserializes a value of type `T` from the I/O stream. This function reads from a type that implements `std::io::Read` and converts the MessagePack data into the specified type `T`. ### Signature `pub fn read_msgpack<'a, R: Read, T: FromMessagePack<'a>>(reader: R) -> Result<T>` ### Errors Deserialization can fail if `T`’s implementation of `FromMessagePack` returns an error, or if the underlying I/O operation fails. ### Example ```rust #[derive(zerompk::FromMessagePack)] struct Point { x: i32, y: i32, } fn main() { let vec = vec![0x92, 0x01, 0x02]; let mut cursor = std::io::Cursor::new(vec); let point: Point = zerompk::read_msgpack(&mut cursor).unwrap(); assert_eq!(point.x, 1); assert_eq!(point.y, 2); } ``` ``` -------------------------------- ### from_msgpack Source: https://docs.rs/zerompk/0.7.1/zerompk/index.html Deserializes a value of type T from a MessagePack-encoded byte slice. ```APIDOC ## from_msgpack<T>(bytes: &[u8]) -> Result<T> ### Description Deserializes a value of type T from a MessagePack-encoded byte slice. ### Parameters - **bytes** (&[u8]) - Required - The byte slice containing the MessagePack-encoded data. ``` -------------------------------- ### read_msgpack Source: https://docs.rs/zerompk/0.7.1/zerompk/index.html Deserializes a value of type T from an I/O stream. ```APIDOC ## read_msgpack<R, T>(reader: R) -> Result<T> ### Description Deserializes a value of type T from the provided I/O stream. ### Parameters - **reader** (R) - Required - The I/O stream to read from. ``` -------------------------------- ### Map Result Values Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Transform the Ok value of a Result using a function. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::<i32>().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Read Trait Definition Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Read.html The core trait definition for reading MessagePack data, including required and provided methods. ```rust pub trait Read<'de> { Show 29 methods // Required methods fn peek_marker(&mut self) -> Result<u8>; fn increment_depth(&mut self) -> Result<()>; fn decrement_depth(&mut self); fn read_nil(&mut self) -> Result<()>; fn read_boolean(&mut self) -> Result<bool>; fn read_u8(&mut self) -> Result<u8>; fn read_u16(&mut self) -> Result<u16>; fn read_u32(&mut self) -> Result<u32>; fn read_u64(&mut self) -> Result<u64>; fn read_i8(&mut self) -> Result<i8>; fn read_i16(&mut self) -> Result<i16>; fn read_i32(&mut self) -> Result<i32>; fn read_i64(&mut self) -> Result<i64>; fn read_f32(&mut self) -> Result<f32>; fn read_f64(&mut self) -> Result<f64>; fn read_timestamp(&mut self) -> Result<(i64, u32)>; fn read_array_len(&mut self) -> Result<usize>; fn read_map_len(&mut self) -> Result<usize>; fn read_ext_len(&mut self) -> Result<(i8, usize)>; fn read_ext(&mut self) -> Result<(i8, Cow<'de, [u8]>)>; fn read_string(&mut self) -> Result<Cow<'de, str>>; fn read_string_bytes(&mut self) -> Result<Cow<'de, [u8]>>; fn read_binary(&mut self) -> Result<Cow<'de, [u8]>>; fn read_option<T: FromMessagePack<'de>>(&mut self) -> Result<Option<T>>; fn read_tag(&mut self) -> Result<Tag<'de>>; fn skip_value(&mut self) -> Result<()>; // Provided methods fn read_array<T: FromMessagePack<'de>>( &mut self, out: &mut Vec<T>, ) -> Result<()> where Self: Sized { ... } fn check_array_len(&mut self, expected: usize) -> Result<()> { ... } fn check_map_len(&mut self, expected: usize) -> Result<()> { ... } } ``` -------------------------------- ### Unwrap Error from Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the Err value or panics if the result is Ok. ```rust let x: Result<u32, &str> = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result<u32, &str> = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### check_array_len Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Read.html Validates that the next value in the input is an array of the expected length and consumes the array header. ```APIDOC ## fn check_array_len(&mut self, expected: usize) -> Result<()> ### Description Validates that the next value in the input is an array of the expected length, and consumes the array header. ``` -------------------------------- ### Unwrap Result Value Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Extracts the Ok value or panics if the result is Err. Use with caution as it may cause program termination. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result<u32, &str> = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Check Result with is_err_and Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns true if the result is Err and the contained value matches the provided predicate. ```rust use std::io::{Error, ErrorKind}; let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result<u32, Error> = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result<u32, String> = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Expect Error from Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the Err value or panics with a custom message if the result is Ok. ```rust let x: Result<u32, &str> = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Methods to inspect the state of a Result. ```rust let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result<u32, &str> = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result<u32, &str> = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result<String, &str> = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` ```rust let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_err(), false); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### check_map_len Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Read.html Validates that the next value in the input is a map of the expected length and consumes the map header. ```APIDOC ## fn check_map_len(&mut self, expected: usize) -> Result<()> ### Description Validates that the next value in the input is a map of the expected length, and consumes the map header. ``` -------------------------------- ### iter Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns an iterator over the possibly contained value. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the possibly contained value. The iterator yields one value if the result is `Result::Ok`, otherwise none. ``` -------------------------------- ### Define FromMessagePack Trait Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.FromMessagePack.html The core trait definition requiring a read method to deserialize data from a reader. ```rust pub trait FromMessagePack<'a> where Self: Sized, { // Required method fn read<R: Read<'a>>(reader: &mut R) -> Result<Self>; } ``` -------------------------------- ### inspect_err Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Calls a function with a reference to the contained value if Err, returning the original result. ```APIDOC ## pub fn inspect_err<F>(self, f: F) -> Result<T, E> ### Description Calls a function with a reference to the contained value if `Err`. Returns the original result. ``` -------------------------------- ### Iterate Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Creates an iterator that yields the contained value if the result is Ok. ```rust let x: Result<u32, &str> = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result<u32, &str> = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Transposing Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Transposes a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result<Option<i32>, SomeErr> = Ok(Some(5)); let y: Option<Result<i32, SomeErr>> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Calculate Product of Result Iterator Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Multiplies numbers from an iterator of Results, returning an Err if any parsing fails. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product(); assert!(total.is_err()); ``` -------------------------------- ### pub unsafe fn unwrap_unchecked(self) -> T Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Ok value, consuming the self value, without checking that the value is not an Err. Calling this method on an Err is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_unchecked(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value, without checking that the value is not an `Err`. ### Safety Calling this method on an `Err` is _undefined behavior_. ``` -------------------------------- ### Compute default value with unwrap_or_else Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained value or computes it from a closure if the result is an Err. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### to_msgpack_vec Source: https://docs.rs/zerompk/0.7.1/zerompk/index.html Serializes a value of type T into a Vec<u8>. ```APIDOC ## to_msgpack_vec<T>(value: &T) -> Result<Vec<u8>> ### Description Serializes a value of type T into a Vec<u8> containing its MessagePack representation. ### Parameters - **value** (&T) - Required - The value to serialize. ``` -------------------------------- ### IntoIterator Implementation Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Converts a Result into an iterator that yields the contained value if Ok, or nothing if Err. ```rust let x: Result<u32, &str> = Ok(5); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result<u32, &str> = Err("nothing!"); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### pub unsafe fn unwrap_err_unchecked(self) -> E Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns the contained Err value, consuming the self value, without checking that the value is not an Ok. Calling this method on an Ok is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_err_unchecked(self) -> E ### Description Returns the contained `Err` value, consuming the `self` value, without checking that the value is not an `Ok`. ### Safety Calling this method on an `Ok` is _undefined behavior_. ``` -------------------------------- ### read_msgpack_bufread Source: https://docs.rs/zerompk/0.7.1/zerompk/fn.read_msgpack_bufread.html Deserializes a value of type T from a buffered I/O stream using the BufRead trait. ```APIDOC ## pub fn read_msgpack_bufread<'a, R: BufRead, T: FromMessagePack<'a>>(reader: &mut R) -> Result<T> ### Description Deserializes a value of type `T` from a buffered I/O stream. This function reads directly from the slice exposed by `std::io::BufRead`, allowing consecutive MessagePack values to be decoded from the same reader without data loss. ### Parameters - **reader** (&mut R) - A mutable reference to a type implementing `std::io::BufRead`. ### Returns - **Result<T>** - Returns the deserialized value of type `T` or an error if deserialization or I/O fails. ### Errors - Fails if `T`'s `FromMessagePack` implementation returns an error. - Fails if the underlying I/O operation fails. ### Example ```rust let data = [0x01, 0x02]; let mut reader = std::io::BufReader::new(data.as_slice()); let first: u8 = zerompk::read_msgpack_bufread(&mut reader).unwrap(); let second: u8 = zerompk::read_msgpack_bufread(&mut reader).unwrap(); assert_eq!((first, second), (1, 2)); ``` ``` -------------------------------- ### Result Type Definition Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html The core definition of the Result type alias and its underlying enum structure. ```rust pub type Result<T> = Result<T, Error>; ``` ```rust pub enum Result<T> { Ok(T), Err(Error), } ``` -------------------------------- ### ToMessagePack Trait Definition Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.ToMessagePack.html The core trait definition requiring a write method for serialization. ```rust pub trait ToMessagePack { // Required method fn write<W: Write>(&self, writer: &mut W) -> Result<()>; } ``` -------------------------------- ### Define SliceReader struct Source: https://docs.rs/zerompk/0.7.1/zerompk/struct.SliceReader.html The definition of the SliceReader struct. ```rust pub struct SliceReader<'de> { /* private fields */ } ``` -------------------------------- ### Into Error Value Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Extracts the Err value without risk of panicking, useful for infallible Result types. ```rust fn only_bad_news() -> Result<!, String> { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Calculate Sum of Result Iterator Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Sums integers from an iterator of Results, returning an Err if a negative element is encountered. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result<i32, _> = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result<i32, _> = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### FromMessagePackOwned Trait Definition Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.FromMessagePackOwned.html The trait definition for types that can be deserialized from MessagePack without borrowing. ```rust pub trait FromMessagePackOwned: for<'a> FromMessagePack<'a> { } ``` -------------------------------- ### Flattening Nested Results Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Converts nested Result types into a single level of nesting. ```rust let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result<Result<&'static str, u32>, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Iterate Mut Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Creates a mutable iterator that yields the contained value if the result is Ok. ```rust let mut x: Result<u32, &str> = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result<u32, &str> = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Define Tag enum Source: https://docs.rs/zerompk/0.7.1/zerompk/enum.Tag.html The Tag enum definition used for MessagePack stream tags. ```rust pub enum Tag<'de> { Int(u64), String(Cow<'de, str>), } ``` -------------------------------- ### read_array<T> Source: https://docs.rs/zerompk/0.7.1/zerompk/trait.Read.html Reads an array into an existing Vec, reusing its allocation. On error, partially decoded elements are dropped and the vector is cleared. ```APIDOC ## fn read_array<T: FromMessagePack<'de>>(&mut self, out: &mut Vec<T>) -> Result<()> ### Description Reads an array into an existing `Vec`, reusing its allocation. On error, all partially decoded elements are dropped and `out` is left empty. ``` -------------------------------- ### map_err Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched. ```APIDOC ## pub fn map_err<F, O>(self, op: O) -> Result<T, F> ### Description Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a contained `Err` value, leaving an `Ok` value untouched. This function can be used to pass through a successful result while handling an error. ``` -------------------------------- ### iter_mut Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Returns a mutable iterator over the possibly contained value. ```APIDOC ## pub fn iter_mut(&mut self) -> IterMut<'_, T> ### Description Returns a mutable iterator over the possibly contained value. The iterator yields one value if the result is `Result::Ok`, otherwise none. ``` -------------------------------- ### Fallback to closure result with or_else Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Lazily evaluates a closure to provide an alternative Result if the current one is an Err. ```rust fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } fn err(x: u32) -> Result<u32, u32> { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### Inspect Err Result Source: https://docs.rs/zerompk/0.7.1/zerompk/type.Result.html Executes a closure with a reference to the Err value without modifying the result. ```rust use std::{fs, io}; fn read() -> io::Result<String> { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### Value Enum Definition Source: https://docs.rs/zerompk/0.7.1/zerompk/enum.Value.html The Value enum defines the structure for schema-less MessagePack data, utilizing Cow for efficient memory management of strings and binary data. ```rust pub enum Value<'de> { Nil, Boolean(bool), Unsigned(u64), Signed(i64), Float32(f32), Float64(f64), String(Cow<'de, str>), Binary(Cow<'de, [u8]>), Array(Vec<Self>), Map(Vec<(Self, Self)>), Extension(i8, Cow<'de, [u8]>), } ```