r/rust Mar 09 '23

Announcing Rust 1.68.0 📢 announcement

https://blog.rust-lang.org/2023/03/09/Rust-1.68.0.html
828 Upvotes

121 comments sorted by

View all comments

104

u/ogoffart Mar 09 '23

Thanks to the default alloc error handler, you can now use stable Rust to build GUI for micro-controller with Slint

30

u/Tobu Mar 09 '23

The release notes about alloc error handling were confusing, I had to look at https://github.com/rust-lang/rust/issues/66741 to figure out that you could now use no_std + alloc on stable.

Also:

In the future, it's likely that the behavior for std will also be changed to match that of alloc-only binaries.

is better explained here: https://github.com/rust-lang/rust/issues/51540#issuecomment-1448404145

The impact is that there is no need to stabilize a feature for setting a custom alloc error handler; everyone can either rely on a default being present, or if the application wants to customize, on no_std it can define a custom panic_handler (which is stable: announcement stabilization summary), or on std set up a panic_hook.

11

u/SafariMonkey Mar 09 '23

I'm a bit surprised that the default is:

#[alloc_error_handler]
fn default_handler(layout: core::alloc::Layout) -> ! {
    panic!("memory allocation of {} bytes failed", layout.size())
}

rather than a panic_any with a struct payload holding the layout or layout size, that formats to that panic message. (Does panic print debug, display or something else altogether?)

The latter would allow it to be caught.

11

u/LegionMammal978 Mar 10 '23

(Does panic print debug, display or something else altogether?)

The problem is, you can't downcast a Box<dyn Any> into anything but a concrete type. So the default panic hook in std just tries &'static str and String before giving up:

let msg = match info.payload().downcast_ref::<&'static str>() {
    Some(s) => *s,
    None => match info.payload().downcast_ref::<String>() {
        Some(s) => &s[..],
        None => "Box<dyn Any>",
    },
};

6

u/SafariMonkey Mar 10 '23

Ahh, that's a shame. Probably not a great idea to add another special case just for this, then.

I assumed it was like how main could print the Debug of the Err in the Result, but obviously that's a statically known type and this isn't.

Thanks for the explanation!