d2-rs-math 0.1.11

Rust port of D2's d2latex package and mathjax-go: LaTeX layout and SVG.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// SPDX-License-Identifier: MIT
// Copyright (c) 2020 Nor Khasyatillah.
// Translated from pinned csscolorparser v0.1.8; see THIRD_PARTY_NOTICES.md.
//
// Arithmetic follows colorparser.go statement by statement: Go's math.Pow,
// math.Sin and math.Cos come from the shared `gomath` port, and every
// product-sum that Go's arm64 compiler fuses (ARM64.rules FMADDD/FMSUBD/
// FNMSUBD) goes through d2-rs-core's go_fmadd/go_fmsub/go_fnmsub, which
// fuse only on aarch64 as Go does (amd64 Go keeps separate roundings).
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 }
}
/// colorparser.go hueToRgb (n1 + ((n2 - n1) * h) fuses on arm64).
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];
    }
    // hslToRgb: n2 = l + s - (l * s); n1 := 2*l - n2.
    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.)),
    ]
}
/// colorparser.go fromLinear: `1.055*math.Pow(x, 1.0/2.4) - 0.055`.
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
    }
}
/// colorparser.go FromOklab (before FromLinearRGB).
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),
        )),
    ]
}
/// `math.Max(0, math.Min(1, n))` in xyzToLinearRgb: NaN stays NaN and
/// Go's Max(0, -0) is +0.
fn clamp_min_max(n: f64) -> f64 {
    if n.is_nan() {
        n
    } else if n >= 1. {
        1.
    } else if n <= 0. {
        0.
    } else {
        n
    }
}
/// colorparser.go labToXyz and xyzToLinearRgb (before FromLinearRGB).
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.;
    // Yn = 1: `Yn * math.Pow(fy, 3)` and `Yn * (l / k)` are exact.
    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())
}

/// Looks up an already-lowercased CSS/SVG named color (the 148-entry W3C
/// table shared by csscolorparser and D2's `lib/color` `namedRgbMap`).
#[must_use]
pub fn css_named_rgb(lowercase_name: &str) -> Option<[u8; 3]> {
    css_named_colors().get(lowercase_name).copied()
}

/// csscolorparser v0.1.8 `Parse`: straight RGBA components in [0, 1].
pub fn parse(raw: &str) -> Option<[f64; 4]> {
    parse_result(raw).ok()
}

/// csscolorparser v0.1.8 `Parse` with its error values: each failing branch
/// returns the same message at the same point as the Go function.
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()),
            // Unknown function names fall through to the bare-hex check on
            // the parenthesized text, as in Go.
            _ => 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}"))
}

/// The component parsing and conversion of one known csscolorparser color
/// function; `None` when a component fails to parse.
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 };
            // remap(t, -1, 1, -limit, limit) = (t+1)*limit - limit.
            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);
            // FromLch/FromOklch: c*math.Cos(h), c*math.Sin(h).
            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,
    })
}
/// Original importer parseSolidColor boundary, returning straight NRGBA bytes.
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())?;
    // Go amd64 converts through a signed 32-bit integer; out-of-range and
    // NaN conversions produce the x86 indefinite integer (whose low byte is 0).
    #[cfg(target_arch = "x86_64")]
    let bytes = color.map(|v| {
        let scaled = v * 255. + 0.5;
        // CVTTSD2SI truncates first, then returns INT_MIN on overflow.
        if scaled > i32::MIN as f64 - 1.0 && scaled < i32::MAX as f64 + 1.0 {
            scaled as i32 as u8
        } else {
            0
        }
    });
    // Go arm64 emits FMA then FCVTZSDW, followed by the low byte.
    #[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}");
            }
        }
    }
}
/// Bit-exact values of pinned csscolorparser v0.1.8 `Parse` built by Go 1.27
/// for linux/arm64 (a probe over the pinned module). Each row differed from
/// the earlier libm/`powi` arithmetic by at least one ulp. amd64 Go does not
/// fuse multiply-adds, so these bits hold for the arm64 build only.
#[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}");
        }
    }
}