Reject non-hex characters such as '+' in Rgba::from_hex

Found while testing crates/color/src/lib.rs:41

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NetterSilver
2026-10-19 05:34:48 +00:00
co-authored by Claude Haiku 5.5
parent 010941ec60
commit c90ea7d9ae
+9 -1
View File
@@ -35,7 +35,7 @@ impl Rgba {
/// `RRGGBB` or `#RRGGBB` (also `RRGGBBAA`).
pub fn from_hex(s: &str) -> Option<Self> {
let s = s.trim().trim_start_matches('#');
if !s.is_ascii() {
if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok());
@@ -519,6 +519,14 @@ pub fn preset(name: &str) -> Option<Rgba> {
mod tests {
use super::*;
#[test]
fn from_hex_rejects_signs() {
assert_eq!(Rgba::from_hex("+12345"), None);
assert_eq!(Rgba::from_hex("#+1+2+3"), None);
assert_eq!(Rgba::from_hex("+1+2+3+4"), None);
assert_eq!(Rgba::from_hex("+12"), None);
}
#[test]
fn hex_roundtrip() {
assert_eq!(Rgba::from_hex("#156082"), Some(Rgba::rgb(0x15, 0x60, 0x82)));