### Custom Native Struct Derives with BinaryMirror in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt This example illustrates how to customize the derive traits (like `Debug`, `Clone`, `PartialEq`, `Eq`) for the generated native structs when using the `BinaryMirror` derive macro. It also shows how to retrieve the source code of the generated native struct. ```rust use binary_mirror_derive::BinaryMirror; // Specify custom derives for native struct #[repr(C)] #[derive(BinaryMirror)] #[bm(derive(Debug, Clone, PartialEq, Eq))] struct CustomStruct { #[bm(type = "str")] name: [u8; 10], #[bm(type = "i32")] value: [u8; 4], } // Native struct has custom derives let native = CustomStructNative::default() .with_name("Test") .with_value(123); let cloned = native.clone(); assert_eq!(native, cloned); // Get generated native struct code let code = CustomStruct::native_struct_code(); println!("{}", code); // Output: // pub struct CustomStructNative { // pub name: Option, // pub value: Option, // } ``` -------------------------------- ### Rust: Support Raw Bytes Type with BinaryMirror for Unprocessed Data Source: https://context7.com/yvictor/binary_mirror/llms.txt Demonstrates how to use the `bytes` type in `binary_mirror` to handle raw, unprocessed byte arrays within structs. This is useful when direct byte manipulation or storage is required without immediate parsing. The example includes converting to JSON, showing bytes as arrays. Dependencies: `binary_mirror`, `binary_mirror_derive`, `serde_json`. ```rust use binary_mirror::FromNative; use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Packet { #[bm(type = "str")] header: [u8; 4], #[bm(type = "bytes")] payload: [u8; 10], #[bm(type = "bytes", default_byte = b'\0')] checksum: [u8; 4], } // Create with raw bytes // Note: PacketNative is a placeholder for the actual native struct. // let native = PacketNative::default() // .with_header("DATA") // .with_payload([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A]) // .with_checksum([0xAB, 0xCD, 0xEF, 0x12]); // let binary = Packet::from_native(&native); // Access raw bytes directly // assert_eq!(binary.payload(), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A]); // assert_eq!(binary.checksum(), [0xAB, 0xCD, 0xEF, 0x12]); // Serialize to JSON (bytes as arrays) // let json = serde_json::to_string(&binary.to_native()).unwrap(); // println!("{}", json); // {"header":"DATA","payload":[1,2,3,4,5,6,7,8,9,10],"checksum":[171,205,239,18]} ``` -------------------------------- ### Rust: Serde support for binary data with BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/README.md Illustrates how to leverage Serde integration provided by the `binary-mirror` crate for converting binary data structures to and from a native format. This enables JSON serialization and deserialization of the parsed data. ```Rust use serde::{Deserialize, Serialize}; // Assuming Trade and TradeNative structs are defined elsewhere let trade = Trade { name: b"AAPL ", value: b"123 ", qty: b"123.4", }; let trade_native = trade.to_native(); let json = serde_json::to_string(&trade_native).unwrap(); println!("{}", json); let parsed = serde_json::from_str::(&json).unwrap(); println!("{:?}", parsed); let trade_from_native = Trade::from_native(&parsed); println!("{}", trade_from_native); ``` -------------------------------- ### Date and Time Parsing with BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/binary-mirror-derive/README.md Shows how to parse date and time information from fixed-length byte fields using `BinaryMirror`. It supports specifying date and time formats using `format` attribute and combining them into a `datetime` field using `datetime_with`. Requires `chrono` types like `NaiveDate`, `NaiveTime`, and `NaiveDateTime` for the output. ```rust use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; #[repr(C)] #[derive(BinaryMirror)] struct MarketData { #[bm(type = "date", format = "%Y%m%d")] date: [u8; 8], #[bm(type = "time", format = "%H%M%S")] time: [u8; 6], // Combine date and time into a datetime #[bm(type = "date", format = "%Y%m%d", datetime_with = "time", alias = "datetime")] trade_date: [u8; 8], } let data = MarketData { date: b"20240101", time: b"123456", trade_date: b"20240101", }; assert_eq!(data.trade_date(), Some(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())); assert_eq!(data.time(), Some(NaiveTime::from_hms_opt(12, 34, 56).unwrap())); assert_eq!( data.datetime(), Some(NaiveDateTime::new( NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(), NaiveTime::from_hms_opt(12, 34, 56).unwrap() )) ); ``` -------------------------------- ### Rust: Format Numbers for Binary Conversion with BinaryMirror Source: https://context7.com/yvictor/binary_mirror/llms.txt Demonstrates how to control numeric output formats when converting native Rust structs to binary representations using the `binary_mirror` crate. It shows zero-padding for integers, fixed decimal places for floats, and custom formatting for Decimal types. Dependencies include `binary_mirror`, `binary_mirror_derive`, and `rust_decimal`. ```rust use binary_mirror::FromNative; use binary_mirror_derive::BinaryMirror; use rust_decimal::Decimal; use std::str::FromStr; #[repr(C)] #[derive(BinaryMirror)] struct FormattedData { // Zero-padded integer #[bm(type = "i32", format = "{:04}")] order_id: [u8; 4], // Fixed decimal places #[bm(type = "f32", format = "{:09.3}")] price: [u8; 9], // Decimal with custom format #[bm(type = "decimal", format = "{:010.3}")] amount: [u8; 10], } // Create native struct and convert to binary with formatting // Note: FormattedDataNative is a placeholder for the actual native struct // that would be generated or defined elsewhere for conversion. // let native = FormattedDataNative::default() // .with_order_id(42) // .with_price(123.456) // .with_amount(Decimal::from_str("123.456").unwrap()); // let binary = FormattedData::from_native(&native); // Verify formatted bytes // assert_eq!(&binary.order_id, b"0042"); // assert_eq!(&binary.price, b"00123.456"); // assert_eq!(&binary.amount, b"000123.456"); // Parse back // assert_eq!(binary.order_id(), Some(42)); // assert_eq!(binary.price(), Some(123.456)); // assert_eq!(binary.amount(), Some(Decimal::from_str("123.456").unwrap())); ``` -------------------------------- ### Rust: Date and Time handling with BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/README.md Demonstrates how `BinaryMirror` handles date and time parsing from fixed-length byte arrays. It shows parsing separate date and time fields, and combining them into a single datetime field using specified formats. ```Rust use binary_mirror_derive::BinaryMirror; use chrono::{NaiveDate, NaiveDateTime, NaiveTime}; #[repr(C)] #[derive(BinaryMirror)] struct MarketData { #[bm(type = "date", format = "%Y%m%d")] date: [u8; 8], #[bm(type = "time", format = "%H%M%S")] time: [u8; 6], #[bm(type = "date", format = "%Y%m%d", datetime_with = "time", alias = "datetime")] trade_date: [u8; 8], } let data = MarketData { date: b"20240101", time: b"123456", trade_date: b"20240101", }; assert_eq!(data.trade_date(), Some(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())); assert_eq!(data.time(), Some(NaiveTime::from_hms_opt(12, 34, 56).unwrap())); assert_eq!( data.datetime(), Some(NaiveDateTime::new( NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(), NaiveTime::from_hms_opt(12, 34, 56).unwrap() )) ); ``` -------------------------------- ### Native Struct Conversion and Serde with Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt Demonstrates converting parsed binary structs to native Rust types and integrating with Serde for JSON serialization and deserialization. This enables bidirectional data flow between binary, native, and JSON formats. It relies on `binary-mirror`, `binary-mirror-derive`, and `serde` crates. ```rust use binary_mirror::{FromBytes, ToNative, FromNative}; use binary_mirror_derive::BinaryMirror; use serde::{Serialize, Deserialize}; #[repr(C)] #[derive(BinaryMirror)] struct Order { #[bm(type = "str")] symbol: [u8; 8], #[bm(type = "i32")] quantity: [u8; 4], #[bm(type = "decimal")] price: [u8; 10], } // Parse binary data let order = Order::from_bytes(b"AAPL 1000123.45 ").unwrap(); // Convert to native struct with Option fields let native = order.to_native(); let json = serde_json::to_string(&native).unwrap(); println!("{}", json); // {"symbol":"AAPL","quantity":1000,"price":"123.45"} // Deserialize JSON and convert back to binary let parsed: OrderNative = serde_json::from_str(&json).unwrap(); let binary_order = Order::from_native(&parsed); assert_eq!(binary_order.symbol(), Some("AAPL".to_string())); assert_eq!(binary_order.quantity(), Some(1000)); ``` -------------------------------- ### Rust: Parse binary data directly from bytes with BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/README.md Shows how to use the `from_bytes` static method provided by `BinaryMirror` to parse raw byte slices directly into a struct. It includes error handling for size mismatches and demonstrates successful parsing with validation. ```Rust use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Data { #[bm(type = "str")] name: [u8; 10], #[bm(type = "i32")] value: [u8; 4], } let bytes = b"Hello 123 "; let data = Data::from_bytes(bytes).expect("Invalid data"); assert_eq!(data.name(), "Hello"); assert_eq!(data.value(), Some(123)); let wrong_size = b"too short"; let err = Data::from_bytes(wrong_size).unwrap_err(); println!("{}", err); // Will show size mismatch and content ``` -------------------------------- ### Basic Structure Parsing with BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/binary-mirror-derive/README.md Demonstrates how to use the `BinaryMirror` derive macro to parse fixed-length binary data into a Rust struct. It maps byte arrays to specific data types like strings, integers, and floats, providing methods to access the parsed values. Ensure the struct is marked with `#[repr(C)]` for correct memory layout. ```rust use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Trade { #[bm(type = "str")] name: [u8; 10], #[bm(type = "i32")] value: [u8; 4], #[bm(type = "f32")] qty: [u8; 5], } let trade = Trade { name: b"AAPL ", value: b"123 ", qty: b"123.4", }; assert_eq!(trade.name(), "AAPL"); assert_eq!(trade.value(), Some(123)); assert_eq!(trade.qty(), Some(123.4)); ``` -------------------------------- ### Build Native Structs with Builder Pattern in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt Illustrates using a fluent builder API to create native Rust structs which can then be converted into binary format. This pattern is useful for constructing complex data structures programmatically. It requires `binary-mirror`, `binary-mirror-derive`, and `rust_decimal` crates. ```rust use binary_mirror::{FromNative, ToBytes}; use binary_mirror_derive::BinaryMirror; use rust_decimal::Decimal; use std::str::FromStr; #[repr(C)] #[derive(BinaryMirror)] struct Quote { #[bm(type = "str")] exchange: [u8; 10], #[bm(type = "decimal")] bid: [u8; 12], #[bm(type = "decimal")] ask: [u8; 12], } // Build native struct with builder pattern let native = QuoteNative::default() .with_exchange("NYSE") .with_bid(Decimal::from_str("100.50").unwrap()) .with_ask(Decimal::from_str("100.55").unwrap()); // Convert to raw binary format let binary = Quote::from_native(&native); assert_eq!(binary.exchange(), Some("NYSE".to_string())); assert_eq!(binary.bid(), Some(Decimal::from_str("100.50").unwrap())); // Export as bytes let bytes = binary.to_bytes(); // &[u8] let owned = binary.to_bytes_owned(); // Vec ``` -------------------------------- ### Field Aliases and Skip Option in BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/binary-mirror-derive/README.md Demonstrates the use of `alias` to provide a different name for a field when accessing its value, and `skip = true` to exclude a field from display output. This allows for more flexible data representation and prevents sensitive or internal fields from being shown by default. ```rust use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Quote { #[bm(type = "str", alias = "exchange")] exh: [u8; 4], #[bm(type = "str", skip = true)] // Skip in Display output internal_code: [u8; 10], } let quote = Quote { exh: b"NYSE", internal_code: b"SECRET ", }; assert_eq!(quote.exchange(), "NYSE"); ``` -------------------------------- ### Debug and Display Implementations for Binary Data in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt This snippet demonstrates how to use the `BinaryMirror` derive macro to automatically generate `Debug` and `Display` implementations for structs representing binary data. It shows how parsed values are displayed and how raw byte/hex data can be accessed for debugging, including error handling for invalid data. ```rust use binary_mirror::FromBytes; use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Data { #[bm(type = "str")] name: [u8; 10], #[bm(type = "i32")] value: [u8; 4], #[bm(type = "f32")] price: [u8; 6], } // Valid data let data = Data::from_bytes(b"Product 1234123.45").unwrap(); // Display shows parsed values println!("{}", data); // Output: Data { name: Product, value: 1234, price: 123.45 } // Debug shows raw hex and bytes println!("{:?}", data); // Output: Data { name: hex: [0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x20, 0x20, 0x20], bytes: "Product ", ... } // Invalid data shows errors in Display let invalid = Data::from_bytes(b"Product abcd123.xx").unwrap(); println!("{}", invalid); // Output: Data { name: Product, value: Error, price: Error } ``` -------------------------------- ### CompactString Support for Memory-Efficient Strings in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt This snippet demonstrates the use of `compact_str::CompactString` with `binary-mirror` for memory-efficient string storage. It shows how to define a struct with fields typed as `compact_str` and how to convert between native structures containing `CompactString` and the binary representation. ```rust use binary_mirror::FromNative; use binary_mirror_derive::BinaryMirror; use compact_str::CompactString; #[repr(C)] #[derive(BinaryMirror)] struct OptimizedData { #[bm(type = "compact_str")] symbol: [u8; 8], #[bm(type = "compact_str")] exchange: [u8; 4], #[bm(type = "i32")] volume: [u8; 8], } // CompactString uses inline storage for strings up to 24 bytes (on 64-bit systems) let native = OptimizedDataNative::default() .with_symbol("AAPL") .with_exchange("NYSE") .with_volume(1000000); let binary = OptimizedData::from_native(&native); assert_eq!(binary.symbol(), Some(CompactString::from("AAPL"))); assert_eq!(binary.exchange(), Some(CompactString::from("NYSE"))); ``` -------------------------------- ### Parsing Binary Data from Bytes with BinaryMirror Source: https://github.com/yvictor/binary_mirror/blob/main/binary-mirror-derive/README.md Explains how to use the `from_bytes` static method provided by the `BinaryMirror` derive macro to parse a byte slice directly into a struct instance. This method is marked as unsafe and requires the struct to be `#[repr(C)]`, the byte slice to match the struct's size exactly, and the bytes to represent a valid struct instance. ```rust use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Data { #[bm(type = "str")] name: [u8; 10], #[bm(type = "i32")] value: [u8; 4], } let bytes = b"Hello 123 "; let data = Data::from_bytes(bytes).expect("Invalid data"); assert_eq!(data.name(), "Hello"); assert_eq!(data.value(), Some(123)); // Size mismatch error handling let wrong_size = b"too short"; let err = Data::from_bytes(wrong_size).unwrap_err(); println!("{}", err); // Will show size mismatch and content ``` -------------------------------- ### Rust: Access Field Metadata with BinaryMirror for Manual Parsing Source: https://context7.com/yvictor/binary_mirror/llms.txt Shows how to retrieve field metadata, such as offset, limit, and size, from structs defined with `binary_mirror`. This metadata can be used for manual byte slice manipulation, validation, or custom parsing logic. It requires `binary_mirror` and `binary_mirror_derive`. ```rust use binary_mirror::FromBytes; use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Message { #[bm(type = "str")] header: [u8; 4], #[bm(type = "i32")] msg_type: [u8; 4], #[bm(type = "str")] body: [u8; 20], } // Get field specifications // let header_spec = Message::header_spec(); // assert_eq!(header_spec.offset, 0); // assert_eq!(header_spec.limit, 4); // assert_eq!(header_spec.size, 4); // let msg_type_spec = Message::msg_type_spec(); // assert_eq!(msg_type_spec.offset, 4); // assert_eq!(msg_type_spec.limit, 8); // assert_eq!(msg_type_spec.size, 4); // Use specs for manual byte slice access // let bytes = b"HEAD0001Message body here "; // let header_bytes = &bytes[header_spec.offset..header_spec.limit]; // assert_eq!(header_bytes, b"HEAD"); // Verify field boundaries // assert_eq!(Message::header_spec().limit, Message::msg_type_spec().offset); // Get total size // assert_eq!(Message::SIZE, 28); // assert_eq!(Message::size(), 28); ``` -------------------------------- ### Date, Time, and DateTime Handling in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt Parse and format temporal data using custom formats. Supports standalone datetime fields, separate date and time fields, and combined datetime from two fields. Utilizes the chrono crate for temporal data types. ```rust use binary_mirror::FromNative; use binary_mirror_derive::BinaryMirror; use chrono::{NaiveDate, NaiveTime, NaiveDateTime}; #[repr(C)] #[derive(BinaryMirror)] struct MarketData { // Standalone datetime field #[bm(type = "datetime", format = "%Y%m%d%H%M%S")] timestamp: [u8; 14], // Separate date and time fields #[bm(type = "date", format = "%Y%m%d")] trade_date: [u8; 8], #[bm(type = "time", format = "%H%M%S")] trade_time: [u8; 6], // Combined datetime from two fields #[bm(type = "date", format = "%Y%m%d", datetime_with = "time", alias = "datetime", skip = true)] date: [u8; 8], #[bm(type = "time", format = "%H%M%S", skip = true)] time: [u8; 6], } // Parse temporal data let data = MarketData { timestamp: *b"20240101123456", trade_date: *b"20240101", trade_time: *b"123456", date: *b"20240101", time: *b"123456", }; assert_eq!(data.timestamp(), Some(NaiveDateTime::parse_from_str("20240101123456", "%Y%m%d%H%M%S").ok().unwrap())); assert_eq!(data.trade_date(), Some(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())); assert_eq!(data.trade_time(), Some(NaiveTime::from_hms_opt(12, 34, 56).unwrap())); assert_eq!(data.datetime(), Some(NaiveDateTime::new( NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(), NaiveTime::from_hms_opt(12, 34, 56).unwrap() ))); // Create from native with builder let native = MarketDataNative::default() .with_timestamp(NaiveDateTime::parse_from_str("20240101123456", "%Y%m%d%H%M%S").ok().unwrap()); let binary = MarketData::from_native(&native); ``` -------------------------------- ### Field Aliases, Skip, and Advanced Attributes in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt Control field visibility and naming using aliases, skip directives, and default values. Supports renaming fields, skipping fields in display output or native structs, setting custom padding bytes, and suppressing parse failure warnings. ```rust use binary_mirror::FromNative; use binary_mirror_derive::BinaryMirror; #[repr(C)] #[derive(BinaryMirror)] struct Record { // Rename field in native struct #[bm(type = "str", alias = "exchange")] exh: [u8; 4], // Skip in Display output but include in native struct #[bm(type = "str", skip = true)] internal_code: [u8; 10], // Skip in native struct but accessible in raw struct #[bm(type = "i32", skip_native = true)] raw_value: [u8; 4], // Custom default padding byte #[bm(type = "str", default_byte = b'0')] padded: [u8; 5], // Suppress warnings for expected parse failures #[bm(type = "i32", ignore_warn = true)] optional: [u8; 4], } let record = Record { exh: *b"NYSE", internal_code: *b"SECRET123 ", raw_value: *b"9999", padded: *b"12 ", optional: *b" ", }; // Access via alias assert_eq!(record.exchange(), Some("NYSE".to_string())); // raw_value accessible in raw struct but not in native assert_eq!(record.raw_value(), Some(9999)); // Convert to native - raw_value field will not exist let native = record.to_native(); // native.raw_value does not exist // Create from native with custom padding let native2 = RecordNative::default().with_padded("ab"); let binary = Record::from_native(&native2); assert_eq!(binary.padded(), Some("ab000".to_string())); // Padded with '0' bytes ``` -------------------------------- ### Rust: Define custom enums for binary data with BinaryEnum Source: https://github.com/yvictor/binary_mirror/blob/main/README.md Shows how to define custom enums that can be used within binary data structures using the `BinaryMirror` and `BinaryEnum` derive macros. It demonstrates mapping byte values to enum variants and vice versa. ```Rust use binary_mirror_derive::{BinaryMirror, BinaryEnum}; #[derive(Debug, PartialEq, BinaryEnum)] enum OrderSide { #[bv(value = b"B")] Buy, #[bv(value = b"S")] Sell, } #[derive(Debug, PartialEq, BinaryEnum)] enum Direction { Up, // Will use b'U' Down, // Will use b'D' } #[repr(C)] #[derive(BinaryMirror)] struct Order { #[bm(type = "enum", enum_type = "OrderSide")] side: [u8; 1], } let order = Order { side: b"B" }; assert_eq!(order.side(), Some(OrderSide::Buy)); ``` -------------------------------- ### Custom Enum Parsing with BinaryEnum Source: https://github.com/yvictor/binary_mirror/blob/main/binary-mirror-derive/README.md Illustrates the use of `BinaryEnum` and `BinaryMirror` to parse single-byte representations into Rust enums. The `#[bv(value = ...)]` attribute specifies the byte value for each enum variant. It also shows a default behavior where the first character of the variant name is used if no explicit value is provided. ```rust use binary_mirror_derive::{BinaryMirror, BinaryEnum}; #[derive(Debug, PartialEq, BinaryEnum)] enum OrderSide { #[bv(value = b"B")] Buy, #[bv(value = b"S")] Sell, } // Default first character behavior #[derive(Debug, PartialEq, BinaryEnum)] enum Direction { Up, // Will use b'U' Down, // Will use b'D' } #[repr(C)] #[derive(BinaryMirror)] struct Order { #[bm(type = "enum", enum_type = "OrderSide")] side: [u8; 1], } let order = Order { side: b"B" }; assert_eq!(order.side(), Some(OrderSide::Buy)); ``` -------------------------------- ### Parse Binary Structs with Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt Parses fixed-length binary data into Rust structs, providing type-safe accessor methods for each field. It requires the `binary-mirror-derive` and `binary-mirror` crates. The input is a byte slice, and the output is a struct instance or an error if parsing fails due to size mismatches. ```rust use binary_mirror_derive::BinaryMirror; use binary_mirror::FromBytes; #[repr(C)] #[derive(BinaryMirror)] struct Trade { #[bm(type = "str")] name: [u8; 10], #[bm(type = "i32")] value: [u8; 4], #[bm(type = "f32")] qty: [u8; 5], } // Parse from bytes let bytes = b"AAPL 123 123.4"; let trade = Trade::from_bytes(bytes).expect("Invalid data"); // Access parsed values assert_eq!(trade.name(), Some("AAPL".to_string())); assert_eq!(trade.value(), Some(123)); assert_eq!(trade.qty(), Some(123.4)); // Size validation with detailed error reporting let wrong_size = b"too short"; let err = Trade::from_bytes(wrong_size).unwrap_err(); println!("{}", err); // "bytes size mismatch: expected 19 bytes but got 9 bytes, content: "too short"" ``` -------------------------------- ### Rust: Specify Default Values for Native Struct Fields with BinaryMirror Source: https://context7.com/yvictor/binary_mirror/llms.txt Illustrates how to define default value functions for fields within native Rust structs intended for binary serialization using `binary_mirror`. This is useful for fields that should have a predefined value if not explicitly set. It requires `binary_mirror` and `binary_mirror_derive`. ```rust use binary_mirror::FromNative; use binary_mirror_derive::BinaryMirror; use chrono::{NaiveDateTime, NaiveDate}; // Define default value functions fn default_str() -> String { "UNKNOWN".to_string() } fn now() -> NaiveDateTime { chrono::Local::now().naive_utc() } fn today() -> NaiveDate { chrono::Local::now().date_naive() } #[repr(C)] #[derive(BinaryMirror)] struct Event { #[bm(type = "str", default_func = "default_str")] name: [u8; 10], #[bm(type = "datetime", format = "%Y%m%d%H%M%S", default_func = "now")] timestamp: [u8; 14], #[bm(type = "date", format = "%Y%m%d", default_func = "today")] date: [u8; 8], } // Create native struct with defaults // Note: EventNative is a placeholder for the actual native struct. // let native = EventNative::default(); // Default values are applied // let binary = Event::from_native(&native); // assert_eq!(binary.name(), Some("UNKNOWN".to_string())); // assert_eq!(binary.timestamp(), Some(now())); // assert_eq!(binary.date(), Some(today())); // Override defaults with builder pattern // let custom_native = EventNative::default() // .with_name("CUSTOM") // .with_date(NaiveDate::from_ymd_opt(2024, 12, 25).unwrap()); ``` -------------------------------- ### Custom Binary Enums in Rust Source: https://context7.com/yvictor/binary_mirror/llms.txt Define enums that map to specific byte sequences. Supports custom byte values, default first-character behavior, and multi-byte enum values. These enums can be integrated into structs for binary data representation and offer methods for byte conversion. ```rust use binary_mirror_derive::{BinaryMirror, BinaryEnum}; use serde::{Serialize, Deserialize}; // Enum with custom byte values #[derive(Debug, PartialEq, BinaryEnum, Serialize, Deserialize)] enum OrderSide { #[bv(value = b"B")] Buy, #[bv(value = b"S")] Sell, } // Enum with default first-character behavior #[derive(Debug, PartialEq, BinaryEnum, Serialize, Deserialize)] enum Direction { Up, // Automatically uses b'U' Down, // Automatically uses b'D' } // Multi-byte enum values #[derive(Debug, PartialEq, BinaryEnum, Serialize, Deserialize)] enum OrderType { #[bv(value = b"MKT")] Market, #[bv(value = b"LMT")] Limit, } // Use in structs #[repr(C)] #[derive(BinaryMirror)] struct Order { #[bm(type = "enum", enum_type = "OrderSide")] side: [u8; 1], #[bm(type = "enum", enum_type = "OrderType")] order_type: [u8; 3], } let order = Order { side: *b"B", order_type: *b"MKT", }; assert_eq!(order.side(), Some(OrderSide::Buy)); assert_eq!(order.order_type(), Some(OrderType::Market)); // Enum conversion methods assert_eq!(OrderSide::Buy.as_bytes(), b"B"); assert_eq!(OrderSide::from_bytes(b"S"), Some(OrderSide::Sell)); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.