grovesNL / glow

GL on Whatever: a set of bindings to run GL anywhere and avoid target-specific code
Apache License 2.0
1.2k stars 130 forks source link

Why is everything (in code examples) wrapped in unsafe? #261

Closed taitep closed 1 year ago

taitep commented 1 year ago

I checked some stuff and it seems that making rust bindings for c libraries that have unsafe code, but not needing the user of the bindings to use unsafe blocks is possible. Why not try to do this? It would make the development process nicer.

grovesNL commented 1 year ago

Hi! :wave:

Crates that provide low-level graphics API bindings like glow, ash, etc. require the caller to be responsible for making sure they follow all of the rules of the API (OpenGL in this case, Vulkan in ash's case). For example, glow can't guarantee that you don't read out-of-bounds in a shader and read uninitialized data, or cause undefined behavior if you use the API in a way that the driver doesn't expect.

Because glow can't guarantee that callers will use the API safely, we have to mark all functions that call the graphics driver as unsafe. If glow didn't mark these functions as unsafe, it would be possible for safe Rust code to segfault or other unexpected behavior which wouldn't follow Rust's safety guarantees.

It's possible to create safe graphics wrappers by wrapping all API calls and validating their usage (including validating shaders to clamp or avoid out-of-bounds accesses). This is what crates like wgpu do, so it's why wgpu doesn't require unsafe on their functions.