16 unstable releases (5 breaking)

new 0.6.6 Nov 25, 2021
0.6.3 Jul 17, 2021
0.4.1 Mar 17, 2021
0.2.1 Dec 12, 2020
0.2.0 Nov 19, 2020

#155 in Encoding

Download history 1863/week @ 2021-08-08 2128/week @ 2021-08-15 1478/week @ 2021-08-22 1595/week @ 2021-08-29 1910/week @ 2021-09-05 3105/week @ 2021-09-12 3625/week @ 2021-09-19 4659/week @ 2021-09-26 3939/week @ 2021-10-03 2379/week @ 2021-10-10 4226/week @ 2021-10-17 4798/week @ 2021-10-24 3673/week @ 2021-10-31 5736/week @ 2021-11-07 4310/week @ 2021-11-14 2793/week @ 2021-11-21

15,436 downloads per month
Used in less than 11 crates

MIT license

50KB
991 lines

bytecheck is a type validation framework for Rust.

bytecheck in action

use bytecheck::CheckBytes;

#[derive(CheckBytes, Debug)]
struct Test {
    a: u32,
    b: bool,
    c: char,
}

#[repr(C, align(16))]
struct Aligned<const N: usize>([u8; N]);

macro_rules! bytes {
    ($($byte:literal,)*) => {
        (&Aligned([$($byte,)*]).0 as &[u8]).as_ptr()
    };
    ($($byte:literal),*) => {
        bytes!($($byte,)*)
    };
}

fn main() {
    // This type is laid out as (u32, char, bool)
    unsafe {
        // These are valid bytes for (0, 'x', true)
        Test::check_bytes(
            bytes![
                0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8,
                1u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8
            ].cast(),
            &()
        ).unwrap();

        // Changing the bytes for the u32 is OK, any bytes are a valid u32
        Test::check_bytes(
            bytes![
                42u8, 16u8, 20u8, 3u8, 0x78u8, 0u8, 0u8, 0u8,
                1u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8
            ].cast(),
            &()
        ).unwrap();

        // Characters outside the valid ranges are invalid
        Test::check_bytes(
            bytes![
                0u8, 0u8, 0u8, 0u8, 0x00u8, 0xd8u8, 0u8, 0u8,
                1u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8
            ].cast(),
            &()
        ).unwrap_err();
        Test::check_bytes(
            bytes![
                0u8, 0u8, 0u8, 0u8, 0x00u8, 0x00u8, 0x11u8, 0u8,
                1u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8
            ].cast(),
            &()
        ).unwrap_err();

        // 0 is a valid boolean value (false) but 2 is not
        Test::check_bytes(
            bytes![
                0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8,
                0u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8
            ].cast(),
            &()
        ).unwrap();
        Test::check_bytes(
            bytes![
                0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8,
                2u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8
            ].cast(),
            &()
        ).unwrap_err();
    }
}

Dependencies

~310–790KB
~19K SLoC