Improve Color::hex performance (#6940)

# Objective

Improve `Color::hex` performance

#### Bench

```bash
running 2 tests
test bench_color_hex_after  ... bench:           4 ns/iter (+/- 0)
test bench_color_hex_before ... bench:          14 ns/iter (+/- 0)
```

## Solution

Use `const fn` decode hex value.

---

## Changelog

Rename

```rust
HexColorError::Hex(FromHexError) -> HexColorError::Char(char)
```
This commit is contained in:
wyhaya 2023-01-17 13:26:43 +00:00
parent 16ff05acdf
commit 1cc663f290
2 changed files with 70 additions and 76 deletions

View file

@ -62,7 +62,6 @@ thread_local = "1.1"
thiserror = "1.0" thiserror = "1.0"
futures-lite = "1.4.0" futures-lite = "1.4.0"
anyhow = "1.0" anyhow = "1.0"
hex = "0.4.2"
hexasphere = "8.0" hexasphere = "8.0"
parking_lot = "0.12.1" parking_lot = "0.12.1"
regex = "1.5" regex = "1.5"

View file

@ -260,37 +260,29 @@ impl Color {
let hex = hex.as_ref(); let hex = hex.as_ref();
let hex = hex.strip_prefix('#').unwrap_or(hex); let hex = hex.strip_prefix('#').unwrap_or(hex);
match *hex.as_bytes() {
// RGB // RGB
if hex.len() == 3 { [r, g, b] => {
let mut data = [0; 6]; let [r, g, b, ..] = decode_hex([r, r, g, g, b, b])?;
for (i, ch) in hex.chars().enumerate() { Ok(Color::rgb_u8(r, g, b))
data[i * 2] = ch as u8;
data[i * 2 + 1] = ch as u8;
} }
return decode_rgb(&data);
}
// RGBA // RGBA
if hex.len() == 4 { [r, g, b, a] => {
let mut data = [0; 8]; let [r, g, b, a, ..] = decode_hex([r, r, g, g, b, b, a, a])?;
for (i, ch) in hex.chars().enumerate() { Ok(Color::rgba_u8(r, g, b, a))
data[i * 2] = ch as u8;
data[i * 2 + 1] = ch as u8;
} }
return decode_rgba(&data);
}
// RRGGBB // RRGGBB
if hex.len() == 6 { [r1, r2, g1, g2, b1, b2] => {
return decode_rgb(hex.as_bytes()); let [r, g, b, ..] = decode_hex([r1, r2, g1, g2, b1, b2])?;
Ok(Color::rgb_u8(r, g, b))
} }
// RRGGBBAA // RRGGBBAA
if hex.len() == 8 { [r1, r2, g1, g2, b1, b2, a1, a2] => {
return decode_rgba(hex.as_bytes()); let [r, g, b, a, ..] = decode_hex([r1, r2, g1, g2, b1, b2, a1, a2])?;
Ok(Color::rgba_u8(r, g, b, a))
}
_ => Err(HexColorError::Length),
} }
Err(HexColorError::Length)
} }
/// New `Color` from sRGB colorspace. /// New `Color` from sRGB colorspace.
@ -1337,38 +1329,49 @@ impl encase::private::CreateFrom for Color {
impl encase::ShaderSize for Color {} impl encase::ShaderSize for Color {}
#[derive(Debug, Error)] #[derive(Debug, Error, PartialEq, Eq)]
pub enum HexColorError { pub enum HexColorError {
#[error("Unexpected length of hex string")] #[error("Unexpected length of hex string")]
Length, Length,
#[error("Error parsing hex value")] #[error("Invalid hex char")]
Hex(#[from] hex::FromHexError), Char(char),
} }
fn decode_rgb(data: &[u8]) -> Result<Color, HexColorError> { /// Converts hex bytes to an array of RGB\[A\] components
let mut buf = [0; 3]; ///
match hex::decode_to_slice(data, &mut buf) { /// # Example
Ok(_) => { /// For RGB: *b"ffffff" -> [255, 255, 255, ..]
let r = buf[0] as f32 / 255.0; /// For RGBA: *b"E2E2E2FF" -> [226, 226, 226, 255, ..]
let g = buf[1] as f32 / 255.0; const fn decode_hex<const N: usize>(mut bytes: [u8; N]) -> Result<[u8; N], HexColorError> {
let b = buf[2] as f32 / 255.0; let mut i = 0;
Ok(Color::rgb(r, g, b)) while i < bytes.len() {
// Convert single hex digit to u8
let val = match hex_value(bytes[i]) {
Ok(val) => val,
Err(byte) => return Err(HexColorError::Char(byte as char)),
};
bytes[i] = val;
i += 1;
} }
Err(err) => Err(HexColorError::Hex(err)), // Modify the original bytes to give an `N / 2` length result
i = 0;
while i < bytes.len() / 2 {
// Convert pairs of u8 to R/G/B/A
// e.g `ff` -> [102, 102] -> [15, 15] = 255
bytes[i] = bytes[i * 2] * 16 + bytes[i * 2 + 1];
i += 1;
} }
Ok(bytes)
} }
fn decode_rgba(data: &[u8]) -> Result<Color, HexColorError> { /// Parse a single hex digit (a-f/A-F/0-9) as a `u8`
let mut buf = [0; 4]; const fn hex_value(b: u8) -> Result<u8, u8> {
match hex::decode_to_slice(data, &mut buf) { match b {
Ok(_) => { b'0'..=b'9' => Ok(b - b'0'),
let r = buf[0] as f32 / 255.0; b'A'..=b'F' => Ok(b - b'A' + 10),
let g = buf[1] as f32 / 255.0; b'a'..=b'f' => Ok(b - b'a' + 10),
let b = buf[2] as f32 / 255.0; // Wrong hex digit
let a = buf[3] as f32 / 255.0; _ => Err(b),
Ok(Color::rgba(r, g, b, a))
}
Err(err) => Err(HexColorError::Hex(err)),
} }
} }
@ -1378,29 +1381,21 @@ mod tests {
#[test] #[test]
fn hex_color() { fn hex_color() {
assert_eq!(Color::hex("FFF").unwrap(), Color::rgb(1.0, 1.0, 1.0)); assert_eq!(Color::hex("FFF"), Ok(Color::WHITE));
assert_eq!(Color::hex("000").unwrap(), Color::rgb(0.0, 0.0, 0.0)); assert_eq!(Color::hex("FFFF"), Ok(Color::WHITE));
assert!(Color::hex("---").is_err()); assert_eq!(Color::hex("FFFFFF"), Ok(Color::WHITE));
assert_eq!(Color::hex("FFFFFFFF"), Ok(Color::WHITE));
assert_eq!(Color::hex("FFFF").unwrap(), Color::rgba(1.0, 1.0, 1.0, 1.0)); assert_eq!(Color::hex("000"), Ok(Color::BLACK));
assert_eq!(Color::hex("0000").unwrap(), Color::rgba(0.0, 0.0, 0.0, 0.0)); assert_eq!(Color::hex("000F"), Ok(Color::BLACK));
assert!(Color::hex("----").is_err()); assert_eq!(Color::hex("000000"), Ok(Color::BLACK));
assert_eq!(Color::hex("000000FF"), Ok(Color::BLACK));
assert_eq!(Color::hex("FFFFFF").unwrap(), Color::rgb(1.0, 1.0, 1.0)); assert_eq!(Color::hex("03a9f4"), Ok(Color::rgb_u8(3, 169, 244)));
assert_eq!(Color::hex("000000").unwrap(), Color::rgb(0.0, 0.0, 0.0)); assert_eq!(Color::hex("yy"), Err(HexColorError::Length));
assert!(Color::hex("------").is_err()); assert_eq!(Color::hex("yyy"), Err(HexColorError::Char('y')));
assert_eq!(Color::hex("#f2a"), Ok(Color::rgb_u8(255, 34, 170)));
assert_eq!( assert_eq!(Color::hex("#e23030"), Ok(Color::rgb_u8(226, 48, 48)));
Color::hex("FFFFFFFF").unwrap(), assert_eq!(Color::hex("#ff"), Err(HexColorError::Length));
Color::rgba(1.0, 1.0, 1.0, 1.0) assert_eq!(Color::hex("##fff"), Err(HexColorError::Char('#')));
);
assert_eq!(
Color::hex("00000000").unwrap(),
Color::rgba(0.0, 0.0, 0.0, 0.0)
);
assert!(Color::hex("--------").is_err());
assert!(Color::hex("1234567890").is_err());
} }
#[test] #[test]