use crate::gomath;
use d2_rs_core::{go_fmadd, go_fmsub, go_fnmsub};
use std::{collections::BTreeMap, sync::OnceLock};
fn floor0(n: f64) -> f64 {
if n.is_nan() {
n
} else if n <= 0. {
0.
} else {
n
}
}
fn clamp(n: f64) -> f64 {
if n < 0. {
0.
} else if n > 1. {
1.
} else {
n
}
}
fn float(s: &str) -> Option<f64> {
d2_rs_core::parse_d2_float(s.trim())
}
fn percent(s: &str, denominator: f64) -> Option<(f64, bool)> {
if let Some(n) = s.strip_suffix('%') {
Some((float(n)? / 100., true))
} else {
Some((float(s)? / denominator, false))
}
}
fn angle(s: &str) -> Option<f64> {
for suffix in ["deg", "grad", "rad", "turn"] {
if let Some(n) = s.strip_suffix(suffix) {
let n = float(n)?;
return Some(match suffix {
"grad" => n / 400. * 360.,
"rad" => n / std::f64::consts::PI * 180.,
"turn" => n * 360.,
_ => n,
});
}
}
float(s)
}
fn normalize(n: f64) -> f64 {
let n = n % 360.;
if n < 0. { n + 360. } else { n }
}
fn hue(a: f64, b: f64, h: f64) -> f64 {
let h = (h % 6. + 6.) % 6.;
if h < 1. {
go_fmadd(b - a, h, a)
} else if h < 3. {
b
} else if h < 4. {
go_fmadd(b - a, 4. - h, a)
} else {
a
}
}
fn hsl(h: f64, s: f64, l: f64) -> [f64; 3] {
let h = normalize(h) / 60.;
let s = clamp(s);
let l = clamp(l);
if s == 0. {
return [l; 3];
}
let b = if l < 0.5 {
l * (1. + s)
} else {
go_fmsub(l, s, l + s)
};
let a = go_fnmsub(2., l, b);
[
clamp(hue(a, b, h + 2.)),
clamp(hue(a, b, h)),
clamp(hue(a, b, h - 2.)),
]
}
fn linear(n: f64) -> f64 {
if n >= 0.0031308 {
go_fnmsub(1.055, gomath::pow(n, 1.0 / 2.4), 0.055)
} else {
12.92 * n
}
}
fn oklab(l: f64, a: f64, b: f64) -> [f64; 3] {
let x = gomath::pow(go_fmadd(0.2158037573, b, go_fmadd(0.3963377774, a, l)), 3.);
let y = gomath::pow(go_fmsub(0.0638541728, b, go_fmsub(0.1055613458, a, l)), 3.);
let z = gomath::pow(go_fmsub(1.2914855480, b, go_fmsub(0.0894841775, a, l)), 3.);
[
linear(go_fmadd(
0.2309699292,
z,
go_fmsub(3.3077115913, y, 4.0767416621 * x),
)),
linear(go_fmsub(
0.3413193965,
z,
go_fmadd(2.6097574011, y, -1.2684380046 * x),
)),
linear(go_fmadd(
1.7076147010,
z,
go_fmsub(0.7034186147, y, -0.0041960863 * x),
)),
]
}
fn clamp_min_max(n: f64) -> f64 {
if n.is_nan() {
n
} else if n >= 1. {
1.
} else if n <= 0. {
0.
} else {
n
}
}
fn lab(l: f64, a: f64, b: f64) -> [f64; 3] {
const E: f64 = 216. / 24389.;
const K: f64 = 24389. / 27.;
let fy = (l + 16.) / 116.;
let fx = fy + a / 500.;
let fz = fy - b / 200.;
let y = if l > 8. { gomath::pow(fy, 3.) } else { l / K };
let fx3 = gomath::pow(fx, 3.);
let x = if fx3 > E {
0.95047 * fx3
} else {
0.95047 * go_fnmsub(116., fx, 16.) / K
};
let fz3 = gomath::pow(fz, 3.);
let z = if fz3 > E {
1.08883 * fz3
} else {
1.08883 * go_fnmsub(116., fz, 16.) / K
};
[
linear(clamp_min_max(go_fmsub(
0.498531,
z,
go_fmsub(1.537177, y, 3.2404537 * x),
))),
linear(clamp_min_max(go_fmadd(
0.041556,
z,
go_fmadd(1.876010, y, -0.969266 * x),
))),
linear(clamp_min_max(go_fmadd(
1.057225,
z,
go_fmsub(0.204025, y, 0.055643 * x),
))),
]
}
fn hex(s: &str) -> Option<[f64; 4]> {
let bytes = s.as_bytes();
let mut result = [0., 0., 0., 1.];
if !matches!(bytes.len(), 3 | 4 | 6 | 8) {
return None;
}
let short = bytes.len() < 5;
let digit = |b: u8| match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
_ => None,
};
for index in 0..if short { bytes.len() } else { bytes.len() / 2 } {
result[index] = f64::from(if short {
digit(bytes[index])? * 17
} else {
digit(bytes[index * 2])? * 16 + digit(bytes[index * 2 + 1])?
}) / 255.;
}
Some(result)
}
fn css_named_colors() -> &'static BTreeMap<String, [u8; 3]> {
static NAMES: OnceLock<BTreeMap<String, [u8; 3]>> = OnceLock::new();
NAMES.get_or_init(|| serde_json::from_str(include_str!("css_named_colors.json")).unwrap())
}
#[must_use]
pub fn css_named_rgb(lowercase_name: &str) -> Option<[u8; 3]> {
css_named_colors().get(lowercase_name).copied()
}
pub fn parse(raw: &str) -> Option<[f64; 4]> {
parse_result(raw).ok()
}
pub fn parse_result(raw: &str) -> Result<[f64; 4], String> {
let names = css_named_colors();
let lowered = String::from_utf8(d2_rs_core::ir::go_lowercase(raw.as_bytes())).unwrap();
let mut s = lowered.trim();
if s == "transparent" {
return Ok([0.; 4]);
}
if let Some(rgb) = names.get(s) {
return Ok([
f64::from(rgb[0]) / 255.,
f64::from(rgb[1]) / 255.,
f64::from(rgb[2]) / 255.,
1.,
]);
}
if let Some(digits) = s.strip_prefix('#') {
return hex(digits).ok_or_else(|| format!("Invalid hex color, {raw}"));
}
if let Some(open) = s.find('(').filter(|_| s.ends_with(')')) {
let name = s[..open].trim();
let inner = &s[open + 1..s.len() - 1];
let fields: Vec<_> = inner
.split([',', '/', ' '])
.filter(|p| !p.is_empty())
.collect();
if !matches!(fields.len(), 3 | 4) {
return Err("Invalid format".into());
}
let alpha = if fields.len() == 4 {
clamp(
percent(fields[3], 1.)
.ok_or_else(|| "Invalid format".to_owned())?
.0,
)
} else {
1.
};
let error = match name {
"rgb" | "rgba" | "hsl" | "hsla" | "oklab" | "oklch" => {
Some(format!("Wrong {name}() components, {raw}"))
}
"hwb" | "hwba" => Some(format!("Wrong hwb() components, {raw}")),
"hsv" | "hsva" => Some(format!("Wrong hsv() components, {raw}")),
"lab" => Some("Invalid lab()".to_owned()),
"lch" => Some("Invalid lch()".to_owned()),
_ => None,
};
if let Some(error) = error {
let [r, g, b] = function_rgb(name, &fields).ok_or(error)?;
return Ok([r, g, b, alpha]);
}
s = inner;
}
hex(s).ok_or_else(|| format!("Invalid color format, {raw}"))
}
fn function_rgb(name: &str, fields: &[&str]) -> Option<[f64; 3]> {
Some(match name {
"rgb" | "rgba" => [
clamp(percent(fields[0], 255.)?.0),
clamp(percent(fields[1], 255.)?.0),
clamp(percent(fields[2], 255.)?.0),
],
"hsl" | "hsla" => hsl(
angle(fields[0])?,
percent(fields[1], 1.)?.0,
percent(fields[2], 1.)?.0,
),
"hwb" | "hwba" => {
let h = angle(fields[0])?;
let w = clamp(percent(fields[1], 1.)?.0);
let b = clamp(percent(fields[2], 1.)?.0);
if w + b >= 1. {
[w / (w + b); 3]
} else {
let mut rgb = hsl(h, 1., 0.5);
for n in &mut rgb {
*n = go_fmadd(*n, 1. - w - b, w);
}
rgb
}
}
"hsv" | "hsva" => {
let h = angle(fields[0])?;
let s = clamp(percent(fields[1], 1.)?.0);
let v = clamp(percent(fields[2], 1.)?.0);
let l = (2. - s) * v / 2.;
let sat = if l == 0. {
s
} else if l == 1. {
0.
} else if l < 0.5 {
s * v / (l * 2.)
} else {
s * v / go_fmsub(l, 2., 2.)
};
hsl(h, sat, l)
}
"oklab" | "lab" => {
let (mut l, lp) = percent(fields[0], 1.)?;
let (mut a, ap) = percent(fields[1], 1.)?;
let (mut b, bp) = percent(fields[2], 1.)?;
let limit = if name == "lab" { 125. } else { 0.4 };
if ap {
a = go_fmadd(a + 1., limit, -limit);
}
if bp {
b = go_fmadd(b + 1., limit, -limit);
}
if name == "lab" && lp {
l *= 100.;
}
if name == "lab" {
lab(floor0(l), a, b)
} else {
oklab(floor0(l), a, b)
}
}
"oklch" | "lch" => {
let (mut l, lp) = percent(fields[0], 1.)?;
let (mut c, cp) = percent(fields[1], 1.)?;
let h = angle(fields[2])? * std::f64::consts::PI / 180.;
if cp {
c *= if name == "lch" { 150. } else { 0.4 };
}
if name == "lch" && lp {
l *= 100.;
}
let c = floor0(c);
let (cs, sn) = (gomath::cos(h), gomath::sin(h));
if name == "lch" {
lab(floor0(l), c * cs, c * sn)
} else {
oklab(floor0(l), c * cs, c * sn)
}
}
_ => return None,
})
}
pub fn solid(value: &str) -> Result<[u8; 4], String> {
if value.len() > 4096 {
return Err("solid color is too long".into());
}
let color = parse(value.trim()).ok_or_else(|| "unsupported solid color".to_owned())?;
#[cfg(target_arch = "x86_64")]
let bytes = color.map(|v| {
let scaled = v * 255. + 0.5;
if scaled > i32::MIN as f64 - 1.0 && scaled < i32::MAX as f64 + 1.0 {
scaled as i32 as u8
} else {
0
}
});
#[cfg(target_arch = "aarch64")]
let bytes = color.map(|v| v.mul_add(255., 0.5) as i32 as u8);
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
let bytes = color.map(|v| (v * 255. + 0.5) as i32 as u8);
Ok(bytes)
}
#[cfg(test)]
mod parse_errors {
use super::parse_result;
#[test]
fn each_failing_branch_returns_the_go_parse_error() {
for (input, error) in [
("", "Invalid color format, "),
("nosuch", "Invalid color format, nosuch"),
("#", "Invalid hex color, #"),
("#12G", "Invalid hex color, #12G"),
("#12345", "Invalid hex color, #12345"),
("rgb(1,2)", "Invalid format"),
("rgb(1,2,3,4,5)", "Invalid format"),
("rgb(1,2,3,x)", "Invalid format"),
("foo(1,2,3,x)", "Invalid format"),
("RGBA(1, 2, x)", "Wrong rgba() components, RGBA(1, 2, x)"),
("hsl(1x,2,3)", "Wrong hsl() components, hsl(1x,2,3)"),
("hwba(1,2,x)", "Wrong hwb() components, hwba(1,2,x)"),
("hsv(x,2,3)", "Wrong hsv() components, hsv(x,2,3)"),
("oklab(x,1,1)", "Wrong oklab() components, oklab(x,1,1)"),
("oklch(1,1,1px)", "Wrong oklch() components, oklch(1,1,1px)"),
("lab(x,1,1)", "Invalid lab()"),
("lch(1,1,x)", "Invalid lch()"),
("foo(1,2,3)", "Invalid color format, foo(1,2,3)"),
("rgb(1,2,3", "Invalid color format, rgb(1,2,3"),
] {
assert_eq!(parse_result(input), Err(error.to_owned()), "{input:?}");
}
for input in [" ABC ", "transparent", "Red", "rgb(1 2 3 / 50%)", "fff8"] {
assert!(parse_result(input).is_ok(), "{input:?}");
}
}
}
#[cfg(all(test, feature = "oracle-fixtures"))]
mod tests {
use super::*;
#[cfg(feature = "oracle-fixtures")]
#[test]
fn original_solid_color_boundary() {
let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
"tests/fixtures/svg-color-v090.json"
))
.unwrap();
for row in rows.as_array().unwrap() {
let result = solid(row["value"].as_str().unwrap());
assert_eq!(
result.as_ref().err().map(String::as_str).unwrap_or(""),
row["error"].as_str().unwrap(),
"{row}"
);
if let Ok(color) = result {
assert_eq!(serde_json::to_value(color).unwrap(), row["rgba"], "{row}");
}
}
}
}
#[cfg(all(test, target_arch = "aarch64"))]
mod go_arm64_values {
use super::parse_result;
#[test]
fn lab_lch_oklab_oklch_match_go_bits() {
for (input, bits) in [
(
"lab(0 -200 12.5%)",
[0, 0x3fceb02014f66e6f, 0, 0x3ff0000000000000],
),
(
"lab(1,2,3)",
[
0x3fa86ff1ab5a6631,
0x3f7cee10ab1dbc70,
0,
0x3ff0000000000000,
],
),
(
"lch(0 150 270)",
[
0,
0x3fc901694f1a65b3,
0x3fed18b26a94193f,
0x3ff0000000000000,
],
),
(
"lch(5 50% 180)",
[
0,
0x3fc525a09e28e931,
0x3facc5ae829daf61,
0x3ff0000000000000,
],
),
(
"oklab(0 0.1 0.25)",
[
0xbfb0a78fb785c027,
0x3fbbc23ffdd13d9d,
0xbfe9ca18ac83ace6,
0x3ff0000000000000,
],
),
(
"oklab(1e2,2,3)",
[
0x40766d56966fa138,
0x40746eb3fa73bdbc,
0x407315abf20b0969,
0x3ff0000000000000,
],
),
(
"oklch(0.1 100% 1e3)",
[
0x3fce332ed46d3ca7,
0xbfed24c9750a555f,
0x3fe49be8c369ae42,
0x3ff0000000000000,
],
),
(
"oklch(1e2,2,3)",
[
0x4075daa52ab092e2,
0x4074738efc9f7a47,
0x4074bf42c486d44d,
0x3ff0000000000000,
],
),
] {
let color = parse_result(input).unwrap();
assert_eq!(color.map(f64::to_bits), bits, "{input}");
}
}
}