### Rust Result unwrap Method Example Source: https://docs.rs/musli/latest/musli/descriptive/type Shows how to use the unwrap method on a Rust Result to get the Ok value. This method panics if the Result is an Err, and its use is generally discouraged in favor of safer alternatives. ```Rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```Rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Rust Result unwrap Method Example Source: https://docs.rs/musli/latest/musli/storage/type Shows how to use the unwrap method on a Rust Result to get the Ok value. This method panics if the Result is an Err, and its use is generally discouraged in favor of safer alternatives. ```Rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```Rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Example Usage of wrap() function Source: https://docs.rs/musli/latest/musli/wrap/struct Demonstrates how to use the `wrap::wrap()` function to wrap a `Vec` buffer. This example shows the basic instantiation of a `Wrap` type. ```Rust use musli::wrap; let buffer: Vec = Vec::new(); let wrapped = wrap::wrap(buffer); ``` -------------------------------- ### Rust Slice Binary Search By Key Example Source: https://docs.rs/musli/latest/musli/struct Provides an example of `binary_search_by_key` for searching in a slice where the sorting key is derived from the elements using a provided function. ```Rust let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)]; assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a, b)| b); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Rust Slice split_at Example Source: https://docs.rs/musli/latest/musli/fixed/struct Provides examples of `split_at` which divides a slice into two at a specified index. It shows how the slice is partitioned into a left and right part. ```rust let v = ['a', 'b', 'c']; { let (left, right) = v.split_at(0); assert_eq!(left, []); assert_eq!(right, ['a', 'b', 'c']); } { let (left, right) = v.split_at(2); assert_eq!(left, ['a', 'b']); assert_eq!(right, ['c']); } { let (left, right) = v.split_at(3); assert_eq!(left, ['a', 'b', 'c']); assert_eq!(right, []); } ``` -------------------------------- ### Rust Slice rchunks_exact_mut Example Source: https://docs.rs/musli/latest/musli/alloc/struct Provides an example of `rchunks_exact_mut` for mutable slices in Rust, enabling iteration over exact-sized mutable chunks from the end and handling remainders. ```Rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` -------------------------------- ### Rust Slice Binary Search By Key Example Source: https://docs.rs/musli/latest/musli/fixed/struct Provides an example of `binary_search_by_key` for searching in a slice where the sorting key is derived from the elements using a provided function. ```Rust let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)]; assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a, b)| b); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Rust Slice clone_from_slice Example Source: https://docs.rs/musli/latest/musli/struct Shows how to copy elements from one slice to another using `clone_from_slice`. Both slices must have the same length, and the element type must implement `Clone`. This example demonstrates copying between distinct slices. ```Rust let src = [1, 2, 3, 4]; let mut dst = [0, 0]; dst.clone_from_slice(&src[2..]); assert_eq!(src, [1, 2, 3, 4]); assert_eq!(dst, [3, 4]); ``` -------------------------------- ### Rust Slice clone_from_slice Example Source: https://docs.rs/musli/latest/musli/fixed/struct Shows how to copy elements from one slice to another using `clone_from_slice`. Both slices must have the same length, and the element type must implement `Clone`. This example demonstrates copying between distinct slices. ```Rust let src = [1, 2, 3, 4]; let mut dst = [0, 0]; dst.clone_from_slice(&src[2..]); assert_eq!(src, [1, 2, 3, 4]); assert_eq!(dst, [3, 4]); ``` -------------------------------- ### Rust Slice Windows with Cell Swap Example Source: https://docs.rs/musli/latest/musli/alloc/struct Illustrates using `windows` with `std::cell::Cell` to perform mutable operations on slice elements indirectly. This example swaps elements within windows, showcasing a workaround for the lack of a direct `windows_mut` equivalent. ```Rust use std::cell::Cell; let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5']; let slice = &mut array[..]; let slice_of_cells: &[Cell] = Cell::from_mut(slice).as_slice_of_cells(); for w in slice_of_cells.windows(3) { Cell::swap(&w[0], &w[2]); } assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']); ``` -------------------------------- ### Get Length of FixedBytes Source: https://docs.rs/musli/latest/musli/struct Returns the number of initialized bytes in the FixedBytes collection. The example demonstrates checking the length after initialization and after pushing a byte. ```Rust use musli::fixed::FixedBytes; let mut buffer = FixedBytes::<10>::new(); assert_eq!(buffer.len(), 0); buffer.push(42); assert_eq!(buffer.len(), 1); ``` -------------------------------- ### Rust Result product Example Source: https://docs.rs/musli/latest/musli/storage/type Shows how to use the product method on an iterator of Results. It calculates the product of all Ok values, returning the first Err encountered. ```Rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Get Remaining Capacity of FixedBytes Source: https://docs.rs/musli/latest/musli/struct Returns the number of bytes that can still be added to the FixedBytes container. The example shows the initial remaining capacity and after adding a byte. ```Rust use musli::fixed::FixedBytes; let mut buffer = FixedBytes::<10>::new(); assert_eq!(buffer.remaining(), 10); buffer.push(42); assert_eq!(buffer.remaining(), 9); ``` -------------------------------- ### Rust Result product Example Source: https://docs.rs/musli/latest/musli/descriptive/type Shows how to use the product method on an iterator of Results. It calculates the product of all Ok values, returning the first Err encountered. ```Rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Rust Result into_ok Method Example (Nightly) Source: https://docs.rs/musli/latest/musli/storage/type Demonstrates the nightly-only experimental into_ok method for Rust Results. This method safely returns the Ok value without panicking, useful for infallible error types. ```Rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Rust Slice rchunks Example Source: https://docs.rs/musli/latest/musli/alloc/struct Demonstrates the usage of the `rchunks` method on a Rust slice, which returns an iterator over chunks of a specified size starting from the end of the slice. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Rust Result into_ok Method Example (Nightly) Source: https://docs.rs/musli/latest/musli/descriptive/type Demonstrates the nightly-only experimental into_ok method for Rust Results. This method safely returns the Ok value without panicking, useful for infallible error types. ```Rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Rust Slice rchunks_exact Example Source: https://docs.rs/musli/latest/musli/alloc/struct Shows how to use `rchunks_exact` in Rust to get an iterator over exact-sized chunks from the end of a slice. It also demonstrates retrieving any remaining elements. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### Rust: Apply Custom Encoding Options Source: https://docs.rs/musli/latest/musli/wire/struct Shows how to create an `Encoding` instance and apply custom options to it. This example defines specific `Options` with `Integer::Fixed` and then creates an `Encoding` configured with these options. ```Rust use musli::options::{self, Options, Integer}; use musli::wire::Encoding; const OPTIONS: Options = options::new().integer(Integer::Fixed).build(); const CONFIG: Encoding = Encoding::new().with_options(); ``` -------------------------------- ### Get Vec Length Source: https://docs.rs/musli/latest/musli/alloc/struct Returns the number of elements currently in the vector. The example initializes a vector, checks its initial length, extends it with data, and then asserts the new length. ```Rust use musli::alloc::{AllocError, Vec}; musli::alloc::default(|alloc| { let mut a = Vec::new_in(alloc); assert_eq!(a.len(), 0); a.extend_from_slice(b"Hello")?; assert_eq!(a.len(), 5); Ok::<_, AllocError>(()) })?; ``` -------------------------------- ### Get Slice of Initialized Memory from FixedBytes Source: https://docs.rs/musli/latest/musli/struct Provides an immutable slice view of the initialized bytes within the FixedBytes container. The example shows accessing the data after extending the buffer. ```Rust use musli::fixed::FixedBytes; let mut buffer = FixedBytes::<10>::new(); buffer.extend_from_slice(&[1, 2, 3]); let slice = buffer.as_slice(); assert_eq!(slice, &[1, 2, 3]); ``` -------------------------------- ### Rust: Configuring Musli Storage Encoding with Options Source: https://docs.rs/musli/latest/musli/storage Illustrates how to configure the Musli storage encoding behavior using custom `Options`. This example sets the integer encoding to `Fixed` and applies these options to the `Encoding` struct. It then demonstrates encoding and decoding a `Person` struct with these custom configurations, verifying the output. ```Rust use musli::{Encode, Decode}; use musli::mode::Binary; use musli::options::{self, Options, Integer}; use musli::storage::Encoding; const OPTIONS: Options = options::new().integer(Integer::Fixed).build(); const CONFIG: Encoding = Encoding::new().with_options(); #[derive(Debug, PartialEq, Encode, Decode)] struct Person<'a> { name: &'a str, age: u32, } let mut out = Vec::new(); let expected = Person { name: "Aristotle", age: 61, }; CONFIG.encode(&mut out, &expected)?; let actual = CONFIG.decode(&out[..])?; assert_eq!(expected, actual); ``` -------------------------------- ### Get Vec Capacity Source: https://docs.rs/musli/latest/musli/alloc/struct Returns the total number of elements the vector can hold before needing to reallocate. The example checks the initial capacity, extends the vector, and asserts that the capacity is sufficient. ```Rust use musli::alloc::{AllocError, Vec}; musli::alloc::default(|alloc| { let mut a = Vec::new_in(alloc); assert_eq!(a.len(), 0); assert_eq!(a.capacity(), 0); a.extend_from_slice(b"Hello")?; assert_eq!(a.len(), 5); assert!(a.capacity() >= 5); Ok::<_, AllocError>(()) })?; ``` -------------------------------- ### Rust Slice Binary Search Example Source: https://docs.rs/musli/latest/musli/struct Demonstrates `binary_search` on a sorted slice to find elements. It shows successful searches, unsuccessful searches, and handling multiple matches. ```Rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Rust Musli Wire Full Upgrade Stability Example Source: https://docs.rs/musli/latest/musli/index Demonstrates full upgrade stability using `musli::wire` in Rust. `Version1` can be decoded from `Version2` by skipping unknown fields. Fields are explicitly named to prevent issues with reordering. ```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())?; ``` -------------------------------- ### Get Mutable Slice of Initialized Memory from FixedBytes Source: https://docs.rs/musli/latest/musli/struct Provides a mutable slice view of the initialized bytes within the FixedBytes container, allowing in-place modification. The example demonstrates modifying an element via the mutable slice. ```Rust use musli::fixed::FixedBytes; let mut buffer = FixedBytes::<10>::new(); buffer.extend_from_slice(&[1, 2, 3]); let slice = buffer.as_mut_slice(); slice[0] = 42; assert_eq!(buffer.as_slice(), &[42, 2, 3]); ``` -------------------------------- ### Initialize FixedBytes with capacity Source: https://docs.rs/musli/latest/musli/fixed/struct Demonstrates creating a FixedBytes buffer with a specified capacity and checking its initial length and remaining capacity. ```Rust use musli::fixed::FixedBytes; let buffer = FixedBytes::<128>::with_capacity(64); assert_eq!(buffer.len(), 0); assert_eq!(buffer.remaining(), 128); ``` -------------------------------- ### Rust: Get element offset in a slice Source: https://docs.rs/musli/latest/musli/fixed/struct Illustrates how to find the index of an element reference within a slice using `element_offset`. This method relies on pointer arithmetic and returns `None` if the element reference does not point to the start of an element. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Rust: Serde Integration Example for Müsli Source: https://docs.rs/musli/latest/musli/serde/index Demonstrates how to use the `#[musli(with = musli::serde)]` attribute to integrate serde-compatible types like `Address` and `Url` into a Müsli struct. This allows Müsli to transparently handle serialization and deserialization of these fields using serde. ```Rust use serde::{Serialize, Deserialize}; use musli::{Encode, Decode}; use url::Url; #[derive(Serialize, Deserialize)] struct Address { street: String, city: String, zip: u32, } #[derive(Encode, Decode)] #[musli(name_all = "name")] struct Person { name: String, #[musli(with = musli::serde)] address: Address, #[musli(with = musli::serde)] url: Url, } let json = musli::json::to_string(&Person { name: "John Doe".to_string(), address: Address { street: "Main St.".to_string(), city: "Springfield".to_string(), zip: 12345, }, url: Url::parse("https://example.com")?, })?; let musli = musli::json::from_str::(&json)?; assert_eq!(musli.name, "John Doe"); assert_eq!(musli.address.street, "Main St."); assert_eq!(musli.address.city, "Springfield"); assert_eq!(musli.address.zip, 12345); assert_eq!(musli.url, "https://example.com/"); ``` -------------------------------- ### Using SequenceHint to Get Sequence Size Source: https://docs.rs/musli/latest/musli/hint/trait Demonstrates how to use the `SequenceHint` trait to retrieve the size of a sequence. It shows examples with a known size hint, an optional size hint with a value, and an optional size hint without a value. ```Rust use musli_core::hint::SequenceHint; fn get_sequence_size(hint: H) -> Option where H: SequenceHint, { hint.get() } // Known size hint let size = get_sequence_size(10usize); assert_eq!(size, Some(10)); // Optional size hint with value let size = get_sequence_size(Some(7usize)); assert_eq!(size, Some(7)); // Optional size hint without value let size = get_sequence_size(None::); assert_eq!(size, None); ``` -------------------------------- ### Rust JSON Encoding and Decoding Example Source: https://docs.rs/musli/latest/musli/json/index Demonstrates how to use the `musli::json` module for encoding and decoding Rust structs. It shows versioning with default fields and handling of unknown fields during deserialization. ```Rust use musli::{Encode, Decode}; #[derive(Debug, PartialEq, Encode, Decode)] struct Version1 { name: String, } #[derive(Debug, PartialEq, Encode, Decode)] struct Version2 { name: String, #[musli(default)] age: Option, } let version2 = musli::json::to_vec(&Version2 { name: String::from("Aristotle"), age: Some(61), })?; let version1: Version1 = musli::json::from_slice(version2.as_slice())?; assert_eq!(version1, Version1 { name: String::from("Aristotle"), }); ``` -------------------------------- ### Rust: Split slice into reverse chunks with remainder Source: https://docs.rs/musli/latest/musli/struct Illustrates the `as_rchunks` method in Rust for splitting a slice into `N`-element arrays starting from the end. It clarifies the relationship between the remainder slice, the chunks, and the original slice length, providing a practical example. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### musli::alloc::with_buffer Example Source: https://docs.rs/musli/latest/musli/alloc/fn Demonstrates the usage of `musli::alloc::with_buffer` to create and manipulate `Vec` instances with a specified buffer size. It shows extending vectors, asserting their contents and lengths, and handling potential allocation errors. ```Rust use musli::alloc::{AllocError, Vec}; musli::alloc::with_buffer::<128, _>(|alloc| { let mut a = Vec::new_in(alloc); let mut b = Vec::new_in(alloc); b.extend_from_slice(b"He11o")?; a.extend_from_slice(b.as_slice())?; assert_eq!(a.as_slice(), b"He11o"); assert_eq!(a.len(), 5); a.extend_from_slice(b" W0rld")?; assert_eq!(a.as_slice(), b"He11o W0rld"); assert_eq!(a.len(), 11); let mut c = Vec::new_in(alloc); c.extend_from_slice(b"!")?; a.extend_from_slice(c.as_slice())?; assert_eq!(a.as_slice(), b"He11o W0rld!"); assert_eq!(a.len(), 12); Ok::<_, AllocError>(()) }); ``` -------------------------------- ### Rust: Split slice and modify last element Source: https://docs.rs/musli/latest/musli/struct Demonstrates splitting a mutable slice and modifying its last element. This example uses `split_last_mut` to get a mutable reference to the last element and the rest of the slice, then updates the last element and the first element of the remaining slice. ```Rust let mut x = &mut [0, 1, 2]; if let Some((last, elements)) = x.split_last_mut() { *last = 3; elements[0] = 4; elements[1] = 5; } assert_eq!(x, &[4, 5, 3]); ``` -------------------------------- ### Musli Vec: Get mutable slice Source: https://docs.rs/musli/latest/musli/alloc/struct Illustrates obtaining a mutable slice representing the initialized portion of the Musli Vec's buffer. This allows in-place modification of the vector's contents. The example demonstrates converting the vector to uppercase using the mutable slice. ```Rust use musli::alloc::{AllocError, Vec}; musli::alloc::default(|alloc| { let mut a = Vec::new_in(alloc); assert_eq!(a.as_slice(), b""); a.extend_from_slice(b"Hello")?; assert_eq!(a.as_slice(), b"Hello"); a.as_mut_slice().make_ascii_uppercase(); assert_eq!(a.as_slice(), b"HELLO"); Ok::<_, AllocError>(()) }); ``` -------------------------------- ### Rust: Configuring Wire Encoding with Options Source: https://docs.rs/musli/latest/musli/wire/index Illustrates how to configure the `musli` wire format's behavior using the `Encoding` type and custom `Options`. This example sets integer encoding to fixed and demonstrates encoding and decoding a `Person` struct with the custom configuration. ```Rust use musli::{Encode, Decode}; use musli::options::{self, Options, Integer}; use musli::wire::Encoding; const OPTIONS: Options = options::new().integer(Integer::Fixed).build(); const CONFIG: Encoding = Encoding::new().with_options(); #[derive(Debug, PartialEq, Encode, Decode)] struct Person<'a> { name: &'a str, age: u32, } let mut out = Vec::new(); let expected = Person { name: "Aristotle", age: 61, }; CONFIG.encode(&mut out, &expected)?; let actual = CONFIG.decode(&out[..])?; assert_eq!(expected, actual); ``` -------------------------------- ### Rust: Get Element Offset in Slice (Nightly) Source: https://docs.rs/musli/latest/musli/struct An experimental nightly-only API to find the byte offset of an element within a slice. It returns `Some(index)` if the element reference points to the start of an element, and `None` otherwise. This method uses pointer arithmetic and does not compare elements. Panics if `T` is zero-sized. ```Rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```Rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Rust: Unsafely get multiple disjoint mutable slice elements Source: https://docs.rs/musli/latest/musli/fixed/struct Provides examples of using `get_disjoint_unchecked_mut` to obtain mutable references to multiple elements or sub-slices within a mutable slice using indices or ranges. This method is unsafe and requires careful handling of indices to avoid undefined behavior. ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0, 2]); *a *= 10; *b *= 100; } assert_eq!(x, &[10, 2, 400]); unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]); a[0] = 8; b[0] = 88; b[1] = 888; } assert_eq!(x, &[8, 88, 888]); unsafe { let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]); a[0] = 11; a[1] = 111; b[0] = 1; } assert_eq!(x, &[1, 11, 111]); ``` -------------------------------- ### Musli Vec: Basic initialization and extension Source: https://docs.rs/musli/latest/musli/alloc/struct This example demonstrates the basic usage of Musli's `Vec` type, including creating a new vector within a default allocator and extending it with a byte slice. It asserts the initial empty state and the state after extension. ```Rust use musli::alloc::Vec; musli::alloc::default(|alloc| { let mut a = Vec::new_in(alloc); assert_eq!(a.as_slice(), b""); a.extend_from_slice(b"Hello")?; assert_eq!(a.as_slice(), b"Hello"); Ok::<_, AllocError>(()) }); ``` -------------------------------- ### Rust: Müsli Slice Allocator Initialization Source: https://docs.rs/musli/latest/musli/index Shows the initialization of the Müsli Slice allocator in Rust. This involves creating a buffer, typically using `ArrayBuffer`, and then creating a `Slice` allocator instance that points to this buffer. This setup is crucial for enabling the zero-heap-allocation strategy. ```Rust use musli::alloc::{ArrayBuffer, Slice}; let mut buf = ArrayBuffer::new(); let alloc = Slice::new(&mut buf); ``` -------------------------------- ### Get TypeId for any Type in Rust Source: https://docs.rs/musli/latest/musli/mode/enum Implements the Any trait for any type T that is 'static. This provides a method to get the TypeId of the instance. ```Rust impl Any for T where T: 'static + ?Sized{ fn type_id(&self) -> TypeId } ``` -------------------------------- ### Rust Slice Binary Search By Example Source: https://docs.rs/musli/latest/musli/struct Demonstrates `binary_search_by` which allows searching using a custom comparison function. This is useful when the sorting criteria are not directly on the elements themselves. ```Rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let seek = 13; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); let seek = 4; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); let seek = 100; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); let seek = 1; let r = s.binary_search_by(|probe| probe.cmp(&seek)); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Get TypeId of Encoding (Rust) Source: https://docs.rs/musli/latest/musli/wire/struct Implements the `Any` trait for `Encoding`, providing the `type_id` method to get the `TypeId` of the `Encoding` instance. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Slice: Get length Source: https://docs.rs/musli/latest/musli/alloc/struct Demonstrates how to get the number of elements in a slice. The `len()` method returns the current length of the slice as a `usize`. ```Rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Rust Slice split_at Examples Source: https://docs.rs/musli/latest/musli/struct Demonstrates the usage of the `split_at` method on an immutable slice in Rust, showing how it divides the slice into two parts at different indices. ```rust let v = ['a', 'b', 'c']; { let (left, right) = v.split_at(0); assert_eq!(left, []); assert_eq!(right, ['a', 'b', 'c']); } { let (left, right) = v.split_at(2); assert_eq!(left, ['a', 'b']); assert_eq!(right, ['c']); } { let (left, right) = v.split_at(3); assert_eq!(left, ['a', 'b', 'c']); assert_eq!(right, []); } ``` -------------------------------- ### Get Slice as Array Reference (Rust) Source: https://docs.rs/musli/latest/musli/alloc/struct Attempts to get a reference to the underlying array if its length matches the specified size `N`. This is a nightly-only experimental API. -------------------------------- ### Rust Unsafe Slice split_at_unchecked Examples Source: https://docs.rs/musli/latest/musli/struct Provides examples of using the `split_at_unchecked` method for immutable slices in Rust, highlighting its behavior without bounds checking. ```rust let v = ['a', 'b', 'c']; unsafe { let (left, right) = v.split_at_unchecked(0); assert_eq!(left, []); assert_eq!(right, ['a', 'b', 'c']); } unsafe { let (left, right) = v.split_at_unchecked(2); assert_eq!(left, ['a', 'b']); assert_eq!(right, ['c']); } unsafe { let (left, right) = v.split_at_unchecked(3); assert_eq!(left, ['a', 'b', 'c']); assert_eq!(right, []); } ``` -------------------------------- ### Rust: Change Encoding Options Source: https://docs.rs/musli/latest/musli/packed/struct Shows how to create an `Encoding` instance with a different set of options. This example defines new `OPTIONS` using `options::new().build()` and applies them using `with_options()`. ```Rust use musli::options::{self, Options, Integer}; use musli::packed::Encoding; const OPTIONS: Options = options::new().build(); const CONFIG: Encoding = Encoding::new().with_options(); ``` -------------------------------- ### Rust: Create Context with Buffer Allocator Source: https://docs.rs/musli/latest/musli/context/fn Shows how to create a context using an allocator that utilizes an existing buffer, demonstrating its use with JSON encoding. ```Rust use musli::{alloc, context}; let mut buf = alloc::ArrayBuffer::new(); let alloc = alloc::Slice::new(&mut buf); let cx = context::new_in(&alloc); let encoding = musli::json::Encoding::new(); let string = encoding.to_string_with(&cx, &42)?; assert_eq!(string, "42"); ``` -------------------------------- ### Rust Result sum Example Source: https://docs.rs/musli/latest/musli/descriptive/type Illustrates the sum method for iterators of Results. It aggregates the sum of Ok values, short-circuiting and returning the first Err if encountered. ```Rust let nums = vec![Ok(5), Ok(10), Ok(1), Ok(2)]; let total: Result = nums.into_iter().sum(); assert_eq!(total, Ok(18)); let nums = vec![Ok(5), Err("error"), Ok(1), Ok(2)]; let total: Result = nums.into_iter().sum(); assert!(total.is_err()); ``` -------------------------------- ### Create New FixedBytes Storage Source: https://docs.rs/musli/latest/musli/fixed/struct Demonstrates how to create a new FixedBytes buffer and check its initial state (length and emptiness). ```Rust use musli::fixed::FixedBytes; let mut buffer = FixedBytes::<128>::new(); assert_eq!(buffer.len(), 0); assert!(buffer.is_empty()); ``` -------------------------------- ### Rust Result sum Example Source: https://docs.rs/musli/latest/musli/storage/type Illustrates the sum method for iterators of Results. It aggregates the sum of Ok values, short-circuiting and returning the first Err if encountered. ```Rust let nums = vec![Ok(5), Ok(10), Ok(1), Ok(2)]; let total: Result = nums.into_iter().sum(); assert_eq!(total, Ok(18)); let nums = vec![Ok(5), Err("error"), Ok(1), Ok(2)]; let total: Result = nums.into_iter().sum(); assert!(total.is_err()); ``` -------------------------------- ### Rust Slice rchunks_exact_mut Example Source: https://docs.rs/musli/latest/musli/fixed/struct Illustrates `rchunks_exact_mut` for mutable iteration over exact-sized chunks from the end of a slice. The example modifies elements within these mutable chunks. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` -------------------------------- ### Rust: Create String from Ok Result Source: https://docs.rs/musli/latest/musli/wire/type Demonstrates creating a String from a successful Result using `into_ok`. This function is part of the nightly-only experimental API. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Get Slice as Fixed-Size Array (Nightly) Source: https://docs.rs/musli/latest/musli/struct Attempts to get a reference to the underlying array if the requested size `N` matches the slice's length. This is a nightly-only experimental API. ```rust pub fn as_array(&self) -> Option<&[T; N]> ``` -------------------------------- ### Get Mutable Slice as Array Reference (Rust) Source: https://docs.rs/musli/latest/musli/alloc/struct Attempts to get a mutable reference to the underlying array if its length matches the specified size `N`. This is a nightly-only experimental API. -------------------------------- ### Rust Slice Binary Search Example Source: https://docs.rs/musli/latest/musli/fixed/struct Demonstrates `binary_search` on a sorted slice to find elements. It shows successful searches, unsuccessful searches, and handling multiple matches. ```Rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Rust: Create String from Ok Result Source: https://docs.rs/musli/latest/musli/packed/type Demonstrates creating a String from a successful Result using `into_ok`. This function is part of the nightly-only experimental API. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Rust Result expect_err Method Example Source: https://docs.rs/musli/latest/musli/storage/type Provides an example of the expect_err method for Rust Results. This method returns the contained Err value or panics with a custom message if the Result is Ok. ```Rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### musli::wire Roundtrip Example Source: https://docs.rs/musli/latest/musli/wire/type Demonstrates a roundtrip serialization and deserialization process using `musli::wire`. It encodes a `Data` struct into bytes and then decodes it back, asserting that the original and decoded data are identical. This showcases the basic usage of `to_vec` and `from_slice`. ```Rust use musli::wire::{self, Result}; use musli::{Encode, Decode}; #[derive(Debug, PartialEq, Encode, Decode)] struct Data { value: u32, } fn wire_roundtrip(data: &Data) -> Result { let bytes = wire::to_vec(data)?; wire::from_slice(&bytes) } let original = Data { value: 42 }; let decoded = wire_roundtrip(&original)?; assert_eq!(original, decoded); ``` -------------------------------- ### Rust Result expect_err Method Example Source: https://docs.rs/musli/latest/musli/descriptive/type Provides an example of the expect_err method for Rust Results. This method returns the contained Err value or panics with a custom message if the Result is Ok. ```Rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Rust: Versioned Data Encoding and Decoding Source: https://docs.rs/musli/latest/musli/wire/index Demonstrates how to use `musli`'s derive macros for `Encode` and `Decode` to handle versioned data structures. It shows encoding a `Version2` struct and decoding it into a `Version1` struct, highlighting backward compatibility by skipping unknown fields. ```Rust use musli::{Encode, Decode}; #[derive(Debug, PartialEq, Encode, Decode)] struct Version1 { name: String, } #[derive(Debug, PartialEq, Encode, Decode)] struct Version2 { name: String, #[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())?; assert_eq!(version1, Version1 { name: String::from("Aristotle"), }); ``` -------------------------------- ### Rust: Get element or subslice by index Source: https://docs.rs/musli/latest/musli/struct Explains the generic `get` method for slices, which allows retrieving an element by position or a subslice by range. It returns `Some` with a reference if the index is valid, and `None` otherwise. ```Rust let slice = [10, 20, 30, 40]; // Get element at index 1 let element = slice.get(1); assert_eq!(element, Some(&20)); // Get subslice from index 1 to 3 (exclusive) let subslice = slice.get(1..3); assert_eq!(subslice, Some(&[20, 30])); // Index out of bounds let out_of_bounds = slice.get(5); assert_eq!(out_of_bounds, None); ```