Skip to content

Commit 82861e3

Browse files
committed
Improve digit duplication
1 parent 8f5adeb commit 82861e3

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

crates/gpui2/src/color.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -127,19 +127,22 @@ impl TryFrom<&'_ str> for Rgba {
127127

128128
let (r, g, b, a) = match hex.len() {
129129
RGB | RGBA => {
130-
// There's likely a better way to handle 3 and 4-value hex codes without
131-
// needing to use `.repeat` and incur additional allocations.
132-
// What we probably want to do is parse the single hex digit and then perform
133-
// bit-shifting to "duplicate" the digit.
134-
let r = u8::from_str_radix(&hex[0..1].repeat(2), 16)?;
135-
let g = u8::from_str_radix(&hex[1..2].repeat(2), 16)?;
136-
let b = u8::from_str_radix(&hex[2..3].repeat(2), 16)?;
130+
let r = u8::from_str_radix(&hex[0..1], 16)?;
131+
let g = u8::from_str_radix(&hex[1..2], 16)?;
132+
let b = u8::from_str_radix(&hex[2..3], 16)?;
137133
let a = if hex.len() == RGBA {
138-
u8::from_str_radix(&hex[3..4].repeat(2), 16)?
134+
u8::from_str_radix(&hex[3..4], 16)?
139135
} else {
140-
0xff
136+
0xf
141137
};
142-
(r, g, b, a)
138+
139+
/// Duplicates a given hex digit.
140+
/// E.g., `0xf` -> `0xff`.
141+
const fn duplicate(value: u8) -> u8 {
142+
value << 4 | value
143+
}
144+
145+
(duplicate(r), duplicate(g), duplicate(b), duplicate(a))
143146
}
144147
RRGGBB | RRGGBBAA => {
145148
let r = u8::from_str_radix(&hex[0..2], 16)?;

0 commit comments

Comments
 (0)