pub fn hex_bytes_to_u32(buf: &[u8]) -> Result<u32, ()> {
fn hex_to_int(c: u8) -> Result<u32, ()> {
if (48..=57).contains(&c) {
return Ok((c - 48) as u32);
}
if (65..=70).contains(&c) {
return Ok((c - 65 + 10) as u32);
}
if (97..=102).contains(&c) {
return Ok((c - 97 + 10) as u32);
}
Err(())
}
match buf.len() {
1 => {
let val = hex_to_int(buf[0]) ?;
return Ok((val << 28) | (val << 24) | (val << 20) | (val << 16) | (val << 12) | (val << 8) | 0xff);
}
2 => { let val = (hex_to_int(buf[0]) ? << 4) + hex_to_int(buf[1]) ?;
return Ok((val << 24) | (val << 16) | (val << 8) | 0xff)
},
3 => {
let r = hex_to_int(buf[0]) ?;
let g = hex_to_int(buf[1]) ?;
let b = hex_to_int(buf[2]) ?;
return Ok((r << 28) | (r << 24) | (g << 20) | (g << 16) | (b << 12) | (b << 8) | 0xff);
}
4 => {
let r = hex_to_int(buf[0]) ?;
let g = hex_to_int(buf[1]) ?;
let b = hex_to_int(buf[2]) ?;
let a = hex_to_int(buf[3]) ?;
return Ok((r << 28) | (r << 24) | (g << 20) | (g << 16) | (b << 12) | (b << 8) | (a << 4) | a);
}
6 => {
let r = (hex_to_int(buf[0]) ? << 4) + hex_to_int(buf[1]) ?;
let g = (hex_to_int(buf[2]) ? << 4) + hex_to_int(buf[3]) ?;
let b = (hex_to_int(buf[4]) ? << 4) + hex_to_int(buf[5]) ?;
return Ok((r << 24) | (g << 16) | (b << 8) | 0xff)
}
8 => {
let r = (hex_to_int(buf[0]) ? << 4) + hex_to_int(buf[1]) ?;
let g = (hex_to_int(buf[2]) ? << 4) + hex_to_int(buf[3]) ?;
let b = (hex_to_int(buf[4]) ? << 4) + hex_to_int(buf[5]) ?;
let a = (hex_to_int(buf[6]) ? << 4) + hex_to_int(buf[7]) ?;
return Ok((r << 24) | (g << 16) | (b << 8) | a)
}
_ => (),
}
Err(())
}