7 releases (4 breaking)

0.5.0 May 3, 2021
0.4.1 Mar 17, 2021
0.4.0 Feb 19, 2021
0.3.0 Jan 11, 2021
0.1.0 Nov 14, 2020

#396 in Encoding

Download history 12/week @ 2021-01-21 11/week @ 2021-01-28 6/week @ 2021-02-04 19/week @ 2021-02-11 38/week @ 2021-02-18 13/week @ 2021-02-25 11/week @ 2021-03-04 46/week @ 2021-03-11 38/week @ 2021-03-18 54/week @ 2021-03-25 35/week @ 2021-04-01 122/week @ 2021-04-08 102/week @ 2021-04-15 38/week @ 2021-04-22 76/week @ 2021-04-29 17/week @ 2021-05-06

204 downloads per month
Used in 3 crates

MIT license

31KB
640 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,
}

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

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

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

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

Dependencies

~0.5–1MB
~22K SLoC