### Validate Bytes with check_bytes Function in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Shows how to use the `check_bytes` function from the bytecheck library to validate if a pointer points to a valid value of a specified type. It returns `Ok(())` if the bytes are valid, and an error otherwise. This example demonstrates validating boolean values represented by `u8`. ```rust use bytecheck::check_bytes; use rancor::Failure; unsafe { // 0 and 1 are valid values for bools check_bytes::((&0u8 as *const u8).cast()).unwrap(); check_bytes::((&1u8 as *const u8).cast()).unwrap(); // 2 is not a valid value for bool check_bytes::((&2u8 as *const u8).cast()).unwrap_err(); } ``` -------------------------------- ### Contextual Byte Validation with check_bytes_with_context in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Illustrates using `check_bytes_with_context` for validating a pointer with custom contextual rules. This function allows passing a context object that can carry additional state for validation logic. The example defines a `Context` trait and a `ContextualByte` struct to demonstrate conditional validation based on the provided context. ```rust use core::{error::Error, fmt}; use bytecheck::{check_bytes_with_context, CheckBytes, Verify}; use rancor::{fail, Failure, Fallible, Source, Strategy}; trait Context { fn is_allowed(&self, value: u8) -> bool; } impl Context for Strategy { fn is_allowed(&self, value: u8) -> bool { T::is_allowed(self, value) } } struct Allowed(u8); impl Context for Allowed { fn is_allowed(&self, value: u8) -> bool { value == self.0 } } #[derive(CheckBytes)] #[bytecheck(verify)] #[repr(C)] pub struct ContextualByte(u8); unsafe impl Verify for ContextualByte where C::Error: Source, { fn verify(&self, context: &mut C) -> Result<(), C::Error> { #[derive(Debug)] struct InvalidByte(u8); impl fmt::Display for InvalidByte { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "invalid contextual byte: {}", self.0) } } impl Error for InvalidByte {} if !context.is_allowed(self.0) { fail!(InvalidByte(self.0)); } Ok(()) } } let value = 45u8; unsafe { // Checking passes when the context allows byte 45 check_bytes_with_context::( (&value as *const u8).cast(), &mut Allowed(45), ).unwrap(); // Checking fails when the context does not allow byte 45 check_bytes_with_context::( (&value as *const u8).cast(), &mut Allowed(0), ).unwrap_err(); } ``` -------------------------------- ### Rust: Validate Struct Bytes with Bytecheck Source: https://github.com/rkyv/bytecheck/blob/main/bytecheck/example.md This Rust code snippet demonstrates how to use the `bytecheck` crate to validate if a raw byte slice is a valid representation of a `Test` struct. It defines a `Test` struct with `CheckBytes` derivation and uses `check_bytes` to perform validation. The example includes cases for valid and invalid byte sequences for different fields, showcasing the crate's ability to catch type and range errors. ```rust use bytecheck::{CheckBytes, check_bytes, rancor::Failure}; #[derive(CheckBytes, Debug)] #[repr(C)] struct Test { a: u32, b: char, c: bool, } #[repr(C, align(4))] struct Aligned([u8; N]); macro_rules! bytes { ($($byte:literal,)*) => { (&Aligned([$($byte,)*]).0 as &[u8]).as_ptr() }; ($($byte:literal),*) => { bytes!($($byte,)*) }; } // In this example, the architecture is assumed to be little-endian #[cfg(target_endian = "little")] unsafe { // These are valid bytes for a `Test` check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap(); // Changing the bytes for the u32 is OK, any bytes are a valid u32 check_bytes::( bytes![ 42u8, 16u8, 20u8, 3u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap(); // Characters outside the valid ranges are invalid check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x00u8, 0xd8u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap_err(); check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x00u8, 0x00u8, 0x11u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap_err(); // 0 is a valid boolean value (false) but 2 is not check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 0u8, 255u8, 255u8, 255u8, ].cast() ).unwrap(); check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 2u8, 255u8, 255u8, 255u8, ].cast() ).unwrap_err(); } ``` -------------------------------- ### Validate Strings and Slices Source: https://context7.com/rkyv/bytecheck/llms.txt Shows validation for UTF-8 strings, byte slices, and null-terminated C strings, leveraging SIMD acceleration where applicable. ```rust use bytecheck::check_bytes; use rancor::{Failure, Infallible}; use core::ffi::CStr; unsafe { check_bytes::("hello world" as *const str).unwrap(); check_bytes::<[i32], Infallible>( &[1, 2, 3, 4] as &[i32] as *const [i32] ).unwrap(); let c_str = CStr::from_bytes_with_nul(b"hello\0").unwrap(); check_bytes::(c_str as *const CStr).unwrap(); } ``` -------------------------------- ### Validate Primitive Types and Collections Source: https://context7.com/rkyv/bytecheck/llms.txt Demonstrates how to validate basic Rust types including integers, floats, booleans, characters, NonZero types, tuples, and arrays using check_bytes. ```rust use bytecheck::check_bytes; use rancor::Failure; use core::num::NonZeroU32; unsafe { check_bytes::(&42u32).unwrap(); check_bytes::(&-100i64).unwrap(); check_bytes::(&3.14f32).unwrap(); check_bytes::(&true).unwrap(); check_bytes::(&false).unwrap(); check_bytes::(&'x').unwrap(); check_bytes::(&NonZeroU32::new(42).unwrap()).unwrap(); check_bytes::<(u32, bool, char), Failure>(&(42u32, true, 'x')).unwrap(); check_bytes::<[bool; 4], Failure>(&[true, false, true, false]).unwrap(); } ``` -------------------------------- ### Validate Data Structures with CheckBytes Source: https://github.com/rkyv/bytecheck/blob/main/README.md Demonstrates how to derive the CheckBytes trait for a struct and use the check_bytes function to validate raw byte buffers against the struct's memory layout. It handles alignment and type-specific constraints such as character and boolean validity. ```rust use bytecheck::{CheckBytes, check_bytes, rancor::Failure}; #[derive(CheckBytes, Debug)] #[repr(C)] struct Test { a: u32, b: char, c: bool, } #[repr(C, align(4))] struct Aligned([u8; N]); macro_rules! bytes { ($($byte:literal,)*) => { (&Aligned([$($byte,)*]).0 as &[u8]).as_ptr() }; ($($byte:literal),*) => { bytes!($($byte,)*) }; } #[cfg(target_endian = "little")] unsafe { check_bytes::(bytes![0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8].cast()).unwrap(); check_bytes::(bytes![0u8, 0u8, 0u8, 0u8, 0x00u8, 0xd8u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8].cast()).unwrap_err(); } ``` -------------------------------- ### Implement CheckBytes Trait for Custom Type in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Demonstrates how to implement the `CheckBytes` trait for a custom Rust struct (`NonMaxU32`) to define specific validation logic. This allows for byte-level validation before casting, ensuring the raw bytes represent a valid instance of the type. It includes custom error handling for validation failures. ```rust use core::{error::Error, fmt}; use bytecheck::CheckBytes; use rancor::{fail, Fallible, Source}; #[repr(C, align(4))] pub struct NonMaxU32(u32); unsafe impl CheckBytes for NonMaxU32 where C::Error: Source, { unsafe fn check_bytes( value: *const Self, context: &mut C, ) -> Result<(), C::Error> { #[derive(Debug)] struct NonMaxCheckError; impl fmt::Display for NonMaxCheckError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "non-max u32 was set to u32::MAX") } } impl Error for NonMaxCheckError {} let value = unsafe { value.read() }; if value.0 == u32::MAX { fail!(NonMaxCheckError); } Ok(()) } } ``` -------------------------------- ### String and Slice Validation Source: https://context7.com/rkyv/bytecheck/llms.txt Validates complex types like UTF-8 strings, byte slices, and C-style strings. ```APIDOC ## POST /check_bytes/complex ### Description Performs structural validation on complex types, including UTF-8 verification for strings and null-termination checks for C strings. ### Method POST ### Endpoint /check_bytes/complex ### Parameters #### Request Body - **type** (string) - Required - The target type (str, [T], CStr) - **data** (bytes) - Required - The raw byte buffer to validate ### Request Example { "type": "str", "data": "68656c6c6f" } ### Response #### Success Response (200) - **status** (string) - Returns "ok" if validation succeeds #### Response Example { "status": "ok" } ``` -------------------------------- ### Customizing Bytecheck Validation with Derive Macro Attributes in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Customizes bytecheck validation behavior using derive macro attributes. Supports omitting bounds for recursive types to prevent infinite trait bound expansion and adding custom verification steps. This allows for more flexible and efficient validation of complex data structures. ```rust use bytecheck::CheckBytes; use rancor::{Fallible, Infallible}; // Custom box type for recursive structures struct MyBox { inner: *const T, } unsafe impl CheckBytes for MyBox where T: CheckBytes, C: Fallible + ?Sized, { unsafe fn check_bytes( value: *const Self, context: &mut C, ) -> Result<(), C::Error> { unsafe { T::check_bytes((*value).inner, context) } } } // Recursive enum with omit_bounds to prevent infinite trait bound expansion #[derive(CheckBytes)] #[repr(u8)] enum Node { Nil, Cons(#[bytecheck(omit_bounds)] MyBox), } // Usage with recursive structure unsafe { let nil = Node::Nil; let cons = Node::Cons(MyBox { inner: &nil as *const Node, }); bytecheck::check_bytes::(&cons).unwrap(); } ``` -------------------------------- ### Primitive Type Validation Source: https://context7.com/rkyv/bytecheck/llms.txt Validates basic Rust types including integers, floats, booleans, characters, and NonZero types. ```APIDOC ## POST /check_bytes/primitive ### Description Validates that a given memory location contains a valid bit pattern for the specified primitive type. ### Method POST ### Endpoint /check_bytes/primitive ### Parameters #### Request Body - **type** (string) - Required - The target Rust type (e.g., u32, bool, f32) - **data** (any) - Required - The raw memory or value to validate ### Request Example { "type": "u32", "data": 42 } ### Response #### Success Response (200) - **status** (string) - Returns "ok" if validation succeeds #### Response Example { "status": "ok" } ``` -------------------------------- ### Implementing Custom Invariant Checks with Verify Trait in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Adds custom invariant checks to data structures using the `Verify` trait in conjunction with the `#[bytecheck(verify)]` attribute. This allows for post-field validation checks to ensure data integrity beyond basic type and layout checks. It defines custom error types for specific validation failures. ```rust use core::{error::Error, fmt}; use bytecheck::{CheckBytes, Verify}; use rancor::{fail, Fallible, Source}; #[derive(CheckBytes)] #[bytecheck(verify)] #[repr(C, align(4))] pub struct NonMaxU32(u32); unsafe impl Verify for NonMaxU32 where C::Error: Source, { fn verify(&self, context: &mut C) -> Result<(), C::Error> { #[derive(Debug)] struct NonMaxCheckError; impl fmt::Display for NonMaxCheckError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "non-max u32 was set to u32::MAX") } } impl Error for NonMaxCheckError {} if self.0 == u32::MAX { fail!(NonMaxCheckError); } Ok(()) } } ``` -------------------------------- ### Derive CheckBytes Trait for Structs and Enums in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Automatically derives the `CheckBytes` trait for Rust structs and enums. This enables compile-time checks for byte-level data integrity. It supports attributes for custom bounds, crate paths, and verification hooks, ensuring that data conforms to expected byte layouts. ```rust use bytecheck::{CheckBytes, check_bytes, rancor::Failure}; #[derive(CheckBytes, Debug)] #[repr(C)] struct Test { a: u32, b: char, c: bool, } #[repr(C, align(4))] struct Aligned([u8; N]); macro_rules! bytes { ($($byte:literal,)*) => { (&Aligned([$($byte,)*]).0 as &[u8]).as_ptr() }; ($($byte:literal),*) => { bytes!($($byte,)*) }; } // In this example, the architecture is assumed to be little-endian #[cfg(target_endian = "little")] unsafe { // These are valid bytes for a `Test` check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap(); // Changing the bytes for the u32 is OK, any bytes are a valid u32 check_bytes::( bytes![ 42u8, 16u8, 20u8, 3u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap(); // Characters outside the valid ranges are invalid check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x00u8, 0xd8u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, ].cast() ).unwrap_err(); // 0 is a valid boolean value (false) but 2 is not check_bytes::( bytes![ 0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 2u8, 255u8, 255u8, 255u8, ].cast() ).unwrap_err(); } ``` -------------------------------- ### Validating Enums with Explicit Discriminant Representation in Rust Source: https://context7.com/rkyv/bytecheck/llms.txt Validates enums that have an explicit discriminant representation (e.g., `#[repr(u8)]`, `#[repr(i32)]`). This ensures that enum variants and their underlying byte representations are correctly checked for integrity. It supports enums with tuple variants, struct variants, and unit variants. ```rust use bytecheck::{CheckBytes, check_bytes}; use rancor::Failure; #[derive(CheckBytes, Debug)] #[repr(u8)] enum Test { A(u32, bool, char), B { a: u32, b: bool, c: char }, C, } // Enums with explicit discriminant values #[derive(CheckBytes, Debug)] #[repr(u8)] enum Status { Pending, Active = 100, Paused, Complete = 200, Archived, } unsafe { // Valid enum variants check_bytes::<_, Failure>(&Test::A(42, true, 'x')).unwrap(); check_bytes::<_, Failure>(&Test::B { a: 42, b: true, c: 'x' }).unwrap(); check_bytes::<_, Failure>(&Test::C).unwrap(); // Status enum variants with explicit values check_bytes::<_, Failure>(&Status::Pending).unwrap(); check_bytes::<_, Failure>(&Status::Active).unwrap(); check_bytes::<_, Failure>(&Status::Complete).unwrap(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.