### Manual Implementation Example Source: https://docs.rs/bytemuck/latest/bytemuck/checked/trait.CheckedBitPattern.html An example demonstrating how to manually implement the CheckedBitPattern trait for a custom enum. ```APIDOC use bytemuck::{CheckedBitPattern, NoUninit}; #[repr(u32)] #[derive(Copy, Clone)] enum MyEnum { Variant0 = 0, Variant1 = 1, Variant2 = 2, } unsafe impl CheckedBitPattern for MyEnum { type Bits = u32; fn is_valid_bit_pattern(bits: &u32) -> bool { match *bits { 0 | 1 | 2 => true, _ => false, } } } // It is often useful to also implement `NoUninit` on our `CheckedBitPattern` types. // This will allow us to do casting of mutable references (and mutable slices). // It is not always possible to do so, but in this case we have no padding so it is. unsafe impl NoUninit for MyEnum {} ``` -------------------------------- ### Rust Slice `rsplitn` Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Shows how to split a slice from the end into at most `n` parts using `rsplitn`. The example splits by numbers divisible by 3, limiting the output to 2 groups. ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### Rust Slice `splitn` Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates splitting a slice into at most `n` parts using `splitn`. The example splits the slice by numbers divisible by 3, limiting the output to 2 groups. ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.splitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### Rust Slice `rsplitn_mut` Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates splitting a mutable slice from the end into at most `n` parts using `rsplitn_mut`. The example modifies the first element of each resulting mutable subslice. ```rust let mut s = [10, 40, 30, 20, 60, 50]; for group in s.rsplitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(s, [1, 40, 30, 20, 60, 1]); ``` -------------------------------- ### Partial Sort Unstable By Key Slice Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates `partial_sort_unstable_by_key` for sorting based on a key extraction function. The examples cover empty ranges, single-element ranges, subranges, and the entire slice, using a reverse sort order. ```rust #![feature(slice_partial_sort_unstable)] let mut v = [4, -5, 1, -3, 2]; // empty range at the beginning, nothing changed v.partial_sort_unstable_by_key(0..0, |a| -a); assert_eq!(v, [4, -5, 1, -3, 2]); // empty range in the middle, partitioning the slice v.partial_sort_unstable_by_key(2..2, |a| -a); for i in 0..2 { assert!(v[i] >= v[2]); } for i in 3..v.len() { assert!(v[2] >= v[i]); } // single element range, same as select_nth_unstable v.partial_sort_unstable_by_key(2..3, |a| -a); for i in 0..2 { assert!(v[i] >= v[2]); } for i in 3..v.len() { assert!(v[2] >= v[i]); } // partial sort a subrange v.partial_sort_unstable_by_key(1..4, |a| -a); assert_eq!(&v[1..4], [2, 1, -3]); // partial sort the whole range, same as sort_unstable v.partial_sort_unstable_by_key(.., |a| -a); assert_eq!(v, [4, 2, 1, -3, -5]); ``` -------------------------------- ### Contiguous Trait - Example Usage Source: https://docs.rs/bytemuck/latest/bytemuck/trait.Contiguous.html An example demonstrating how to implement and use the Contiguous trait for a C-style enum `Foo`. ```APIDOC ## §Example ```rust #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq)] enum Foo { A = 0, B = 1, C = 2, D = 3, E = 4, } unsafe impl Contiguous for Foo { type Int = u8; const MIN_VALUE: u8 = Foo::A as u8; const MAX_VALUE: u8 = Foo::E as u8; } assert_eq!(Foo::from_integer(3).unwrap(), Foo::D); assert_eq!(Foo::from_integer(8), None); assert_eq!(Foo::C.into_integer(), 2); ``` ``` -------------------------------- ### Partial Sort Unstable By Slice Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Illustrates the usage of `partial_sort_unstable_by` with a custom comparison function for reverse sorting. It shows examples with empty, single-element, subranges, and the full slice. ```rust #![feature(slice_partial_sort_unstable)] let mut v = [4, -5, 1, -3, 2]; // empty range at the beginning, nothing changed v.partial_sort_unstable_by(0..0, |a, b| b.cmp(a)); assert_eq!(v, [4, -5, 1, -3, 2]); // empty range in the middle, partitioning the slice v.partial_sort_unstable_by(2..2, |a, b| b.cmp(a)); for i in 0..2 { assert!(v[i] >= v[2]); } for i in 3..v.len() { assert!(v[2] >= v[i]); } // single element range, same as select_nth_unstable v.partial_sort_unstable_by(2..3, |a, b| b.cmp(a)); for i in 0..2 { assert!(v[i] >= v[2]); } for i in 3..v.len() { assert!(v[2] >= v[i]); } // partial sort a subrange v.partial_sort_unstable_by(1..4, |a, b| b.cmp(a)); assert_eq!(&v[1..4], [2, 1, -3]); // partial sort the whole range, same as sort_unstable v.partial_sort_unstable_by(.., |a, b| b.cmp(a)); assert_eq!(v, [4, 2, 1, -3, -5]); ``` -------------------------------- ### Rust Slice `splitn_mut` Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Illustrates using `splitn_mut` to split a mutable slice into a maximum of `n` parts. The example modifies the first element of each resulting mutable subslice. ```rust let mut v = [10, 40, 30, 20, 60, 50]; for group in v.splitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(v, [1, 40, 30, 1, 60, 50]); ``` -------------------------------- ### Zeroable Struct Example Source: https://docs.rs/bytemuck/latest/bytemuck/derive.Zeroable.html Example of deriving `Zeroable` for a struct. The struct must be `Copy` and `Clone`, and its fields must also implement `Zeroable`. ```rust #[derive(Copy, Clone, Zeroable)] #[repr(C)] struct Test { a: u16, b: u16, } ``` -------------------------------- ### Get First Element Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Returns an Option containing a reference to the first element of the slice, or None if the slice is empty. ```rust pub fn first(&self) -> Option<&T> ``` ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Check if Slice Starts With Prefix Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `starts_with` to determine if a slice begins with a given sequence. It returns `true` for an empty prefix. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Rust Slice trim_prefix Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates removing a prefix from a slice. If the prefix is not present, the original slice is returned. This API is experimental and requires a nightly feature. ```rust #![feature(trim_prefix_suffix)] let v = &[10, 40, 30]; // Prefix present - removes it assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]); assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]); assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]); // Prefix absent - returns original slice assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]); assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]); let prefix : &str = "he"; assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref()); ``` -------------------------------- ### try_cast_slice_box Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/fn.try_cast_slice_box.html Attempts to cast the content type of a Box<[T]> to another type. On failure, you get back an error along with the starting Box<[T]>. ```APIDOC ## Function try_cast_slice_box bytemuck::allocation ### Summary ```rust pub fn try_cast_slice_box( input: Box<[A]>, ) -> Result, (PodCastError, Box<[A]>)> ``` Available on **crate feature`extern_crate_alloc`** only. ### Description Attempts to cast the content type of a `Box<[T]>`. On failure you get back an error along with the starting `Box<[T]>`. ### Failure Conditions * The start and end content type of the `Box<[T]>` must have the exact same alignment. * The start and end content size in bytes of the `Box<[T]>` must be the exact same. ### Type Parameters * `A`: The original type of the elements in the `Box<[T]>`. Must implement `NoUninit`. * `B`: The target type for the elements in the `Box<[T]>`. Must implement `AnyBitPattern`. ### Parameters * `input`: A `Box<[A]>` to be cast. ### Returns A `Result` which is either: * `Ok(Box<[B]>)`: If the cast is successful, containing the new `Box<[B]>`. * `Err((PodCastError, Box<[A]>))`: If the cast fails, containing a `PodCastError` and the original `Box<[A]>`. ``` -------------------------------- ### Manual NoUninit Implementation for Struct Source: https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html Illustrates a manual implementation of the NoUninit trait for a struct. The struct must be repr(C) or repr(transparent) and all its fields must also implement NoUninit. ```rust unsafe impl NoUninit for MyStruct {} ``` -------------------------------- ### Fails to compile: &mut [u8] to &mut [u16] Source: https://docs.rs/bytemuck/latest/bytemuck/fn.must_cast_slice_mut.html This example fails to compile because the length of the `&mut [u8]` slice might not be a multiple of 2, which is required for conversion to `&mut [u16]`. ```rust // fails to compile (bytes.len() might not be a multiple of 2): let byte_pairs : &mut [[u8; 2]] = bytemuck::must_cast_slice_mut(bytes); ``` -------------------------------- ### try_cast_box Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/fn.try_cast_box.html Attempts to cast the content type of a Box. On failure, you get back an error along with the starting Box. This function is available only when the `extern_crate_alloc` feature is enabled. ```APIDOC ## Function try_cast_box ### Summary ``` pub fn try_cast_box(input: Box) -> Result, (PodCastError, Box)> ``` Available on **crate feature`extern_crate_alloc`** only. ### Description Attempts to cast the content type of a `Box`. On failure you get back an error along with the starting `Box`. ### Failure Conditions * The start and end content type of the `Box` must have the exact same alignment. * The start and end size of the `Box` must have the exact same size. ``` -------------------------------- ### Iterate Over Reverse Chunks Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `rchunks` to get an iterator over slices of `chunk_size` elements, starting from the end of the slice. The last chunk may be smaller if `chunk_size` does not divide the slice length. ```rust let slice = [0, 1, 2, 3, 4, 5]; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &[4, 5]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert_eq!(iter.next().unwrap(), &[0, 1]); assert!(iter.next().is_none()); ``` -------------------------------- ### Rust: Using partial_sort_unstable_by_key Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates various use cases of `partial_sort_unstable_by_key` on a slice, including empty ranges, single-element ranges, and full range sorting. It shows how to sort based on a key extracted from elements. ```rust #![feature(slice_partial_sort_unstable)] let mut v = [4i32, -5, 1, -3, 2]; // empty range at the beginning, nothing changed v.partial_sort_unstable_by_key(0..0, |k| k.abs()); assert_eq!(v, [4, -5, 1, -3, 2]); // empty range in the middle, partitioning the slice v.partial_sort_unstable_by_key(2..2, |k| k.abs()); for i in 0..2 { assert!(v[i].abs() <= v[2].abs()); } for i in 3..v.len() { assert!(v[2].abs() <= v[i].abs()); } // single element range, same as select_nth_unstable v.partial_sort_unstable_by_key(2..3, |k| k.abs()); for i in 0..2 { assert!(v[i].abs() <= v[2].abs()); } for i in 3..v.len() { assert!(v[2].abs() <= v[i].abs()); } // partial sort a subrange v.partial_sort_unstable_by_key(1..4, |k| k.abs()); assert_eq!(&v[1..4], [2, -3, 4]); // partial sort the whole range, same as sort_unstable v.partial_sort_unstable_by_key(.., |k| k.abs()); assert_eq!(v, [1, 2, -3, 4, -5]); ``` -------------------------------- ### Derive ByteHash for a generic struct with arrays Source: https://docs.rs/bytemuck/latest/bytemuck/derive.ByteHash.html Derive ByteHash for a generic struct that includes an array of a specific size. This example also requires implementing `NoUninit` for the generic type. ```rust #[derive(Copy, Clone, ByteHash)] #[repr(C)] struct Test { a: [u32; N], } unsafe impl NoUninit for Test {} ``` -------------------------------- ### Remove Prefix from Slice Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `strip_prefix` to get a subslice with the prefix removed. Returns `None` if the slice does not start with the specified prefix. Handles empty prefixes and prefixes equal to the entire slice. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### Get Element Offset Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Finds the index of an element reference within a slice using pointer arithmetic. Returns `None` if the element does not point to the start of an element within the slice. This method panics if `T` is zero-sized. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust 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 ``` -------------------------------- ### Manual AnyBitPattern Implementation Safety Rules Source: https://docs.rs/bytemuck/latest/bytemuck/trait.AnyBitPattern.html Outlines the critical safety rules that must be followed when manually implementing the AnyBitPattern trait. Manual implementation requires careful adherence to these guidelines to prevent unsoundness. ```rust // The type must be inhabited (eg: no Infallible). // The type must be valid for any bit pattern of its backing memory. // Structs need to have all fields also be `AnyBitPattern`. // It is disallowed for types to contain pointer types, `Cell`, `UnsafeCell`, atomics, and any other forms of interior mutability. // More precisely: A shared reference to the type must allow reads, and _only_ reads. ``` -------------------------------- ### Iterate over immutable chunks from the end of a slice Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `rchunks` to get an iterator over immutable slices of a specified size, starting from the end. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```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()); ``` -------------------------------- ### Using CheckedBitPattern with Casting Functions Source: https://docs.rs/bytemuck/latest/bytemuck/checked/trait.CheckedBitPattern.html Demonstrates how to use checked casting functions with types implementing CheckedBitPattern. ```APIDOC use bytemuck::{bytes_of, bytes_of_mut}; use bytemuck::checked; let bytes = bytes_of(&2u32); let result = checked::try_from_bytes::(bytes); assert_eq!(result, Ok(&MyEnum::Variant2)); // Fails for invalid discriminant let bytes = bytes_of(&100u32); let result = checked::try_from_bytes::(bytes); assert!(result.is_err()); // Since we implemented NoUninit, we can also cast mutably from an original type // that is `NoUninit + AnyBitPattern`: let mut my_u32 = 2u32; { let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32); assert_eq!(as_enum_mut, &mut MyEnum::Variant2); *as_enum_mut = MyEnum::Variant0; } assert_eq!(my_u32, 0u32); ``` -------------------------------- ### try_cast_slice_arc Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/fn.try_cast_slice_arc.html Attempts to cast the content type of a `Arc<[T]>`. On failure, you get back an error along with the starting `Arc<[T]>`. The bounds on this function are the same as `cast_mut`, because a user could call `Rc::get_unchecked_mut` on the output, which could be observable in the input. ```APIDOC ## Function try_cast_slice_arc ### Signature ```rust pub fn try_cast_slice_arc( input: Arc<[A]> ) -> Result, (PodCastError, Arc<[A]>)> ``` ### Available On * crate feature`extern_crate_alloc` and `target_has_atomic=ptr` only. ### Failure Conditions * The start and end content type of the `Arc<[T]>` must have the exact same alignment. * The start and end content size in bytes of the `Arc<[T]>` must be the exact same. ``` -------------------------------- ### NoUninit Implementation for Pod Types Source: https://docs.rs/bytemuck/latest/src/bytemuck/no_uninit.rs.html Implements the NoUninit trait for any type that already implements the Pod trait. This leverages the existing guarantees of Pod to satisfy NoUninit. ```rust unsafe impl NoUninit for T {} ``` -------------------------------- ### try_cast_arc Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/fn.try_cast_arc.html Attempts to cast the content type of a `Arc`. On failure you get back an error along with the starting `Arc`. The bounds on this function are the same as `cast_mut`, because a user could call `Rc::get_unchecked_mut` on the output, which could be observable in the input. ```APIDOC ## Function try_cast_arc Source: bytemuck::allocation ```rust pub fn try_cast_arc( input: Arc, ) -> Result, (PodCastError, Arc)> ``` Available on **crate feature`extern_crate_alloc` and `target_has_atomic=ptr`** only. ### Failure Conditions * The start and end content type of the `Arc` must have the exact same alignment. * The start and end size of the `Arc` must have the exact same size. ``` -------------------------------- ### Iterate over mutable chunks from the end of a slice Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `rchunks_mut` to get an iterator over mutable slices of a specified size, starting from the end. This allows in-place modification of slice elements within chunks. The last chunk may be smaller. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### Manual CheckedBitPattern Implementation for Enum Source: https://docs.rs/bytemuck/latest/bytemuck/checked/trait.CheckedBitPattern.html Demonstrates manual implementation of CheckedBitPattern for a fieldless enum, including the NoUninit trait. ```rust use bytemuck::{CheckedBitPattern, NoUninit}; #[repr(u32)] #[derive(Copy, Clone)] enum MyEnum { Variant0 = 0, Variant1 = 1, Variant2 = 2, } unsafe impl CheckedBitPattern for MyEnum { type Bits = u32; fn is_valid_bit_pattern(bits: &u32) -> bool { match *bits { 0 | 1 | 2 => true, _ => false, } } } // It is often useful to also implement `NoUninit` on our `CheckedBitPattern` types. // This will allow us to do casting of mutable references (and mutable slices). // It is not always possible to do so, but in this case we have no padding so it is. unsafe impl NoUninit for MyEnum {} ``` -------------------------------- ### Deriving NoUninit with Macro Source: https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html Demonstrates how to automatically implement the NoUninit trait for a struct using the derive macro. Ensure the 'derive' feature flag is enabled. ```rust #[cfg(feature = "derive")] #[derive(NoUninit)] #[repr(C)] struct MyStruct { a: u8, b: u16, } ``` -------------------------------- ### try_cast_rc Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/fn.try_cast_rc.html Attempts to cast the content type of a Rc. On failure, you get back an error along with the starting Rc. The bounds on this function are the same as cast_mut, because a user could call Rc::get_unchecked_mut on the output, which could be observable in the input. Available on crate feature `extern_crate_alloc` only. ```APIDOC ## Function try_cast_rc ### Description Attempts to cast the content type of a `Rc`. On failure you get back an error along with the starting `Rc`. The bounds on this function are the same as `cast_mut`, because a user could call `Rc::get_unchecked_mut` on the output, which could be observable in the input. Available on **crate feature`extern_crate_alloc`** only. ### Failure Conditions * The start and end content type of the `Rc` must have the exact same alignment. * The start and end size of the `Rc` must have the exact same size. ### Signature ```rust pub fn try_cast_rc( input: Rc, ) -> Result, (PodCastError, Rc)> ``` ``` -------------------------------- ### Zeroable Enum Examples Source: https://docs.rs/bytemuck/latest/bytemuck/derive.Zeroable.html Examples of deriving `Zeroable` for enums. The first example shows an enum with explicit discriminants, where one variant has discriminant 0. The second example demonstrates an enum with `#[repr(C)]` where the first variant implicitly has discriminant 0 and contains fields that must be `Zeroable`. ```rust #[derive(Copy, Clone, Zeroable)] #[repr(i32)] enum Values { A = 0, B = 1, C = 2, } ``` ```rust #[derive(Clone, Zeroable)] #[repr(C)] enum Implicit { A(bool, u8, char), B(String), C(std::num::NonZeroU8), } ``` -------------------------------- ### starts_with Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Determines if a slice begins with a specified prefix slice. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Parameters * `needle`: The slice to check as a prefix. ### Returns `true` if the slice starts with `needle`, `false` otherwise. ### Examples ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` Always returns `true` if `needle` is an empty slice: ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` ``` -------------------------------- ### Manual NoUninit Implementation for Enum Source: https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html Shows a manual implementation of the NoUninit trait for an enum. Enums must be #[repr(Int)] or #[repr(C)], and variants must adhere to struct-like rules. ```rust #[repr(u8)] enum MyEnum { VariantA, VariantB, } unsafe impl NoUninit for MyEnum {} ``` -------------------------------- ### NoUninit Implementations for NonZero Integer Types Source: https://docs.rs/bytemuck/latest/src/bytemuck/no_uninit.rs.html Implements the NoUninit trait for all NonZero integer types (both signed and unsigned, and for various bit widths). These types are guaranteed to have valid bit patterns and no padding. ```rust unsafe impl NoUninit for NonZeroU8 {} unsafe impl NoUninit for NonZeroI8 {} unsafe impl NoUninit for NonZeroU16 {} unsafe impl NoUninit for NonZeroI16 {} unsafe impl NoUninit for NonZeroU32 {} unsafe impl NoUninit for NonZeroI32 {} unsafe impl NoUninit for NonZeroU64 {} unsafe impl NoUninit for NonZeroI64 {} unsafe impl NoUninit for NonZeroU128 {} unsafe impl NoUninit for NonZeroI128 {} unsafe impl NoUninit for NonZeroUsize {} unsafe impl NoUninit for NonZeroIsize {} ``` -------------------------------- ### Getting the Last Element of a Slice Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates how to get an immutable reference to the last element of a slice. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Deriving AnyBitPattern Source: https://docs.rs/bytemuck/latest/bytemuck/trait.AnyBitPattern.html Demonstrates how to automatically implement the AnyBitPattern trait for structs and enums using the derive macro. This is the recommended approach for ensuring trait compliance. ```rust #[cfg(feature = "derive")] #[derive(AnyBitPattern)] struct MyStruct; #[cfg(feature = "derive")] #[derive(AnyBitPattern)] enum MyEnum { ``` -------------------------------- ### NoUninit Implementation for bool Source: https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html The bool type implements NoUninit as it is a simple, POD-like type with no padding. ```rust impl NoUninit for bool {} ``` -------------------------------- ### Getting the First Chunk of a Slice Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates how to get an immutable reference to the first `N` elements of a slice as an array. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### NoUninit Implementation for NonZero types Source: https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html Various NonZero integer types implement NoUninit, signifying they are safe to treat as plain old data. ```rust impl NoUninit for NonZeroI8 {} ``` ```rust impl NoUninit for NonZeroI16 {} ``` ```rust impl NoUninit for NonZeroI32 {} ``` ```rust impl NoUninit for NonZeroI64 {} ``` ```rust impl NoUninit for NonZeroI128 {} ``` ```rust impl NoUninit for NonZeroIsize {} ``` ```rust impl NoUninit for NonZeroU8 {} ``` ```rust impl NoUninit for NonZeroU16 {} ``` ```rust impl NoUninit for NonZeroU32 {} ``` ```rust impl NoUninit for NonZeroU64 {} ``` ```rust impl NoUninit for NonZeroU128 {} ``` ```rust impl NoUninit for NonZeroUsize {} ``` -------------------------------- ### NoUninit Implementations for Primitive Types Source: https://docs.rs/bytemuck/latest/src/bytemuck/no_uninit.rs.html Provides implementations of the NoUninit trait for several primitive types including char and bool. These types are guaranteed by the language to have no uninitialized or padding bytes. ```rust unsafe impl NoUninit for char {} unsafe impl NoUninit for bool {} ``` -------------------------------- ### Rust Slice `rsplit` Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Demonstrates splitting a slice from the end using `rsplit` with a predicate that matches the value 0. Shows how empty slices can be returned if the delimiter is at the beginning or end. ```rust let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` -------------------------------- ### AnyBitPattern Implementation for Pod types Source: https://docs.rs/bytemuck/latest/src/bytemuck/anybitpattern.rs.html Provides an implementation of the AnyBitPattern trait for any type that already implements the Pod trait. This leverages the existing guarantees of Pod types. ```APIDOC unsafe impl AnyBitPattern for T {} ``` -------------------------------- ### Using CheckedBitPattern with Casting Functions Source: https://docs.rs/bytemuck/latest/bytemuck/checked/trait.CheckedBitPattern.html Shows how to use checked casting functions like try_from_bytes and cast_mut with types implementing CheckedBitPattern. ```rust use bytemuck::{bytes_of, bytes_of_mut}; use bytemuck::checked; let bytes = bytes_of(&2u32); let result = checked::try_from_bytes::(bytes); assert_eq!(result, Ok(&MyEnum::Variant2)); // Fails for invalid discriminant let bytes = bytes_of(&100u32); let result = checked::try_from_bytes::(bytes); assert!(result.is_err()); // Since we implemented NoUninit, we can also cast mutably from an original type // that is `NoUninit + AnyBitPattern`: let mut my_u32 = 2u32; { let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32); assert_eq!(as_enum_mut, &mut MyEnum::Variant2); *as_enum_mut = MyEnum::Variant0; } assert_eq!(my_u32, 0u32); ``` -------------------------------- ### Zeroable Implementations for Pointers Source: https://docs.rs/bytemuck/latest/src/bytemuck/zeroable.rs.html Demonstrates `Zeroable` implementations for raw pointers, including mutable, constant, slice, and string pointers. ```APIDOC ## Implementations for Pointers ### Raw Pointers * `*mut T` `unsafe impl Zeroable for *mut T {}` * `*const T` `unsafe impl Zeroable for *const T {}` ### Slice Pointers * `*mut [T]` `unsafe impl Zeroable for *mut [T] {}` * `*const [T]` `unsafe impl Zeroable for *const [T] {}` ### String Pointers * `*mut str` `unsafe impl Zeroable for *mut str {}` * `*const str` `unsafe impl Zeroable for *const str {}` ``` -------------------------------- ### Split Off Slice Starting from Third Element Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `split_off` to remove and return a subslice from a slice starting at a specified index. The original slice is modified to exclude the removed part. This method accepts one-sided ranges like `2..`. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### NoUninit Implementation for char Source: https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html The char type implements NoUninit, indicating it is a plain old data type without uninitialized bytes. ```rust impl NoUninit for char {} ``` -------------------------------- ### Split Off Mutable Slice Starting from Third Element Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Use `split_off_mut` to remove and return a mutable subslice from a mutable slice starting at a specified index. The original mutable slice is modified to exclude the removed part. This method accepts one-sided ranges like `2..`. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut tail = slice.split_off_mut(2..).unwrap(); assert_eq!(slice, &mut ['a', 'b']); assert_eq!(tail, &mut ['c', 'd']); ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Returns the number of elements (bytes) in the slice. ```rust pub fn len(&self) -> usize ``` ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### AnyBitPattern for MaybeUninit Source: https://docs.rs/bytemuck/latest/bytemuck/trait.AnyBitPattern.html Shows the implementation of AnyBitPattern for MaybeUninit, where T itself must implement AnyBitPattern. This requires the 'zeroable_maybe_uninit' crate feature. ```rust impl AnyBitPattern for MaybeUninit where T: AnyBitPattern, Available on **crate feature`zeroable_maybe_uninit`** only. ``` -------------------------------- ### Rust: Using select_nth_unstable_by with a custom comparator Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Shows how to use `select_nth_unstable_by` with a custom comparator function to partition a slice. This example uses a reversed comparator to find elements greater than or equal to the median, the median itself, and elements less than or equal to it. ```rust let mut v = [-5i32, 4, 2, -3, 1]; // Find the items `>=` to the median, the median itself, and the items `<=` to it, by using // a reversed comparator. let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a)); assert!(before == [4, 2] || before == [2, 4]); assert_eq!(median, &mut 1); assert!(after == [-3, -5] || after == [-5, -3]); // We are only guaranteed the slice will be one of the following, based on the way we sort // about the specified index. assert!(v == [2, 4, 1, -5, -3] || v == [2, 4, 1, -3, -5] || v == [4, 2, 1, -5, -3] || v == [4, 2, 1, -3, -5]); ``` -------------------------------- ### iter Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Returns an iterator over the slice, yielding elements from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ``` let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Get BoxBytes Layout Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Retrieves the original memory layout associated with the BoxBytes instance. ```rust pub fn layout(&self) -> Layout ``` -------------------------------- ### Rust Slice binary_search Example Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Performs a binary search on a sorted slice. Returns Ok(index) if found, or Err(insertion_point) if not found. The slice must be sorted for predictable results. ```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, }); ``` -------------------------------- ### TransparentWrapper Trait Documentation Source: https://docs.rs/bytemuck/latest/src/bytemuck/transparent.rs.html Documentation for the TransparentWrapper trait, including its safety contract and usage examples. ```APIDOC ## TransparentWrapper ### Description A trait which indicates that a type is a `#[repr(transparent)]` wrapper around the `Inner` value. This allows safely copy transmuting between the `Inner` type and the `TransparentWrapper` type. Functions like `wrap_{}` convert from the inner type to the wrapper type and `peel_{}` functions do the inverse conversion from the wrapper type to the inner type. We deliberately do not call the wrapper-removing methods "unwrap" because at this point that word is too strongly tied to the Option/ Result methods. ### Safety The safety contract of `TransparentWrapper` is relatively simple: For a given `Wrapper` which implements `TransparentWrapper`: 1. `Wrapper` must be a wrapper around `Inner` with an identical data representations. This either means that it must be a `#[repr(transparent)]` struct which contains a either a field of type `Inner` (or a field of some other transparent wrapper for `Inner`) as the only non-ZST field. 2. Any fields *other* than the `Inner` field must be trivially constructable ZSTs, for example `PhantomData`, `PhantomPinned`, etc. (When deriving `TransparentWrapper` on a type with ZST fields, the ZST fields must be [`Zeroable`]). 3. The `Wrapper` may not impose additional alignment requirements over `Inner`. Note: this is currently guaranteed by `repr(transparent)`, but there have been discussions of lifting it, so it's stated here explicitly. 4. All functions on `TransparentWrapper` **may not** be overridden. ### Caveats If the wrapper imposes additional constraints upon the inner type which are required for safety, it's responsible for ensuring those still hold -- this generally requires preventing access to instances of the inner type, as implementing `TransparentWrapper for T` means anybody can call `T::cast_ref(any_instance_of_u)`. For example, it would be invalid to implement TransparentWrapper for `str` to implement `TransparentWrapper` around `[u8]` because of this. ### Examples #### Basic ```rust use bytemuck::TransparentWrapper; # #[derive(Default)] # struct SomeStruct(u32); #[repr(transparent)] struct MyWrapper(SomeStruct); unsafe impl TransparentWrapper for MyWrapper {} // interpret a reference to &SomeStruct as a &MyWrapper let thing = SomeStruct::default(); let inner_ref: &MyWrapper = MyWrapper::wrap_ref(&thing); // Works with &mut too. let mut mut_thing = SomeStruct::default(); let inner_mut: &mut MyWrapper = MyWrapper::wrap_mut(&mut mut_thing); # let _ = (inner_ref, inner_mut); // silence warnings ``` #### Use with dynamically sized types ```rust use bytemuck::TransparentWrapper; #[repr(transparent)] struct Slice([T]); unsafe impl TransparentWrapper<[T]> for Slice {} let s = Slice::wrap_ref(&[1u32, 2, 3]); assert_eq!(&s.0, &[1, 2, 3]); let mut buf = [1, 2, 3u8]; let sm = Slice::wrap_mut(&mut buf); ``` #### Deriving When deriving, the non-wrapped fields must uphold all the normal requirements, and must also be `Zeroable`. ```rust use bytemuck::TransparentWrapper; use std::marker::PhantomData; #[derive(TransparentWrapper)] #[repr(transparent)] #[transparent(usize)] struct Wrapper(usize, PhantomData); // PhantomData implements Zeroable for all T ``` Here, an error will occur, because `MyZst` does not implement `Zeroable`. ```compile_fail use bytemuck::TransparentWrapper; struct MyZst; #[derive(TransparentWrapper)] #[repr(transparent)] #[transparent(usize)] struct Wrapper(usize, MyZst); // MyZst does not implement Zeroable ``` ``` -------------------------------- ### Rust Slice `split_once` Example (Nightly) Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Illustrates the experimental `split_once` API for splitting a slice at the first occurrence of an element matching a predicate. It returns the prefix and suffix, excluding the matched element. Requires the `slice_split_once` feature. ```rust #![feature(slice_split_once)] let s = [1, 2, 3, 2, 4]; assert_eq!(s.split_once(|&x| x == 2), Some(( &[1][..], &[3, 2, 4][..] ))); assert_eq!(s.split_once(|&x| x == 0), None); ``` -------------------------------- ### get Source: https://docs.rs/bytemuck/latest/bytemuck/allocation/struct.BoxBytes.html Returns a reference to an element or subslice based on the provided index. Returns None if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method `get` ### Parameters - `index`: `I` where `I: SliceIndex<[T]>` - The index or range to access. ### Return Value - `Option<&>::Output>`: An optional reference to the element or subslice. ``` -------------------------------- ### Implementing AnyBitPattern for Pod Types Source: https://docs.rs/bytemuck/latest/src/bytemuck/anybitpattern.rs.html Provides an implementation of AnyBitPattern for any type that already implements the Pod trait. This leverages the stricter guarantees of Pod to satisfy AnyBitPattern. ```rust unsafe impl AnyBitPattern for T {} ```