emilk / egui

egui: an easy-to-use immediate mode GUI in Rust that runs on both web and native
https://www.egui.rs/
Apache License 2.0
22.61k stars 1.62k forks source link

hex_color!() macro is not const #5160

Open Ora9 opened 2 months ago

Ora9 commented 2 months ago

It would be nice if hex_color!() macro would be const to be used in constant declaration and to define colors at compile time

Btw, the doc says that it's the case on Color32::from_hex method : « To parse hex colors at compile-time (e.g. for use in const contexts) use the macro crate::hex_color! instead. »

But when trying on a test project with the latest egui git master, i get this error :

error[E0015]: cannot call non-const fn `Color32::from_rgba_unmultiplied` in constants
 --> src/main.rs:1:30
  |
1 | const TEST: egui::Color32 = egui::hex_color!("#ff0202");
  |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants
  = note: this error originates in the macro `egui::hex_color` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0015`.

This is related to #1596, where this comment was saying that it wasn't possible at the time to make the macro const due to floating-point conversions. And that this could be soon fixed But this was in 2022, and looking at the code (here and here there are some functions that are not const yet (linear_f32_from_gamma_u8 and friends) I'm quite new to rust, but is it still not possible to make the macro const ? That would be really handy

YgorSouza commented 2 months ago

Const floating-point arithmetic is going to be stabilized in Rust 1.82, which comes out in 3 weeks. But egui is still targeting 1.76 for now, and likely won't switch immediately. When it does switch, I suppose a const version of from_rgba_unmultiplied could be written to make the macro const. The current implementation cannot be made const because it uses a lookup table to improve performance, and that can only be initialized at runtime.

Until then, maybe the documentation could be updated to reflect the fact that the macro is not actually const, but only has the advantage of generating a compilation error if the string literal is invalid.