NewsCrawler.org

puns: a Rust crate that proves at compile time that two types can share bytes

Contribute to uael/puns development by creating an account on GitHub.
Image: Reddit

puns is a Rust library that reads a value of one type as a value of another type in place, a technique called type punning[1]. It is offered as a safe alternative to transmute[2] and to hand-written parsing of bytes. When the program is built, the two types are compared by their sizes, alignments[3], padding[4] and the values each byte can take. Each pun is then proven, checked at run time, or refused: a proven pun compiles to no instruction, a checked one tests only what could not be proven, and a refused one does not compile, for example when it would read padding or let safe code write an invalid value through a &mut.

Users write no unsafe code and implement no trait, since #[derive(Pun)] is all that is needed, and it works on stable Rust without std. Two types need not be declared alike to hold the same bytes, and a Position made of a u8 and a bool can be read as two bytes with no instruction. Reading a bool as a u8 through a &mut is refused, because safe code could then write a 2 where a bool should be.

Attributes on the derive describe what a field type cannot say, such as a size stored in a header or a checksum. The project shows this with UDP over IPv4 over Ethernet, where there is no parsing code and the declarations are the format. The frame is read in place, with nothing copied or allocated.

Read the original github.comDiscussion

Sources

  • GitHub

    Author: u/uaelucas

    Proving that two layouts are compatible at compile time, on stable Rust (puns, an alternative to zerocopy/bytemuck)

    2 comments

Published: First seen: Читать по-русски

Open as a page