### Run Axum Server Example Source: https://github.com/udoprog/musli/blob/main/crates/musli-web/README.md This command navigates to the example server directory and runs the Axum-based server implementation. It requires Cargo to be installed. ```Shell cd examples/server && cargo run ``` -------------------------------- ### Run Yew Client Example Source: https://github.com/udoprog/musli/blob/main/crates/musli-web/README.md This command navigates to the example client directory and serves the Yew client application using Trunk. Trunk is a build tool for Rust Web applications. ```Shell cd examples/client && trunk serve ``` -------------------------------- ### Initialize Slice Allocator with Musli (Rust) Source: https://github.com/udoprog/musli/blob/main/README.md Initializes a Musli `Slice` allocator using an `ArrayBuffer`. This setup is necessary for using Musli in its fastest, memory-preallocating mode. ```rust use musli::alloc::{ArrayBuffer, Slice}; let mut buf = ArrayBuffer::new(); let alloc = Slice::new(&mut buf); ``` -------------------------------- ### Rust Musli Storage Partial Upgrade Stability Example Source: https://github.com/udoprog/musli/blob/main/README.md Illustrates partial upgrade stability with `musli::storage`, showing that `Version2` cannot be decoded from `Version1` (suitable for on-disk storage evolution), but `Version2` can decode `Version1`. ```rust let version2 = musli::storage::to_vec(&Version2 { name: String::from("Aristotle"), age: Some(61), })?; assert!(musli::storage::decode::<_, Version1>(version2.as_slice()).is_err()); let version1 = musli::storage::to_vec(&Version1 { name: String::from("Aristotle"), })?; let version2: Version2 = musli::storage::decode(version1.as_slice())?; ``` -------------------------------- ### Musli Enum Serialization Example Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates basic enum serialization and deserialization using Musli's derive macros. Includes a variant with a default value. ```rust use musli::{Encode, Decode}; #[derive(Debug, PartialEq, Eq, Encode, Decode)] enum Animal { Cat, Dog, #[musli(default)] Unknown, } ``` -------------------------------- ### Rust: Customizing size limit with usize Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Provides examples of how to use `usize` as the `Size` parameter to bypass the default 32-bit limit for `Ref` types, allowing for larger data. ```rust // These no longer panic: let reference = Ref::::new(1usize << 32); let slice = Ref::<[Custom], Native, usize>::with_metadata(0u32, 1usize << 32); let unsize = Ref::::with_metadata(0u32, 1usize << 32); ``` -------------------------------- ### Rust Musli Wire Full Upgrade Stability Example Source: https://github.com/udoprog/musli/blob/main/README.md Demonstrates full upgrade stability with `musli::wire` where `Version1` can decode `Version2` by skipping unknown fields. It uses `#[musli(name = ..)]` to ensure field stability across versions. ```rust use musli::{Encode, Decode}; #[derive(Debug, PartialEq, Encode, Decode)] struct Version1 { #[musli(Binary, name = 0)] name: String, } #[derive(Debug, PartialEq, Encode, Decode)] struct Version2 { #[musli(Binary, name = 0)] name: String, #[musli(Binary, name = 1)] #[musli(default)] age: Option, } let version2 = musli::wire::to_vec(&Version2 { name: String::from("Aristotle"), age: Some(61), })?; let version1: Version1 = musli::wire::decode(version2.as_slice())?; ``` -------------------------------- ### Generic Musli Serialization with Custom Module Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Illustrates how to implement generic serialization and deserialization using Musli. This example shows a custom module that can handle fields of different types, making the serialization more flexible. ```rust mod example { use musli::{Decode, Encode}; #[derive(Decode, Encode)] struct Container { #[musli(with = self::module)] field: Field, } struct Field { value: T, } mod module { use musli::{Decoder, Encoder}; use super::Field; pub fn encode(field: &Field, encoder: E) -> Result<(), E::Error> where E: Encoder, { todo!() } pub fn decode<'de, D, T>(decoder: D) -> Result, D::Error> where D: Decoder<'de>, { todo!() } } } ``` -------------------------------- ### Store String with musli-zerocopy Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Demonstrates how to store an unsized string and a reference to it using `OwnedBuf` in musli-zerocopy. The example shows how the string and its reference (offset and size) are laid out in the buffer. ```rust use musli_zerocopy::OwnedBuf; let mut buf = OwnedBuf::new(); let string = buf.store_unsized("Hello World!")?; let reference = buf.store(&string)?; assert_eq!(reference.offset(), 12); ``` -------------------------------- ### Build Portable Archive with Big-Endian Byte Order (Rust) Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Illustrates constructing a portable archive using `OwnedBuf` with a big-endian byte order. The example includes storing data and asserting the correctness of the generated buffer. ```rust use musli_zerocopy::{endian, Endian, OwnedBuf}; let mut buf = OwnedBuf::new() .with_byte_order::(); let first = buf.store(&Endian::be(42u16))?; let portable = Archive { string: buf.store_unsized("Hello World!")?, number: Endian::new(10), }; let portable = buf.store(&portable)?; assert_eq!(&buf[..], &[ 0, 42, // 42u16 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, // "Hello World!" 0, 0, // padding 0, 0, 0, 2, 0, 0, 0, 12, // Ref 0, 0, 0, 10 // 10u32 ]); let portable = buf.load(portable)?; ``` -------------------------------- ### Get Buffer Alignment and Endianness (Rust) Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Demonstrates how to retrieve the alignment and endianness of a buffer using Musli Zerocopy. This is crucial for ensuring data compatibility when sending data over a network. ```rust use musli_zerocopy::OwnedBuf; let buf = OwnedBuf::new(); /* write something */ let is_little_endian = cfg!(target_endian = "little"); let alignment = buf.requested(); ``` -------------------------------- ### Musli Default Field Value Examples (Default and Custom Path) Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates Musli's `#[musli(default)]` attribute for using `Default::default()` and `#[musli(default = )]` for specifying a custom default value via a function. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Person { name: String, #[musli(default)] age: Option, #[musli(default = default_height)] height: Option, #[musli(skip, default = default_meaning)] meaning: u32, } fn default_height() -> Option { Some(180) } fn default_meaning() -> u32 { 42 } ``` -------------------------------- ### Rust ZeroCopy Struct with Ref Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Demonstrates defining a Rust struct with zero-copy capabilities using the `ZeroCopy` derive macro. It includes a `Ref` field, showcasing how to reference string data directly from a byte buffer. The example shows reading data from a buffer and accessing the string reference. ```Rust use musli_zerocopy::{buf, Ref, ZeroCopy}; #[derive(ZeroCopy)] #[repr(C)] struct Person { age: u8, name: Ref, } let buf = buf::aligned_buf::(include_bytes!("author.bin"))?; let person = Person::from_bytes(&buf[..])?; assert_eq!(person.age, 35); // References are incrementally validated. assert_eq!(buf.load(person.name)?, "John-John"); ``` -------------------------------- ### Basic Musli Serialization with Custom Module Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates a basic Musli serialization setup with a custom encoding and decoding module for a specific field within a struct. This allows for fine-grained control over how individual fields are serialized. ```rust mod example { use musli::{Decode, Encode}; #[derive(Decode, Encode)] struct Container { #[musli(with = self::module)] field: Field, } struct Field { /* internal */ } mod module { use musli::{Decoder, Encoder}; use super::Field; pub fn encode(field: &Field, encoder: E) -> Result<(), E::Error> where E: Encoder, { todo!() } pub fn decode<'de, D>(decoder: D) -> Result where D: Decoder<'de>, { todo!() } } } ``` -------------------------------- ### JSON Externally Tagged Enum Example Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows the JSON output for an externally tagged enum in Musli. The variant tag is a top-level key, making it portable across formats. ```json {"Request": {"id": "...", "method": "...", "params": {...}}} ``` -------------------------------- ### Store Slice with musli-zerocopy Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Illustrates storing a slice of `u32` values and a reference to it using `OwnedBuf`. The example shows the layout of the slice elements and the reference (offset and length) within the buffer. ```rust use musli_zerocopy::{Ref, OwnedBuf}; let mut buf = OwnedBuf::new(); let slice: Ref<[u32]> = buf.store_slice(&[1, 2, 3, 4])?; let reference = buf.store(&slice)?; assert_eq!(reference.offset(), 16); ``` -------------------------------- ### Store Custom Struct with musli-zerocopy Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Provides an example of storing a custom struct containing a `u32` field and a `Ref` using `OwnedBuf`. It demonstrates how the struct, including its fields and the string reference, is serialized into the buffer. ```rust use core::mem::size_of; use musli_zerocopy::{OwnedBuf, Ref, ZeroCopy}; #[derive(ZeroCopy)] #[repr(C)] struct Custom { field: u32, string: Ref, } let mut buf = OwnedBuf::new(); let string = buf.store_unsized("Hello World!")?; let custom = buf.store(&Custom { field: 42, string })?; // The buffer stores both the unsized string and the Custom element. assert!(buf.len() >= 24); // We assert that the produced alignment is smaller or equal to 8 // since we'll be relying on this below. assert!(buf.requested() <= 8); ``` -------------------------------- ### JSON Internally Tagged Enum Example Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Presents the JSON output for an internally tagged enum in Musli, where a specific field ('type' in this case) indicates the enum variant. ```json {"type": "Request", "id": "...", "method": "...", "params": {...}} ``` -------------------------------- ### Read Custom Type from Aligned Buffer (Rust) Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Provides an example of reading a custom type directly from an aligned byte buffer using Musli Zerocopy. It shows how to create a reference to the type within the buffer and load its fields. ```rust use core::mem::size_of; use musli_zerocopy::Buf; // Helper to force the static buffer to be aligned like `A`. #[repr(C)] struct Align([A; 0], T); static BYTES: &Align = &Align([], *include_bytes!("custom.bin")); let buf = Buf::new(&BYTES.1); // Construct a pointer into the buffer. let custom = Ref::::new(BYTES.1.len() - size_of::()); let custom: &Custom = buf.load(custom)?; assert_eq!(custom.field, 42); assert_eq!(buf.load(custom.string)?, "Hello World!"); ``` -------------------------------- ### Musli Serialization with Custom UUID and HashSet Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Provides a comprehensive example of custom Musli serialization for complex types like `CustomUuid` and `HashSet`. It defines specific encoding and decoding functions for these types, demonstrating advanced customization capabilities. ```rust mod example { use std::collections::HashSet; use musli::{Encode, Decode}; pub struct CustomUuid(u128); #[derive(Encode, Decode)] struct Struct { #[musli(with = self::custom_uuid)] id: CustomUuid, #[musli(with = self::custom_set)] numbers: HashSet, } mod custom_uuid { use musli::{Context, Decode, Decoder, Encode, Encoder}; use super::CustomUuid; pub fn encode(uuid: &CustomUuid, encoder: E) -> Result<(), E::Error> where E: Encoder, { uuid.0.encode(encoder) } pub fn decode<'de, D>(decoder: D) -> Result where D: Decoder<'de>, { Ok(CustomUuid(decoder.decode()?)) } } mod custom_set { use std::collections::HashSet; use std::hash::Hash; use musli::{Context, Decode, Decoder, Encode, Encoder}; pub fn encode(set: &HashSet, encoder: E) -> Result<(), E::Error> where E: Encoder, T: Encode + Eq + Hash, { encoder.encode(set) } pub fn decode<'de, D, T>(decoder: D) -> Result, D::Error> where D: Decoder<'de>, T: Decode<'de, D::Mode, D::Allocator> + Eq + Hash, { decoder.decode() } } } ``` -------------------------------- ### Musli Skip Field with Default Value Example Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows how to use the `#[musli(skip)]` attribute to exclude a field from serialization and how to provide a custom default value using `#[musli(default = ...)]`. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Person { name: String, #[musli(skip)] age: Option, #[musli(skip, default = default_country)] country: Option, } fn default_country() -> Option { Some(String::from("Earth")) } ``` -------------------------------- ### Rust Musli Binary and Text Modes Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates using Musli's Binary and Text modes with Rust structs. The Binary mode uses indexed fields, while the Text mode uses literal text fields by name. This example shows how to derive Encode and Decode traits and apply mode-specific attributes. ```rust use musli::{Encode, Decode}; use musli::mode::Binary; use musli::json::Encoding; #[derive(Encode, Decode)] struct Person<'a> { #[musli(Text, name = "name")] not_name: &'a str, age: u32, } const TEXT: Encoding = Encoding::new(); const BINARY: Encoding = Encoding::new().with_mode(); let named = TEXT.to_vec(&Person { not_name: "Aristotle", age: 61 })?; assert_eq!(named.as_slice(), br#"{"name":"Aristotle","age":61}""#); let indexed = BINARY.to_vec(&Person { not_name: "Plato", age: 84 })?; assert_eq!(indexed.as_slice(), br#"{"0":"Plato","1":84}""#); Ok::<_, musli::json::Error>(()) ``` -------------------------------- ### Customize Text Mode with Field Name Indexing Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates customizing the Text mode for the Person struct to use usize for field names. This example shows how meta-attributes can alter derive behavior for specific modes. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(Text, name(type = usize))] struct Person<'a> { name: &'a str, age: u32, } ``` -------------------------------- ### Run Musli Tests (Serialization) Source: https://github.com/udoprog/musli/blob/main/tests/README.md Executes serialization tests for the Musli crate using the 'tests' binary. The `--features musli-wire` flag enables necessary features. ```sh cargo run -p tests --features musli-wire ``` -------------------------------- ### Conditional Derives with decode_only Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Illustrates using `decode_only` to apply attributes exclusively for decoding. This example renames a field 'last_name' to 'last' specifically for the Text decoding mode. ```rust use musli::{Decode, Encode}; #[derive(Encode, Decode)] struct Name<'a> { sur_name: &'a str, #[musli(Text, decode_only, name = "last")] last_name: &'a str, } ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/udoprog/musli/blob/main/tools/README.md Executes all defined benchmarks, with each benchmark corresponding to a specific report. ```sh cargo run -p tools -- bench ``` -------------------------------- ### Run Musli Tests (Deserialization) Source: https://github.com/udoprog/musli/blob/main/tests/README.md Executes deserialization tests for the Musli crate using the 'tests' binary. The `--features musli-wire` flag enables necessary features, and `--random` generates random bytes for testing. ```sh cargo run -p tests --features musli-wire -- --random ``` -------------------------------- ### Run Musli Tests with Miri (Deserialization) Source: https://github.com/udoprog/musli/blob/main/tests/README.md Runs deserialization tests for the Musli crate using the 'tests' binary and Miri for memory safety. The `--features musli-wire` flag enables necessary features. When run with Miri, dataset sizes are reduced. ```sh cargo +nightly miri run -p tests --features musli-wire -- --random ``` -------------------------------- ### Generate Full Benchmark Report Source: https://github.com/udoprog/musli/blob/main/tools/README.md Generates a comprehensive report by iterating through all feature combinations. This process can be time-consuming. Use the `--quick` flag for faster testing. ```sh cargo run -p tools -- bench --report full ``` -------------------------------- ### Run Musli Tests with Miri (Serialization) Source: https://github.com/udoprog/musli/blob/main/tests/README.md Runs serialization tests for the Musli crate using the 'tests' binary, with Miri enabled for memory safety checks. The `--features musli-wire` flag enables necessary features. When run with Miri, dataset sizes are reduced. ```sh cargo +nightly miri run -p tests --features musli-wire ``` -------------------------------- ### Run Musli Benchmarks Source: https://github.com/udoprog/musli/blob/main/tests/README.md Executes the benchmarking suite for the Musli crate. The `--force` flag overwrites existing violation plots, ensuring comparable feature sets are grouped for accurate reporting in `benchmarks-new/index.md`. ```rust cargo run -p tools -- --bench --force ``` -------------------------------- ### Run Clippy for Sanity Checks Source: https://github.com/udoprog/musli/blob/main/tools/README.md Runs clippy to perform sanity checks on the configuration. This check is performed for each report. ```sh cargo run -p tools -- clippy ``` -------------------------------- ### Fuzz Serde JSON with Musli Tests Source: https://github.com/udoprog/musli/blob/main/tests/README.md Fuzzes the `serde_json` framework using the Musli 'tests' binary by enabling the `serde_json` feature. This allows targeted fuzzing of specific serialization frameworks. ```sh cargo run -p tests --features serde_json ``` -------------------------------- ### Build Portable Archive with Little-Endian Byte Order (Rust) Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Demonstrates building a portable archive using `OwnedBuf` with a specified little-endian byte order. It shows how to store various data types and verifies the resulting buffer content. ```rust use musli_zerocopy::{endian, Endian, OwnedBuf}; let mut buf = OwnedBuf::new() .with_byte_order::(); let first = buf.store(&Endian::le(42u16))?; let portable = Archive { string: buf.store_unsized("Hello World!")?, number: Endian::new(10), }; let portable = buf.store(&portable)?; assert_eq!(&buf[..], &[ 42, 0, // 42u16 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, // "Hello World!" 0, 0, // padding 2, 0, 0, 0, 12, 0, 0, 0, // Ref 10, 0, 0, 0 // 10u32 ]); let portable = buf.load(portable)?; ``` -------------------------------- ### Rust: Initializing OwnedBuf with custom Size Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Demonstrates the use of `OwnedBuf::with_size` to initialize an `OwnedBuf` with a custom `Size` implementation, such as `usize`. ```rust use musli_zerocopy::OwnedBuf; use musli_zerocopy::buf::DefaultAlignment; let mut buf = OwnedBuf::with_capacity_and_alignment::(0)? .with_size::(); ``` -------------------------------- ### Compare Musli Structure Sizes Source: https://github.com/udoprog/musli/blob/main/tests/README.md Performs a size comparison of generated structures within the Musli project. The `--size` flag generates a JSON report intended for consumption by the benchmarking 'tools' crate. ```sh cargo run -p tests -- --size ``` -------------------------------- ### Rust: Compare Musli Encoding with Manual Serialization Source: https://github.com/udoprog/musli/blob/main/README.md Compares the efficiency of Musli's encoding with manual byte-level serialization for a Rust struct. Both methods aim to produce the same assembly output when compiled in release mode, highlighting Musli's optimization capabilities. ```rust const OPTIONS: Options = options::new().fixed().native_byte_order().build(); const ENCODING: Encoding = Encoding::new().with_options(); #[derive(Encode, Decode)] #[musli(packed)] pub struct Storage { left: u32, right: u32, } fn with_musli(storage: &Storage) -> Result<[u8; 8]> { let mut array = [0; 8]; ENCODING.encode(&mut array[..], storage)?; Ok(array) } fn without_musli(storage: &Storage) -> Result<[u8; 8]> { let mut array = [0; 8]; array[..4].copy_from_slice(&storage.left.to_ne_bytes()); array[4..].copy_from_slice(&storage.right.to_ne_bytes()); Ok(array) } ``` -------------------------------- ### Add musli to Cargo.toml Source: https://github.com/udoprog/musli/blob/main/README.md This snippet shows how to add the musli crate to your project's Cargo.toml file, including a specific version and feature flag for storage. ```TOML [dependencies] musli = { version = "0.0.145", features = ["storage"] } ``` -------------------------------- ### Rust: Exceeding 32-bit limit for Ref Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Demonstrates a panic when attempting to create a `Ref` with an address larger than 2^32, highlighting the default 32-bit limitation. ```rust Ref::::new(1usize << 32); ``` -------------------------------- ### Musli Field Pattern Matching for Decoding Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates using `#[musli(pattern = ...)]` to specify patterns for decoding fields, allowing for flexible matching of byte ranges or specific values. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Struct { field1: u32, field2: u32, #[musli(Binary, pattern = 2..=4)] other: u32, } ``` ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Struct { field1: u32, field2: u32, #[musli(Binary, pattern = (2..=4 | 10..=20))] other: u32, } ``` -------------------------------- ### Rust Enum with Custom Tag Formatting Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows how to apply custom formatting to tags and content using format_with, exemplified with BStr::new for byte string formatting. ```rust use bstr::BStr; use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(tag(value = b"type", format_with = BStr::new), content(value = b"data", format_with = BStr::new))] enum Message { Request { id: String, method: String }, Reply { id: String, body: Vec }, } ``` -------------------------------- ### Rust: Exceeding 32-bit limit for Ref Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Shows a panic when creating a `Ref` with a size larger than 2^32, emphasizing the 32-bit limit for string data. ```rust Ref::::with_metadata(0u32, 1usize << 32); ``` -------------------------------- ### Bitwise Encoding Limitations with NonZero Fields Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates a case where bitwise optimizations are only supported in one direction (encoding) due to the nature of NonZero types. ```rust use core::num::NonZero; use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(packed)] struct Struct { a: NonZero, b: u32, } const _: () = assert!(musli::is_bitwise_encode::()); const _: () = assert!(!musli::is_bitwise_decode::()); ``` -------------------------------- ### Define Portable Archive Structure (Rust) Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Defines a generic `Archive` struct that is `Portable` by accepting `ByteOrder` and `Size` type parameters. This allows for flexible byte order specification. ```rust use musli_zerocopy::{Size, ByteOrder, Ref, Endian, ZeroCopy}; #[derive(ZeroCopy)] #[repr(C)] struct Archive where E: ByteOrder, O: Size { string: Ref, number: Endian, } ``` -------------------------------- ### Rust SliceReader for efficient reading Source: https://github.com/udoprog/musli/blob/main/README.md The `SliceReader` provides a more efficient way to read from `&[u8]` slices compared to the default `Reader` implementation. It achieves this by performing comparisons directly on pointers, reducing overhead. ```Rust SliceReader ``` -------------------------------- ### Rust: Exceeding 32-bit limit for Ref<[T]> Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Illustrates a panic when using `Ref<[Custom]>` with a length exceeding 2^32, showcasing the 32-bit size constraint. ```rust Ref::<[Custom]>::with_metadata(0u32, 1usize << 32); ``` -------------------------------- ### Musli Bytes Encoding for Vectors and Slices Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates the use of `#[musli(bytes)]` to serialize and deserialize fields as byte arrays using `EncodeBytes` and `DecodeBytes` traits. ```rust use std::collections::VecDeque; use musli::{Decode, Encode}; #[derive(Decode, Encode)] struct Container<'de> { #[musli(bytes)] vec: Vec, #[musli(bytes)] vec_deque: VecDeque, #[musli(bytes)] bytes: &'de [u8], } ``` -------------------------------- ### Musli Custom Encoding/Decoding with `with` Attribute Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Explains how to use the `#[musli(with = )]` attribute to specify custom serialization and deserialization logic for a field by referencing an external module. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Struct { #[musli(with = custom_logic)] field: MyType, } ``` -------------------------------- ### Bitwise Optimizations with #[musli(packed)] Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows how #[musli(packed)] can enable bitwise optimizations if the serialization pattern matches memory layout. It includes checks using musli::is_bitwise_encode and musli::is_bitwise_decode. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(packed)] struct Struct { a: u32, b: u32, } const _: () = assert!(musli::is_bitwise_encode::()); const _: () = assert!(musli::is_bitwise_decode::()); ``` -------------------------------- ### Rust: Serialize Struct with Two Modes (Text and Alt) Source: https://github.com/udoprog/musli/blob/main/README.md This Rust code snippet demonstrates how to define and use two different serialization modes (Text and Alt) for a single struct named 'Word' using the Müsli library. It shows how to configure the modes and serialize the struct into JSON-like text and a packed array format. ```rust use musli::{Decode, Encode}; use musli::json::Encoding; enum Alt {} #[derive(Decode, Encode)] #[musli(Text, name_all = "name")] #[musli(mode = Alt, packed)] struct Word<'a> { text: &'a str, teineigo: bool, } const TEXT: Encoding = Encoding::new(); const ALT: Encoding = Encoding::new().with_mode(); let word = Word { text: "あります", teineigo: true, }; let out = TEXT.to_string(&word)?; assert_eq!(out, r#"{"text":"あります","teineigo":true}"#); let out = ALT.to_string(&word)?; assert_eq!(out, r#"["あります",true]"#); ``` -------------------------------- ### Musli: Enable Tracing with `trace` Attribute Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows how to use the `#[musli(trace)]` attribute to enable detailed error tracing for specific fields during serialization and deserialization. This attribute enhances debugging by providing more context, especially for complex data structures like HashMaps. ```rust use std::collections::HashMap; use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Collection { #[musli(trace)] values: HashMap, } ``` -------------------------------- ### Generate Report Source: https://github.com/udoprog/musli/blob/main/tools/README.md Generates a report, potentially optimized for release builds. The `--report ` argument can be used to filter for a specific report by its ID. ```sh cargo run -p tools -- report --release ``` -------------------------------- ### Write Custom Type at Offset Zero (Rust) Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Illustrates how to write a custom type at the beginning of a buffer (offset zero) using Musli Zerocopy. This method is useful for ensuring that all dependent data is stored at subsequent offsets. ```rust use musli_zerocopy::OwnedBuf; use musli_zerocopy::mem::PackedMaybeUninit; let mut buf = OwnedBuf::new(); let reference: Ref> = buf.store_uninit::()?; let string = buf.store_unsized("Hello World!")?; buf.load_uninit_mut(reference)?.write(&Custom { field: 42, string }); let reference = reference.assume_init(); assert_eq!(reference.offset(), 0); ``` -------------------------------- ### Applying Bounds with #[musli(bound = ...)] and #[musli(decode_bound = ...)] in Rust Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Illustrates how to use #[musli(bound = ...)] and #[musli(decode_bound = ...)] to enforce trait bounds on generic types for Encode and Decode implementations, including HRTBs. ```rust use std::marker::PhantomData; use musli::{Decode, Encode}; #[derive(Debug, Clone, Encode, Decode)] #[musli(Binary, bound = {T}, decode_bound = {T})] #[musli(Text, bound = {T: Encode}, decode_bound<'de, A> = {T: Decode<'de, Text, A>})] pub struct GenericWithBound { value: T, } ``` -------------------------------- ### Rust SIMD-accelerated String decoding Source: https://github.com/udoprog/musli/blob/main/README.md Unsafe code is utilized for owned `String` decoding across all binary formats to leverage faster string processing via the `simdutf8` library. Disabling the `simdutf8` feature removes this specific use of unsafe code. ```Rust simdutf8 ``` -------------------------------- ### Rust FixedBytes for uninitialized data Source: https://github.com/udoprog/musli/blob/main/README.md The `FixedBytes` type is a stack-based container that can operate on uninitialized data. Its implementation relies heavily on unsafe code to enable stack-based serialization, particularly useful in `no-std` environments. ```Rust FixedBytes ``` -------------------------------- ### Rust Enum Variant Decoding with Pattern Matching Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates using #[musli(pattern = ..)] to define custom patterns for decoding enum variants, including single ranges and multiple ranges. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] enum Enum { Variant1, Variant2, #[musli(Binary, pattern = 2..=4)] Deprecated, } ``` ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] enum Enum { Variant1, Variant2, #[musli(Binary, pattern = (2..=4 | 10..=20))] Deprecated, } ``` -------------------------------- ### Rust: Storing data with custom Size in OwnedBuf Source: https://github.com/udoprog/musli/blob/main/crates/musli-zerocopy/README.md Shows how to store various data types, including `Ref` for primitive, slice, and unsized types, within an `OwnedBuf` configured with `usize` for its size parameter. ```rust use musli_zerocopy::{DefaultAlignment, OwnedBuf, Ref, ZeroCopy}; use musli_zerocopy::endian::Native; #[derive(ZeroCopy)] #[repr(C)] struct Custom { reference: Ref, slice: Ref::<[u32], Native, usize>, unsize: Ref::, } let mut buf = OwnedBuf::with_capacity(0)? .with_size::(); let reference = buf.store(&42u32)?; let slice = buf.store_slice(&[1, 2, 3, 4])?; let unsize = buf.store_unsized("Hello World")?; buf.store(&Custom { reference, slice, unsize })?; ``` -------------------------------- ### Rust Struct with Encode/Decode Derives Source: https://github.com/udoprog/musli/blob/main/README.md Demonstrates how to derive the Encode and Decode traits for a Rust struct, enabling Musli's serialization capabilities. This is the core mechanism for defining the schema for serialization. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Person { /* .. fields .. */ } ``` -------------------------------- ### Rust Enum with String Tag and Content Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates using #[musli(tag = "type", content = "data")] to define string-based tags and content fields for enum variants. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(tag = "type", content = "data")] enum Message { Request { id: String, method: String }, Reply { id: String, body: Vec }, } ``` -------------------------------- ### Musli Packed Encoding for Tuples and Arrays Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows how to use the `#[musli(packed)]` attribute to serialize and deserialize fields using the `EncodePacked` and `DecodePacked` traits for compact, sequential data. ```rust use std::collections::VecDeque; use musli::{Decode, Encode}; #[derive(Decode, Encode)] struct Container { #[musli(packed)] tuple: (u32, u64), #[musli(packed)] array: [u32; 4], } ``` -------------------------------- ### Rust UTF-8 handling in musli::json Source: https://github.com/udoprog/musli/blob/main/README.md This section highlights unsafety related to UTF-8 handling in `musli::json`. The crate performs its own UTF-8 validity checks, similar to `serde_json`, to ensure correct processing. ```Rust musli::json ``` -------------------------------- ### Packed Encoding with #[musli(packed)] Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Illustrates the use of the #[musli(packed)] attribute to disable tagging and encode fields sequentially. This is efficient but requires careful handling of versioning. ```rust use musli::{Encode, Decode}; #[derive(Encode)] #[musli(packed)] struct Struct { field1: u32, field2: u64, } let data = musli::storage::to_vec(&Struct { field1: 1, field2: 2, })?; assert_eq!(data.as_slice(), [1, 2]); Ok::<_, musli::storage::Error>(()) ``` -------------------------------- ### Encode Data with Musli (Rust) Source: https://github.com/udoprog/musli/blob/main/README.md Encodes a value into a byte buffer using Musli with optimized options for speed. It pre-allocates serialization space and uses a packed format, requiring the data type to implement `Encode`. The function returns the number of bytes written. ```rust use musli::alloc::{Allocator, Global}; use musli::context::{self, ErrorMarker as Error}; use musli::options::{self, Float, Integer, Width, Options}; use musli::storage::Encoding; use musli::{Decode, Encode}; use musli::alloc::Slice; enum Packed {} const OPTIONS: Options = options::new().fixed().native_byte_order().build(); const ENCODING: Encoding = Encoding::new().with_options().with_mode(); #[inline] pub fn encode<'buf, T, A>(buf: &'buf mut [u8], value: &T, alloc: A) -> Result<&'buf [u8], Error> where T: Encode, A: Allocator, { let cx = context::new_in(alloc); let w = ENCODING.to_slice_with(&cx, &mut buf[..], value)?; Ok(&buf[..w]) } ``` -------------------------------- ### Formatting Custom Names with #[musli(name(format_with = ...))] in Rust Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Shows how to use #[musli(name(format_with = ...))] to specify a custom formatting method for #[musli(name(...))] attributes, improving diagnostic output for types like byte arrays. ```rust use bstr::BStr; use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(name(type = [u8], format_with = BStr::new))] struct StructBytesArray { #[musli(name = b"field1")] field1: u32, #[musli(name = b"field2")] field2: u32, } ``` -------------------------------- ### Rust mem::transmute in Tag::kind Source: https://github.com/udoprog/musli/blob/main/README.md This snippet uses `mem::transmute` to efficiently convert a value into the `Kind` enum, which is guaranteed to be `#[repr(u8)]`. This is done to ensure the conversion is as performant as possible. ```Rust mem::transmute ``` -------------------------------- ### Transparent Encoding with #[musli(transparent)] Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates how to use the #[musli(transparent)] attribute on a struct with a single field. This allows the field to be encoded/decoded directly without being treated as a separate field within the serialization format. ```rust use musli::{Encode, Decode}; #[derive(Encode)] #[musli(transparent)] struct Struct(u32); let data = musli::wire::to_vec(&Struct(42))?; let actual: u32 = musli::wire::from_slice(&data)?; assert_eq!(actual, 42u32); Ok::<_, musli::wire::Error>(()) ``` -------------------------------- ### Musli: Conditionally Skip Encoding with `skip_encoding_if` Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Demonstrates the use of the `#[musli(skip_encoding_if = ...)]` attribute to conditionally skip encoding a field. This is particularly useful for optional fields, such as `Option`, to avoid serializing them when they are `None`. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Person { name: String, #[musli(skip_encoding_if = Option::is_none)] age: Option, } ``` -------------------------------- ### Decode Data with Musli (Rust) Source: https://github.com/udoprog/musli/blob/main/README.md Decodes a value from a byte buffer using Musli with optimized options for speed. It utilizes a packed format and requires the data type to implement `Decode<'buf, Packed, A>`. The function returns the decoded value. ```rust use musli::alloc::{Allocator, Global}; use musli::context::{self, ErrorMarker as Error}; use musli::options::{self, Float, Integer, Width, Options}; use musli::storage::Encoding; use musli::{Decode, Encode}; use musli::alloc::Slice; enum Packed {} const OPTIONS: Options = options::new().fixed().native_byte_order().build(); const ENCODING: Encoding = Encoding::new().with_options().with_mode(); #[inline] pub fn decode<'buf, T, A>(buf: &'buf [u8], alloc: A) -> Result where T: Decode<'buf, Packed, A>, A: Allocator, { let cx = context::new_in(alloc); ENCODING.from_slice_with(&cx, buf) } ``` -------------------------------- ### Musli Field Renaming with `name` Attribute Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Illustrates how to rename fields during Musli serialization and deserialization using the `#[musli(name = ...)]` attribute with various data types. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] struct Struct { #[musli(name = "other")] something: String, #[musli(name = 1)] field1: u32, #[musli(name = "Hello World")] field2: String, #[musli(name = b"box\0")] field3: &'static [u8], #[musli(name = SomeStruct { field: 42 })] field4: SomeStruct, } #[derive(Encode, Decode)] struct SomeStruct { field: u32, } ``` -------------------------------- ### Container Attribute: Rename All Enum Variants to kebab-case Source: https://github.com/udoprog/musli/blob/main/crates/musli/help/derives.md Uses the `name_all` container attribute to rename all enum variants to kebab-case. This demonstrates bulk renaming for serialization consistency. ```rust use musli::{Encode, Decode}; #[derive(Encode, Decode)] #[musli(name_all = "kebab-case")] enum KebabCase { // This will be named `first-variant`. FirstVariant { field_name: u32, }, // This will be named `second-variant`. SecondVariant { field_name: u32, }, } ```