fix(palette): fix u16 overflow in luma() causing grayscale theme crash#1832
fix(palette): fix u16 overflow in luma() causing grayscale theme crash#1832wdw8276 wants to merge 2 commits into
Conversation
u16::from(r) * 299 overflows u16::MAX (65535) when r >= 220, and u16::from(g) * 587 overflows when g >= 112, causing a panic in debug builds whenever the grayscale theme processes bright colors. Use u32 for intermediate arithmetic to prevent overflow.
There was a problem hiding this comment.
Code Review
This pull request updates the luma function in crates/tui/src/palette.rs to use u32 for intermediate calculations, effectively preventing integer overflows. The reviewer suggested improving the accuracy of the luminance mapping by adding a rounding offset before division and recommended simplifying the expression by removing redundant parentheses.
|
|
||
| fn luma(r: u8, g: u8, b: u8) -> u8 { | ||
| (((u16::from(r) * 299) + (u16::from(g) * 587) + (u16::from(b) * 114)) / 1000) as u8 | ||
| (((u32::from(r) * 299) + (u32::from(g) * 587) + (u32::from(b) * 114)) / 1000) as u8 |
There was a problem hiding this comment.
While the switch to u32 correctly prevents the overflow and subsequent panic, the current implementation uses integer division which truncates the result. For more accurate luminance mapping to the grayscale palette, consider adding a rounding offset (500) before dividing by 1000. Additionally, the inner parentheses around the multiplications are redundant and can be removed to improve readability.
| (((u32::from(r) * 299) + (u32::from(g) * 587) + (u32::from(b) * 114)) / 1000) as u8 | |
| ((u32::from(r) * 299 + u32::from(g) * 587 + u32::from(b) * 114 + 500) / 1000) as u8 |
Apply Gemini review suggestions: - Add +500 before /1000 for proper integer rounding - Remove redundant inner parentheses
|
Thanks for the review! Both suggestions have been applied in the latest commit:
|
Summary
luma()inpalette.rsusesu16for intermediate arithmeticu16::from(r) * 299overflowsu16::MAX(65535) whenr >= 220u16::from(g) * 587overflows wheng >= 112attempt to add with overflow) whenever the grayscale theme processes a bright RGB coloru32for intermediate calculations (result still fits inu8)Reproduction
Switch to the Grayscale theme (
/theme→ select option 4) in a debug build — TUI immediately crashes with a panic logged to~/.deepseek/crashes/.Fix