🗜 presser - A crate to help you copy things into raw buffers without invoking spooky action at a distance (UB)

140 points termhn

presser is a crate I wrote to help our devs internally at Embark Studios after observing how fraught it is to avoid soundness pitfalls in what at first seems like it should be a an easy task: copying the data of some type into an allocated buffer somewhere else. Unfortunately, it's not actually so obvious how to do this correctly in Rust, especially for developers who may have come from a C or C++ background. Hence, presser was born, and today it was fully open-sourced!

One primary use-case is copying data into graphics-api-allocated buffers which will then be accessed by the GPU. The most obvious path to do this right now in Rust (which I've seen being used in lots of open source as well as internal graphics code) can invoke undefined behavior in subtle ways.

For example, viewing an allocated but uninitialized buffer as an &mut [u8] slice ("it's just bytes, right?") is instantly undefined behavior, and transmuteing (even a T: Copy) type which has any padding bytes in its layout as a &[u8] to be the source of a copy is also instantly undefined behavior. In both cases this is because it is invalid to create a reference to an invalid value, and uninitialized memory is an invalid u8, even if your code never actually accesses that memory. This immediately makes what seems like the most straightforward way to copy data into buffers unsound 😬

And this isn't even taking into account the necessary hijinx to ensure alignment, which can also be fraught.

presser helps with this by allowing you to view raw allocated memory of some size as a "Slab" of memory and then provides safe, valid ways to copy data into that memory.

Further info:
Repo - https://github.com/EmbarkStudios/presser
Crates.io - https://crates.io/crates/presser