15 unstable releases (5 breaking)

0.6.7 Dec 3, 2021
0.6.5 Aug 6, 2021
0.6.3 Jul 17, 2021
0.4.1 Mar 17, 2021
0.2.0 Nov 19, 2020

#527 in Rust patterns

Download history 3623/week @ 2021-10-03 2284/week @ 2021-10-10 3895/week @ 2021-10-17 4805/week @ 2021-10-24 3665/week @ 2021-10-31 5667/week @ 2021-11-07 4301/week @ 2021-11-14 2729/week @ 2021-11-21 4087/week @ 2021-11-28 6458/week @ 2021-12-05 9684/week @ 2021-12-12 8083/week @ 2021-12-19 3948/week @ 2021-12-26 19022/week @ 2022-01-02 23513/week @ 2022-01-09 21340/week @ 2022-01-16

67,924 downloads per month
Used in 17 crates (via bytecheck)

MIT license

21KB
422 lines

bytecheck   Latest Version License requires: rustc 1.52+

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

~280–700KB
~17K SLoC

ia