### Serialize and Deserialize Tuple with MessagePack in Rust Source: https://github.com/3hren/msgpack-rust/blob/master/rmp-serde/README.md Demonstrates basic serialization and deserialization of a Rust tuple to MessagePack format using `rmp_serde::to_vec` and `rmp_serde::from_slice`. This is a motivating example for the crate's functionality. ```rust let buf = rmp_serde::to_vec(&(42, "the Answer")).unwrap(); assert_eq!( vec![0x92, 0x2a, 0xaa, 0x74, 0x68, 0x65, 0x20, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72], buf ); assert_eq!((42, "the Answer"), rmp_serde::from_slice(&buf).unwrap()); ``` -------------------------------- ### Rust: Full Serialization and Deserialization with rmp-serde Source: https://context7.com/3hren/msgpack-rust/llms.txt This Rust code demonstrates a complete round-trip serialization and deserialization process using `rmp-serde`. It defines a complex struct with various data types (primitives, Option, Vec, HashMap, nested struct, enum) and serializes it to MessagePack bytes using `rmp_serde::to_vec` and `rmp_serde::to_vec_named`. It then deserializes the bytes back into the original struct using `rmp_serde::from_slice`, asserting that the decoded data matches the original. This example is suitable for applications needing efficient binary serialization. ```rust use serde::{Serialize, Deserialize}; use std::collections::HashMap; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct CompleteExample { // Primitive types flag: bool, count: u64, ratio: f64, name: String, // Optional value nickname: Option, // Collections tags: Vec, metadata: HashMap, // Nested struct nested: NestedData, // Enum status: Status, } #[derive(Debug, Serialize, Deserialize, PartialEq)] struct NestedData { id: u32, data: Vec, } #[derive(Debug, Serialize, Deserialize, PartialEq)] enum Status { Active, Inactive, Pending { reason: String }, } fn main() -> Result<(), Box> { let example = CompleteExample { flag: true, count: 1_000_000, ratio: 3.14159, name: "Test Record".to_string(), nickname: Some("test".to_string()), tags: vec!["rust".to_string(), "msgpack".to_string()], metadata: [("version".to_string(), 1), ("priority".to_string(), 5)] .into_iter().collect(), nested: NestedData { id: 42, data: vec![0xDE, 0xAD, 0xBE, 0xEF], }, status: Status::Pending { reason: "awaiting review".to_string() }, }; // Serialize let bytes = rmp_serde::to_vec(&example)?; println!("Serialized size: {} bytes", bytes.len()); // Compare with named format let named_bytes = rmp_serde::to_vec_named(&example)?; println!("Named format size: {} bytes", named_bytes.len()); // Deserialize let decoded: CompleteExample = rmp_serde::from_slice(&bytes)?; assert_eq!(example, decoded); println!("Round-trip successful!"); println!("Decoded: {:?}", decoded); // Named format is also deserializable let decoded_named: CompleteExample = rmp_serde::from_slice(&named_bytes)?; assert_eq!(example, decoded_named); Ok(()) } ``` -------------------------------- ### Low-Level Primitive Encoding in Rust Source: https://context7.com/3hren/msgpack-rust/llms.txt Provides examples of using the `rmp::encode` module for direct, low-level control over MessagePack encoding of primitive types. It covers encoding nil, booleans, integers, floats, strings, binary data, and array/map headers. ```rust use rmp::encode::{ write_nil, write_bool, write_sint, write_uint, write_f32, write_f64, write_str, write_bin, write_array_len, write_map_len, }; fn main() -> Result<(), Box> { let mut buf = Vec::new(); // Encode nil write_nil(&mut buf)?; assert_eq!(buf, [0xc0]); buf.clear(); // Encode boolean write_bool(&mut buf, true)?; assert_eq!(buf, [0xc3]); buf.clear(); // Encode integers (automatically picks compact representation) write_sint(&mut buf, 42)?; write_sint(&mut buf, 300)?; write_sint(&mut buf, -100)?; println!("Integers: {:x?}", buf); buf.clear(); // Encode floats write_f64(&mut buf, std::f64::consts::PI)?; assert_eq!(buf[0], 0xcb); // f64 marker buf.clear(); // Encode string write_str(&mut buf, "Hello, MessagePack!")?; println!("String: {:x?}", buf); buf.clear(); // Encode binary data write_bin(&mut buf, &[0xDE, 0xAD, 0xBE, 0xEF])?; println!("Binary: {:x?}", buf); buf.clear(); // Encode array header (elements follow separately) write_array_len(&mut buf, 3)?; write_sint(&mut buf, 1)?; write_sint(&mut buf, 2)?; write_sint(&mut buf, 3)?; println!("Array [1,2,3]: {:x?}", buf); buf.clear(); // Encode map header write_map_len(&mut buf, 2)?; write_str(&mut buf, "key1")?; write_sint(&mut buf, 100)?; write_str(&mut buf, "key2")?; write_bool(&mut buf, true)?; println!("Map: {:x?}", buf); Ok(()) } ``` -------------------------------- ### Deserialization from Bytes to Typed Structs (Rust) Source: https://context7.com/3hren/msgpack-rust/llms.txt Deserializes MessagePack data from a byte slice into typed Rust structures using `rmp_serde::from_slice`. It supports zero-copy deserialization for string and binary data when possible, reducing memory allocations. The example demonstrates deserializing into both borrowed and owned types. ```rust use serde::{Serialize, Deserialize}; #[derive(Debug, Deserialize, PartialEq)] struct Dog<'a> { name: &'a str, // Zero-copy borrowed string age: u8, } fn main() -> Result<(), Box> { // Pre-encoded MessagePack: ["Bobby", 8] let buf = [0x92, 0xa5, 0x42, 0x6f, 0x62, 0x62, 0x79, 0x08]; // Deserialize with zero-copy string borrowing let dog: Dog = rmp_serde::from_slice(&buf)?; assert_eq!(dog, Dog { name: "Bobby", age: 8 }); println!("Deserialized: {:?}", dog); // For owned data, use owned types #[derive(Debug, Deserialize)] struct OwnedDog { name: String, age: u8, } let owned: OwnedDog = rmp_serde::from_slice(&buf)?; println!("Owned: {:?}", owned); Ok(()) } ``` -------------------------------- ### Configure Struct Serialization as Maps in Rust Source: https://context7.com/3hren/msgpack-rust/llms.txt Demonstrates how to use `Serializer::with_struct_map` to serialize Rust structs as MessagePack maps with field names. This method offers more flexibility than the default tuple encoding. It also shows how to optimize binary data encoding using `with_bytes`. ```rust use serde::Serialize; use rmp_serde::Serializer; #[derive(Serialize)] struct User { username: String, email: String, verified: bool, } fn main() -> Result<(), Box> { let user = User { username: "johndoe".to_string(), email: "john@example.com".to_string(), verified: true, }; // Default: serialize as tuple (compact) let mut compact_buf = Vec::new(); user.serialize(&mut Serializer::new(&mut compact_buf))?; println!("Compact: {} bytes", compact_buf.len()); // With struct_map: serialize as map with field names let mut named_buf = Vec::new(); user.serialize(&mut Serializer::new(&mut named_buf).with_struct_map())?; println!("Named: {} bytes", named_buf.len()); // Efficient binary mode for byte arrays let mut bytes_buf = Vec::new(); let data: Vec = vec![0u8; 100]; data.serialize( &mut Serializer::new(&mut bytes_buf) .with_bytes(rmp_serde::config::BytesMode::ForceAll) )?; println!("Binary optimized: {} bytes", bytes_buf.len()); Ok(()) } ``` -------------------------------- ### Value Encoding and Decoding in Rust Source: https://context7.com/3hren/msgpack-rust/llms.txt Illustrates the encoding and decoding capabilities of the `rmpv` crate for the dynamic `Value` type. This snippet covers building complex nested data structures, serializing them to bytes, deserializing them back, and performing safe decoding with a maximum depth limit. ```rust use rmpv::{Value, decode, encode}; use std::io::Cursor; fn main() -> Result<(), Box> { // Build a complex nested structure let data = Value::Map(vec![ (Value::from("users"), Value::Array(vec![ Value::Map(vec![ (Value::from("name"), Value::from("Alice")), (Value::from("age"), Value::from(30u8)), ]), Value::Map(vec![ (Value::from("name"), Value::from("Bob")), (Value::from("age"), Value::from(25u8)), ]), ])), (Value::from("count"), Value::from(2u32)), ]); // Encode to bytes let mut buf = Vec::new(); encode::write_value(&mut buf, &data)?; println!("Encoded {} bytes", buf.len()); // Decode back to Value let mut cursor = Cursor::new(&buf); let decoded = decode::read_value(&mut cursor)?; assert_eq!(data, decoded); // Safe decoding with depth limit (prevents stack overflow on malicious data) let mut cursor = Cursor::new(&buf); let safe_decoded = decode::read_value_with_max_depth(&mut cursor, 100)?; println!("Safe decoded: {}", safe_decoded); // Access nested data if let Some(users) = decoded["users"].as_array() { for user in users { println!("User: {} (age {})", user["name"].as_str().unwrap_or("unknown"), user["age"].as_u64().unwrap_or(0) ); } } Ok(()) } ``` -------------------------------- ### Rust: MessagePack Integer Encoding Variants with rmp crate Source: https://context7.com/3hren/msgpack-rust/llms.txt Illustrates the use of `rmp::encode` for both automatic compact integer encoding and explicit fixed-size integer encoding in Rust. This provides control over the wire format size for integers. Dependencies include the `rmp` crate. ```rust use rmp::encode::{ write_pfix, write_nfix, // Fixed positive/negative integers write_u8, write_u16, write_u32, write_u64, // Explicit unsigned sizes write_i8, write_i16, write_i32, write_i64, // Explicit signed sizes write_uint, write_sint, // Auto-compact encoding }; fn main() -> Result<(), Box> { // Auto-compact encoding chooses smallest representation let mut compact = Vec::new(); write_sint(&mut compact, 42)?; write_sint(&mut compact, 200)?; write_sint(&mut compact, 300)?; write_sint(&mut compact, -50)?; println!("Compact encoding: {:x?}", compact); // Explicit fixed-size encoding let mut fixed = Vec::new(); // Force specific byte widths write_u8(&mut fixed, 42)?; write_u16(&mut fixed, 42)?; write_u32(&mut fixed, 42)?; write_u64(&mut fixed, 42)?; println!("Fixed u8/u16/u32/u64 encoding: {:x?}", fixed); // Compare sizes for the value 42 let mut bufs: Vec> = vec![vec![]; 5]; write_pfix(&mut bufs[0], 42)?; write_u8(&mut bufs[1], 42)?; write_u16(&mut bufs[2], 42)?; write_u32(&mut bufs[3], 42)?; write_u64(&mut bufs[4], 42)?; for (i, buf) in bufs.iter().enumerate() { println!("Format {}: {} bytes = {:x?}", i, buf.len(), buf); } Ok(()) } ``` -------------------------------- ### Encode Signed Integer Compactly in Rust using rmp Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md Shows how to encode a signed integer (300) using `rmp::encode::write_sint` in Rust, which aims to select the most compact representation for the given value. The output is verified against the expected MessagePack byte sequence. ```rust let mut buf = Vec::new(); rmp::encode::write_sint(&mut buf, 300).unwrap(); assert_eq!([0xcd, 0x1, 0x2c], buf[..]); ``` -------------------------------- ### Low-Level Primitive Decoding in Rust Source: https://context7.com/3hren/msgpack-rust/llms.txt Demonstrates the use of the `rmp::decode` module for reading primitive MessagePack values. It showcases type-safe decoding and flexible integer conversion for various MessagePack types, including nil, booleans, integers, floats, arrays, and maps. ```rust use rmp::decode::{ read_nil, read_bool, read_int, read_f64, read_str_len, read_array_len, read_map_len, }; fn main() -> Result<(), Box> { // Decode nil let nil_buf = [0xc0]; read_nil(&mut &nil_buf[..])?; println!("Decoded nil"); // Decode boolean let bool_buf = [0xc3]; let val = read_bool(&mut &bool_buf[..])?; assert_eq!(val, true); // Decode integer with flexible type casting let int_buf = [0xcd, 0x01, 0x2c]; // uint16 = 300 // read_int automatically handles type conversion let as_u16: u16 = read_int(&mut &int_buf[..])?; let as_i32: i32 = read_int(&mut &int_buf[..])?; let as_u64: u64 = read_int(&mut &int_buf[..])?; assert_eq!(as_u16, 300); assert_eq!(as_i32, 300); assert_eq!(as_u64, 300); println!("Integer: {}", as_u16); // Decode float let f64_buf = [0xcb, 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18]; let pi = read_f64(&mut &f64_buf[..])?; println!("Float: {}", pi); // Decode array length, then read elements let arr_buf = [0x93, 0x01, 0x02, 0x03]; // fixarray(3), 1, 2, 3 let mut cursor = &arr_buf[..]; let len = read_array_len(&mut cursor)?; println!("Array length: {}", len); for _ in 0..len { let elem: i32 = read_int(&mut cursor)?; println!(" Element: {}", elem); } // Decode map let map_buf = [0x81, 0xa3, 0x6b, 0x65, 0x79, 0x2a]; // {"key": 42} let mut cursor = &map_buf[..]; let map_len = read_map_len(&mut cursor)?; println!("Map with {} entries", map_len); Ok(()) } ``` -------------------------------- ### Encode Integer with Different Representations in Rust using rmp Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md Illustrates how a single integer value (42) can be encoded using various MessagePack representations (pfix, u8, u16, u32, u64) in Rust. This showcases the flexibility of the `rmp::encode` functions. ```rust let mut bufs = vec![vec![]; 5]; rmp::encode::write_pfix(&mut bufs[0], 42).unwrap(); rmp::encode::write_u8(&mut bufs[1], 42).unwrap(); rmp::encode::write_u16(&mut bufs[2], 42).unwrap(); rmp::encode::write_u32(&mut bufs[3], 42).unwrap(); rmp::encode::write_u64(&mut bufs[4], 42).unwrap(); assert_eq!([0x2a], bufs[0][..]); assert_eq!([0xcc, 0x2a], bufs[1][..]); assert_eq!([0xcd, 0x00, 0x2a], bufs[2][..]); assert_eq!([0xce, 0x00, 0x00, 0x00, 0x2a], bufs[3][..]); assert_eq!([0xcf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a], bufs[4][..]); ``` -------------------------------- ### Rust: Encode and Decode MessagePack Extension Types Source: https://context7.com/3hren/msgpack-rust/llms.txt Demonstrates low-level and Serde-based encoding/decoding of custom MessagePack extension types. Requires the `rmp`, `rmp-serde`, and `serde` crates. Handles custom type tags and byte payloads, suitable for application-specific data like timestamps. ```rust use rmp::encode::{write_ext_meta, RmpWrite}; use rmp::decode::{read_ext_meta, RmpRead}; use serde::{Serialize, Deserialize}; // Custom extension type for timestamps (type tag = 1) const TIMESTAMP_EXT_TYPE: i8 = 1; fn encode_timestamp(buf: &mut Vec, seconds: i64) -> Result<(), Box> { let data = seconds.to_be_bytes(); write_ext_meta(buf, data.len() as u32, TIMESTAMP_EXT_TYPE)?; buf.write_bytes(&data)?; Ok(()) } fn decode_timestamp(buf: &[u8]) -> Result> { let mut cursor = &buf[..]; let meta = read_ext_meta(&mut cursor)?; if meta.typeid != TIMESTAMP_EXT_TYPE { return Err("Invalid extension type".into()); } let mut bytes = [0u8; 8]; cursor.read_exact_buf(&mut bytes)?; Ok(i64::from_be_bytes(bytes)) } // Using serde for extension types #[derive(Debug, PartialEq, Serialize, Deserialize)] #[serde(rename = "_ExtStruct")] struct ExtTimestamp((i8, serde_bytes::ByteBuf)); fn main() -> Result<(), Box> { // Low-level extension encoding let mut buf = Vec::new(); let timestamp = 1700000000i64; // Unix timestamp encode_timestamp(&mut buf, timestamp)?; println!("Encoded extension: {:x?}", buf); // Decode extension let decoded = decode_timestamp(&buf)?; assert_eq!(timestamp, decoded); println!("Decoded timestamp: {}", decoded); // Serde-based extension handling let ext = ExtTimestamp((TIMESTAMP_EXT_TYPE, serde_bytes::ByteBuf::from(timestamp.to_be_bytes().to_vec()))); let bytes = rmp_serde::to_vec(&ext)?; println!("Serde extension: {:x?}", bytes); Ok(()) } ``` -------------------------------- ### Streaming I/O Serialization and Deserialization (Rust) Source: https://context7.com/3hren/msgpack-rust/llms.txt Provides streaming serialization and deserialization capabilities for MessagePack data using `rmp_serde::Serializer` and `rmp_serde::Deserializer`. These types can be used with any `std::io::Write` or `std::io::Read` compatible streams, such as files or network sockets. This is ideal for handling large datasets or network communication. ```rust use serde::{Serialize, Deserialize}; use rmp_serde::{Serializer, Deserializer}; use std::io::Cursor; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct Message { id: u64, payload: Vec, } fn main() -> Result<(), Box> { let msg = Message { id: 12345, payload: vec![1, 2, 3, 4, 5], }; // Serialize to a writer (could be File, TcpStream, etc.) let mut buffer = Vec::new(); msg.serialize(&mut Serializer::new(&mut buffer))?; println!("Serialized {} bytes", buffer.len()); // Deserialize from a reader let cursor = Cursor::new(&buffer); let mut deserializer = Deserializer::new(cursor); let decoded: Message = Deserialize::deserialize(&mut deserializer)?; assert_eq!(msg, decoded); println!("Decoded: {:?}", decoded); Ok(()) } ``` -------------------------------- ### Custom Struct Serialization and Deserialization with MessagePack and Serde in Rust Source: https://github.com/3hren/msgpack-rust/blob/master/rmp-serde/README.md Shows how to serialize and deserialize a custom Rust struct (`Human`) to MessagePack using Serde's `Serialize` and `Deserialize` traits, along with `rmp_serde::Serializer`. Requires deriving `Serialize` and `Deserialize` on the struct. ```rust use std::collections::HashMap; use serde::{Deserialize, Serialize}; use rmp_serde::{Deserializer, Serializer}; #[derive(Debug, PartialEq, Deserialize, Serialize)] struct Human { age: u32, name: String, } fn main() { let mut buf = Vec::new(); let val = Human { age: 42, name: "John".into(), }; val.serialize(&mut Serializer::new(&mut buf)).unwrap(); } ``` -------------------------------- ### Dynamic Value Type for Schema-less Data in Rust Source: https://context7.com/3hren/msgpack-rust/llms.txt Demonstrates the `rmpv::Value` enum for representing arbitrary MessagePack data without a predefined schema. It shows how to create `Value` instances programmatically, perform type checking, access elements by index or key, and deserialize unknown MessagePack data. ```rust use rmpv::{Value, decode::read_value}; use std::io::Cursor; fn main() -> Result<(), Box> { // Create values programmatically let value = Value::Array(vec![ Value::Nil, Value::Boolean(true), Value::from(42), Value::from("hello"), Value::Binary(vec![1, 2, 3]), Value::Map(vec![ (Value::from("key"), Value::from(100)), ]), ]); // Type checking assert!(value.is_array()); println!("Is array: {}", value.is_array()); // Access array elements by index println!("Element 0 is nil: {}", value[0].is_nil()); println!("Element 1: {}", value[1].as_bool().unwrap()); println!("Element 2: {}", value[2].as_i64().unwrap()); println!("Element 3: {}", value[3].as_str().unwrap()); // Access map by string key if let Value::Map(_) = &value[5] { let map_value = &value[5]; println!("Map key value: {}", map_value["key"].as_i64().unwrap()); } // Parse unknown MessagePack data let unknown_data = [0x93, 0xc0, 0xc3, 0xa5, 0x68, 0x65, 0x6c, 0x6c, 0x6f]; let mut cursor = Cursor::new(&unknown_data); let parsed: Value = read_value(&mut cursor)?; println!("Parsed: {}", parsed); // [nil, true, "hello"] // Convert to owned/borrowed reference let value_ref = value.as_ref(); println!("As reference type: {:?}", value_ref); Ok(()) } ``` -------------------------------- ### Encode and Decode Floating-Point Number in Rust using rmp Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md Demonstrates a round-trip operation for a floating-point number (π) using the `rmp` crate in Rust. It shows encoding the value to MessagePack using `rmp::encode::write_f64` and then decoding it back using `rmp::decode::read_f64`, verifying the result. ```rust let pi = std::f64::consts::PI; let mut buf = Vec::new(); rmp::encode::write_f64(&mut buf, pi).unwrap(); assert_eq!([0xcb, 0x40, 0x9, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18], buf[..]); assert_eq!(pi, rmp::decode::read_f64(&mut &buf[..]).unwrap()); ``` -------------------------------- ### Add rmp dependency to Cargo.toml Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md To use the rmp crate in your Rust project, add the following dependency to your `Cargo.toml` file. This ensures that the `rmp` library version 0.8 is available for use. ```toml [dependencies.rmp] rmp = "0.8" ``` -------------------------------- ### High-Level Serde Serialization to Vec (Rust) Source: https://context7.com/3hren/msgpack-rust/llms.txt Serializes any Serde-compatible Rust type into a MessagePack byte vector using `rmp_serde::to_vec`. Structs are serialized as compact arrays by default, omitting field names for maximum efficiency. This function is suitable for general-purpose serialization where compactness is prioritized. ```rust use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize, PartialEq)] struct Person { name: String, age: u32, active: bool, } fn main() -> Result<(), Box> { let person = Person { name: "Alice".to_string(), age: 30, active: true, }; // Serialize to MessagePack bytes (compact array format) let bytes = rmp_serde::to_vec(&person)?; // Output: [0x93, 0xa5, 0x41, 0x6c, 0x69, 0x63, 0x65, 0x1e, 0xc3] // Breakdown: fixarray(3), fixstr(5)"Alice", fixint(30), true println!("Serialized {} bytes: {:x?}", bytes.len(), bytes); Ok(()) } ``` -------------------------------- ### Encode and Decode Boolean in Rust using rmp Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md Demonstrates how to encode a boolean value to MessagePack format using `rmp::encode::write_bool` and verify the resulting byte array. It also shows how to decode a boolean from a byte array. ```rust let mut buf = Vec::new(); rmp::encode::write_bool(&mut buf, true).unwrap(); assert_eq!([0xc3], buf[..]); // Example of decoding (though not explicitly shown in the original text, it's implied by the library's purpose) // let mut reader = &buf[..]; // assert_eq!(true, rmp::decode::read_bool(&mut reader).unwrap()); ``` -------------------------------- ### Named Struct Serialization to Vec (Rust) Source: https://context7.com/3hren/msgpack-rust/llms.txt Serializes structs into MessagePack maps with field names included using `rmp_serde::to_vec_named`. This format is larger than the compact array format but is more human-readable when decoded and useful for interoperability. It contrasts with `to_vec` which omits field names. ```rust use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] struct Config { host: String, port: u16, debug: bool, } fn main() -> Result<(), Box> { let config = Config { host: "localhost".to_string(), port: 8080, debug: false, }; // Serialize with field names preserved let bytes = rmp_serde::to_vec_named(&config)?; // Results in: {"host": "localhost", "port": 8080, "debug": false} // Larger than compact format but human-readable when decoded println!("Named serialization: {} bytes", bytes.len()); // Compare with compact format let compact = rmp_serde::to_vec(&config)?; println!("Compact serialization: {} bytes", compact.len()); Ok(()) } ``` -------------------------------- ### Decode Integer with Flexible Type in Rust using rmp Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md Illustrates the use of `rmp::decode::read_int` in Rust, which allows decoding an integer from MessagePack bytes into various integer types (signed and unsigned) without explicit type specification. This function is useful for interoperability with other MessagePack libraries. ```rust let buf = [0xcd, 0x1, 0x2c]; assert_eq!(300i16, rmp::decode::read_int(&mut &buf[..]).unwrap()); assert_eq!(300i32, rmp::decode::read_int(&mut &buf[..]).unwrap()); assert_eq!(300i64, rmp::decode::read_int(&mut &buf[..]).unwrap()); assert_eq!(300u16, rmp::decode::read_int(&mut &buf[..]).unwrap()); assert_eq!(300u32, rmp::decode::read_int(&mut &buf[..]).unwrap()); assert_eq!(300u64, rmp::decode::read_int(&mut &buf[..]).unwrap()); ``` -------------------------------- ### Decode Specific Integer Type in Rust using rmp Source: https://github.com/3hren/msgpack-rust/blob/master/rmp/README.md Demonstrates decoding a MessagePack byte array into a specific unsigned integer type (`u16`) using `rmp::decode::read_u16` in Rust. It also shows that attempting to decode into an incompatible type (`u32`) results in a type mismatch error. ```rust let buf = [0xcd, 0x1, 0x2c]; assert_eq!(300, rmp::decode::read_u16(&mut &buf[..]).unwrap()); // Attempting to decode into an incompatible type rmp::decode::read_u32(&mut &buf[..]).err().unwrap(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.