29 releases

0.8.0-pre6 Jan 1, 2024
0.8.0-pre5 Dec 15, 2023
0.8.0-pre1 Nov 4, 2023
0.8.0-alpha.9 Mar 30, 2024
0.2.0 Nov 19, 2020

#26 in #repr

Download history 290982/week @ 2024-02-05 281107/week @ 2024-02-12 259800/week @ 2024-02-19 288338/week @ 2024-02-26 301966/week @ 2024-03-04 319522/week @ 2024-03-11 334868/week @ 2024-03-18 324254/week @ 2024-03-25 321308/week @ 2024-04-01 325617/week @ 2024-04-08 318705/week @ 2024-04-15 312396/week @ 2024-04-22 266823/week @ 2024-04-29 285489/week @ 2024-05-06 301466/week @ 2024-05-13 281160/week @ 2024-05-20

1,151,800 downloads per month
Used in 416 crates (via bytecheck)

MIT license

31KB
688 lines

bytecheck   Latest Version License

bytecheck is a type validation framework for Rust.

bytecheck in action

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<const N: usize>([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::<Test, Failure>(
        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::<Test, Failure>(
        bytes![
            42u8, 16u8, 20u8, 3u8,
            0x78u8, 0u8, 0u8, 0u8,
            1u8, 255u8, 255u8, 255u8,
        ].cast()
    ).unwrap();

    // Characters outside the valid ranges are invalid
    check_bytes::<Test, Failure>(
        bytes![
            0u8, 0u8, 0u8, 0u8,
            0x00u8, 0xd8u8, 0u8, 0u8,
            1u8, 255u8, 255u8, 255u8,
        ].cast()
    ).unwrap_err();
    check_bytes::<Test, Failure>(
        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::<Test, Failure>(
        bytes![
            0u8, 0u8, 0u8, 0u8,
            0x78u8, 0u8, 0u8, 0u8,
            0u8, 255u8, 255u8, 255u8,
        ].cast()
    ).unwrap();
    check_bytes::<Test, Failure>(
        bytes![
            0u8, 0u8, 0u8, 0u8,
            0x78u8, 0u8, 0u8, 0u8,
            2u8, 255u8, 255u8, 255u8,
        ].cast()
    ).unwrap_err();
}

lib.rs:

Procedural macros for bytecheck.

Dependencies

~0.3–0.8MB
~19K SLoC