-
-
Save hadronized/6296800987f05b91430a105a233a54f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn from_hex(hex: impl AsRef<str>) -> Option<Color> { | |
let hex = hex.as_ref(); | |
let bytes = hex.as_bytes(); | |
let (mut r, mut g, mut b); | |
if hex.len() == 4 && bytes[0] == b'#' { | |
// triplet form (#rgb) | |
let mut h = u16::from_str_radix(&hex[1..], 16).ok()?; | |
b = (h & 0xf) as _; | |
b += b << 4; | |
h >>= 4; | |
g = (h & 0xf) as _; | |
g += g << 4; | |
h >>= 4; | |
r = (h & 0xf) as _; | |
r += r << 4; | |
} else if hex.len() == 7 && bytes[0] == b'#' { | |
// #rrggbb form | |
let mut h = u32::from_str_radix(&hex[1..], 16).ok()?; | |
b = (h & 0xff) as _; | |
h >>= 8; | |
g = (h & 0xff) as _; | |
h >>= 8; | |
r = (h & 0xff) as _; | |
} else { | |
return None; | |
} | |
Some(Color(Col::TrueColor { r, g, b })) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment