5 releases (2 stable)

1.0.1 Mar 17, 2024
1.0.0 Aug 31, 2023
0.1.2 Jul 1, 2021
0.1.1 Apr 6, 2020
0.1.0 Apr 6, 2020

#68 in No standard library

Download history 303/week @ 2024-01-27 335/week @ 2024-02-03 447/week @ 2024-02-10 472/week @ 2024-02-17 340/week @ 2024-02-24 164/week @ 2024-03-02 84/week @ 2024-03-09 163/week @ 2024-03-16 36/week @ 2024-03-23 57/week @ 2024-03-30 17/week @ 2024-04-06 26/week @ 2024-04-13 28/week @ 2024-04-20 27/week @ 2024-04-27 17/week @ 2024-05-04 12/week @ 2024-05-11

89 downloads per month
Used in 5 crates (via xoodoo)

MIT license

4KB

rawbytes

A Rust crate to view a structure as a plain byte array (&[u8]).

Super simple. Tiny. Zero dependencies.

This is a safer interface to slice::from_raw_parts_{mut}()

Example usage:

use rawbytes::RawBytes;

#[repr(C, packed(4))]
struct Foo {
    x: [u32; 32],
}

#[test]
fn test() {
    let mut foo = Foo { x: [0; 32] };

    let foo_bytes = RawBytes::bytes_view(&foo);
    assert_eq!(foo_bytes.len(), 128);

    let foo_bytes = RawBytes::bytes_view_mut(&mut foo);
    foo_bytes[0] = 1;
    assert_eq!(foo.x[0], 1);
}

Note that structures must should have the C representation to ensure that a new Rust release is not going to change the representation.

Warning and alternatives

Warning: this crate contains two instances of the unsafe keyword, because there are no other ways to achieve this in Rust. Still, you may be named and shamed for using a crate that perfectly does the job, but includes that keyword.

An alternative is the zerocopy crate. It's bigger, far more complex, not any faster, and it also require the unsafe keyword. But it's maintained by a Google employee, so you may be less named and shamed.

No runtime deps