logoalt Hacker News

stavrosyesterday at 6:27 PM7 repliesview on HN

I thought Rust treated undefined behaviour as a compiler bug? Does anyone know what's actually happening here?


Replies

AlotOfReadingyesterday at 6:35 PM

"unsafe" is a promise to the compiler that you're going to ensure invariants that the compiler can't check. Rust only promises to eliminate UB if the invariants are held. You can still get UB by violating that promise, as this bug demonstrates.

show 1 reply
jcranmeryesterday at 7:20 PM

Rust has lots of undefined behavior, in general a broadly similar set to that which exists in C. What Rust does that is different is that to trigger undefined behavior, you need to execute unsafe code. (This isn't the same as saying that you have to be in unsafe code--you can violate a precondition in unsafe code and have the UB itself trigger in safe code).

show 1 reply
repelsteeltjeyesterday at 6:40 PM

I'm sure there have been attempts at defining a language that has no UB, but afaik all meaningful languages have UB in some dark corner or enumerated explicitly. For example, Java thread execution order is UB.

show 1 reply
quikoayesterday at 6:33 PM

It is only allowed in unsafe blocks. As long as the unsafe blocks are few and well understood then Rust programmers can contain this to a small well defined portion of a program.

stousetyesterday at 6:38 PM

Safe Rust does.

Unsafe Rust allows you to tell the compiler “hold my beer”. It’s a concession to the reality that the normal restrictions of Rust disallow some semantically valid programs that you might otherwise want to write. The safeguards work great in most cases, but in some they’re overly restrictive.

In practice, the overwhelming majority of code is able to be written in safe Rust and the compiler can have your back. The majority of the rest is for performance reasons, interacting with external functions like C libraries over FFI, or expressing semantics that safe Rust struggles with (e.g., circular references).

show 1 reply
ViewTrick1002yesterday at 6:32 PM

They are using unsafe since large portions of Bun is interfacing with other unsafe codebases. Together with a "1:1" rewrite from Zig to Rust.

And it's not like Bun when written in Zig has been a beacon of stability either. It has been segfaults all over the place.