colorthief-dataset 0.1.0

Static xkcd color-hierarchy table with pre-computed LAB used by `colorthief` for human-vocabulary color naming.
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
526
527
//! Static xkcd color-hierarchy table for human-vocabulary color naming.
//!
//! Each entry exposes five hierarchical names (xkcd → design → common →
//! family → kind), plus the entry's RGB and a pre-computed CIE LAB triple
//! used by [`Color::nearest_to`] for nearest-neighbor lookup.
//!
//! # Why LAB is pre-computed at codegen time
//!
//! The sRGB → LAB pipeline involves a power function (gamma decode) and a
//! cube root (LAB f-function), both transcendental. Computing those for
//! all 950 entries on every query would dwarf the actual nearest-neighbor
//! scan. Pre-computing at `cargo xtask codegen` time pushes that cost out
//! of the hot path; the runtime cost of `nearest_to` is one sRGB→LAB on
//! the query plus 950 squared-distance comparisons (no `sqrt` — squared
//! distance preserves ordering).
//!
//! # Distance metric
//!
//! Choose via [`Algorithm`]; the default ([`Algorithm::Ciede2000Exact`])
//! is the modern perceptual gold-standard. Faster alternatives are
//! available via [`Color::nearest_to`] (Delta E 76, ~470 ns NEON) and
//! [`Color::nearest_to_cie94`] (CIE94, ~620 ns NEON) for throughput-
//! sensitive callers willing to trade borderline accuracy for speed.
//!
//! # Attribution
//!
//! The color hierarchy is sourced from Stitch Fix's `colornamer` (Apache
//! 2.0); see `THIRD_PARTY_NOTICES.md` for the full upstream attribution.

#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
#![deny(missing_docs)]
// `unsafe_code` is `deny`-not-`forbid` because the per-arch NEON kernel in
// `nearest::aarch64_neon` needs `unsafe` to call `core::arch::aarch64`
// intrinsics (the NEON entry function is `#[target_feature(enable = "neon")]`
// and therefore `unsafe fn`). That module carries a local
// `#[allow(unsafe_code)]` and is the ONLY place unsafe code is allowed.
#![deny(unsafe_code)]

mod generated;
mod nearest;

pub use generated::{COLORS, Family, Kind};
// `Algorithm` is defined below alongside `Color`; re-exported to
// crate root for ergonomics — `colorthief_dataset::Algorithm` is
// where users expect to find it.

/// **Not a stable API.**
///
/// Hidden helpers used by `colorthief-dataset/benches/nearest.rs` to
/// compare backends head-to-head. Calling these directly bypasses the
/// dispatcher in [`Color::nearest_to`] — production code should use
/// the public method.
#[doc(hidden)]
pub mod __bench {
  pub use crate::nearest::{
    cie94::{delta_e_94_sq, nearest_idx as cie94_nearest_idx},
    ciede2000::{
      delta_e_2000_sq, nearest_idx as ciede2000_nearest_idx,
      nearest_idx_prefiltered as ciede2000_prefiltered_nearest_idx,
    },
    scalar::{delta_e_76_sq, nearest_idx as scalar_nearest_idx},
  };

  #[cfg(feature = "lut")]
  pub use crate::nearest::ciede2000_lut::nearest_idx as ciede2000_lut_nearest_idx;

  // `target_feature = "neon"` (not just `target_arch = "aarch64"`):
  // see `nearest::aarch64_neon` mod decl for the
  // `aarch64-unknown-none-softfloat` rationale.
  #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
  pub use crate::nearest::cie94_aarch64_neon::nearest_idx as cie94_aarch64_neon_nearest_idx;
  #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
  pub use crate::nearest::cie94_wasm_simd128::nearest_idx as cie94_wasm_simd128_nearest_idx;
  #[cfg(target_arch = "x86_64")]
  pub use crate::nearest::cie94_x86_avx2::nearest_idx as cie94_x86_avx2_nearest_idx;
  #[cfg(target_arch = "x86_64")]
  pub use crate::nearest::cie94_x86_avx512::nearest_idx as cie94_x86_avx512_nearest_idx;
  #[cfg(target_arch = "x86_64")]
  pub use crate::nearest::cie94_x86_sse41::nearest_idx as cie94_x86_sse41_nearest_idx;

  #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
  pub use crate::nearest::aarch64_neon::nearest_idx as aarch64_neon_nearest_idx;

  // x86 backends are `unsafe fn` (the `#[target_feature]` attribute
  // enforces the safety boundary). Re-export them as-is — the bench
  // wraps the `unsafe { ... }` after a runtime feature check.
  #[cfg(target_arch = "x86_64")]
  pub use crate::nearest::x86_avx2::nearest_idx as x86_avx2_nearest_idx;
  #[cfg(target_arch = "x86_64")]
  pub use crate::nearest::x86_avx512::nearest_idx as x86_avx512_nearest_idx;
  #[cfg(target_arch = "x86_64")]
  pub use crate::nearest::x86_sse41::nearest_idx as x86_sse41_nearest_idx;

  #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
  pub use crate::nearest::wasm_simd128::nearest_idx as wasm_simd128_nearest_idx;

  /// Public re-export of the crate-private `rgb_to_lab` so benches can
  /// pre-convert RGB queries without duplicating the math.
  pub fn rgb_to_lab(rgb: [u8; 3]) -> [f32; 3] {
    super::rgb_to_lab(rgb)
  }
}

/// One named entry in the xkcd color hierarchy.
///
/// Carries every column from the upstream `color_hierarchy.csv`:
/// xkcd / design / common name, hex, and RGB triples for each level,
/// plus the family / kind / neutrality classification. The xkcd LAB
/// triple is pre-computed at codegen time for nearest-neighbor lookup
/// in [`Self::nearest_to`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Color {
  pub(crate) name: &'static str,
  pub(crate) hex: &'static str,
  pub(crate) rgb: [u8; 3],
  pub(crate) lab: [f32; 3],
  pub(crate) design_name: &'static str,
  pub(crate) design_hex: &'static str,
  pub(crate) design_rgb: [u8; 3],
  pub(crate) common_name: &'static str,
  pub(crate) common_hex: &'static str,
  pub(crate) common_rgb: [u8; 3],
  pub(crate) family: Family,
  pub(crate) kind: Kind,
  pub(crate) is_neutral: bool,
}

impl Color {
  /// xkcd-survey name (~950 unique values, e.g. `"burnt orange"`,
  /// `"vermilion"`).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn name(&self) -> &'static str {
    self.name
  }

  /// xkcd hex string, e.g. `"#bd6c48"`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn hex(&self) -> &'static str {
    self.hex
  }

  /// xkcd RGB triple, e.g. `[189, 108, 72]`. The exact 8-bit value the
  /// xkcd survey reports for this name.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn rgb(&self) -> [u8; 3] {
    self.rgb
  }

  /// Pre-computed CIE LAB (D65 illuminant, 2° observer) for [`Self::rgb`].
  /// Used internally by [`Self::nearest_to`]; exposed publicly so callers
  /// can implement their own distance metric (e.g. CIEDE2000) on top of
  /// the same cached values.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn lab(&self) -> [f32; 3] {
    self.lab
  }

  /// Coarser design-palette name (~250 unique, e.g. `"russet brown"`).
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn design_name(&self) -> &'static str {
    self.design_name
  }

  /// Hex string for the design-palette anchor color.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn design_hex(&self) -> &'static str {
    self.design_hex
  }

  /// RGB triple for the design-palette anchor color (the canonical
  /// 8-bit representation of [`Self::design_name`]). Differs from
  /// [`Self::rgb`] when the xkcd entry sits at the edge of its
  /// design-palette bucket.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn design_rgb(&self) -> [u8; 3] {
    self.design_rgb
  }

  /// Coarser still common name (~120 unique, e.g. `"sienna"`). The
  /// search-friendly default for indexing pipelines.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn common_name(&self) -> &'static str {
    self.common_name
  }

  /// Hex string for the common-name anchor color.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn common_hex(&self) -> &'static str {
    self.common_hex
  }

  /// RGB triple for the common-name anchor color.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn common_rgb(&self) -> [u8; 3] {
    self.common_rgb
  }

  /// Color family classification (26 values, e.g. [`Family::Yellow`],
  /// [`Family::BlueGreen`], [`Family::Neutral`]). Call
  /// [`Family::as_str`] for the original CSV string.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn family(&self) -> Family {
    self.family
  }

  /// Color kind / texture classification (11 values, e.g.
  /// [`Kind::NeonColor`], [`Kind::PainterlyNeutral`]). Call
  /// [`Kind::as_str`] for the original CSV string.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn kind(&self) -> Kind {
    self.kind
  }

  /// `true` if the entry is classified as a neutral (vs a chromatic
  /// color). Drives the `color_or_neutral` axis in the original Stitch
  /// Fix taxonomy.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn is_neutral(&self) -> bool {
    self.is_neutral
  }

  /// Every entry in the dataset, in CSV (alphabetical-by-`name`) order.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn all() -> &'static [&'static Color] {
    COLORS
  }

  /// Find the entry whose pre-computed LAB is closest to the given query
  /// RGB by **Delta E 76** (squared Euclidean LAB).
  ///
  /// Always returns an entry — `COLORS` is non-empty and verified at
  /// codegen time. The scan dispatches to a per-arch SIMD backend
  /// (NEON / AVX2 / SSE4.1 / WASM SIMD128) on every target that has
  /// one; other targets fall through to the scalar reference. Every
  /// backend is bit-identical — see [`crate::nearest`] for the
  /// dispatch contract and parity tests.
  ///
  /// # When to use this method
  ///
  /// Delta E 76 is the *fast* metric: against this crate's well-
  /// clustered 949-entry xkcd palette it picks the same named entry
  /// as CIEDE2000 in the overwhelming majority of cases, at ~150×
  /// the throughput of [`Algorithm::Ciede2000Exact`] (the default
  /// returned by [`Algorithm::default`]). Reach for it when you've
  /// measured the slower default bottlenecking real workloads and
  /// can tolerate borderline misnamings near the gray / yellow
  /// boundary.
  pub fn nearest_to(rgb: [u8; 3]) -> &'static Color {
    crate::nearest::nearest(rgb_to_lab(rgb))
  }

  /// Find the entry whose pre-computed LAB is closest to the given
  /// query RGB by **CIEDE2000** — the modern perceptual gold-standard
  /// colour-difference formula.
  ///
  /// CIEDE2000 corrects Delta E 76's known biases (over-weighting
  /// yellows, under-weighting blues, hue-rotation in the saturated
  /// blue region) at the cost of `atan2` / `sin` / `cos` / `exp` per
  /// pair plus branchy hue-wraparound logic.
  ///
  /// # Implementation
  ///
  /// - With `feature = "lut"` (the default): O(1) cell lookup → small
  ///   candidate scan via the pre-computed candidate-set LUT
  ///   ([`crate::nearest::ciede2000_lut`]). Provably exact at u8 RGB
  ///   resolution; ~few-hundred-ns/query.
  /// - Without `feature = "lut"`: full-scan reference over all 949
  ///   palette entries (~71 µs/query). Same correctness guarantee,
  ///   slower.
  ///
  /// Both modes are scalar — CIEDE2000's transcendentals don't
  /// vectorise usefully (see [`crate::nearest::ciede2000`]).
  pub fn nearest_to_ciede2000(rgb: [u8; 3]) -> &'static Color {
    crate::nearest::nearest_ciede2000(rgb)
  }

  /// Strict CIEDE2000 nearest-neighbor. Behaviorally equivalent to
  /// [`Self::nearest_to_ciede2000`] — both are exact under both
  /// feature configurations (the LUT path is provably exact, the
  /// no-LUT path is full-scan). Retained as a distinct entry point
  /// for API stability; consumers picking between the two by name
  /// should prefer [`Self::nearest_to_ciede2000`].
  pub fn nearest_to_ciede2000_exact(rgb: [u8; 3]) -> &'static Color {
    crate::nearest::nearest_ciede2000(rgb)
  }

  /// Find the entry whose pre-computed LAB is closest to the given
  /// query RGB by **CIE94** (Delta E 94, graphic-arts weighting).
  ///
  /// CIE94 sits between Delta E 76 and CIEDE2000 in both perceptual
  /// accuracy and arithmetic cost. It uses no transcendentals beyond
  /// `sqrt`, so unlike CIEDE2000 the formula vectorises cleanly —
  /// SIMD backends are a planned follow-up that will mirror the
  /// Delta E 76 module structure.
  ///
  /// CIE94 is **asymmetric** (the S_C / S_H scale factors depend on
  /// the reference's chroma C₁); this implementation treats the
  /// palette entry as the reference and the query as the sample.
  pub fn nearest_to_cie94(rgb: [u8; 3]) -> &'static Color {
    crate::nearest::nearest_cie94(rgb_to_lab(rgb))
  }
}

/// Color-difference algorithm used to map an arbitrary RGB query to
/// its nearest [`Color`] in the xkcd palette.
///
/// Each variant corresponds to one of the per-metric
/// `Color::nearest_to_*` methods. The enum exists so callers can
/// store the choice as a value and pass it to higher-level APIs like
/// `colorthief::extract_with` without committing to a specific
/// `Color::nearest_to_*` callsite.
///
/// Marked `#[non_exhaustive]` so adding a future variant (e.g. CMC,
/// CIEDE2010) is a non-breaking change for downstream consumers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
#[non_exhaustive]
#[repr(u8)]
pub enum Algorithm {
  /// **Delta E 76** — squared Euclidean LAB distance. Fastest by a
  /// wide margin (~470 ns/query on Apple Silicon NEON, ~940 ns
  /// scalar). SIMD-dispatched on every supported arch with bit-
  /// identical parity. Recommended for search-vocabulary indexing
  /// where throughput matters more than borderline accuracy.
  DeltaE76,

  /// **CIE94 (Delta E 94, graphic-arts weighting)** — middle ground
  /// between Delta E 76's speed and CIEDE2000's accuracy. Uses only
  /// `sqrt` for transcendentals, so it vectorises cleanly. ~900 ns
  /// NEON / ~4.4 µs scalar. Asymmetric: the palette entry is the
  /// reference, the query is the sample.
  Cie94,

  /// **CIEDE2000** — the modern perceptual gold-standard formula.
  /// With `feature = "lut"` (the default) routes through the
  /// candidate-set LUT (~230 ns/query, provably exact at u8 RGB);
  /// without the feature falls back to the full-scan reference
  /// (~71 µs/query, also provably exact). Behaviorally equivalent
  /// to [`Self::Ciede2000Exact`] under both feature configurations.
  Ciede2000,

  /// **CIEDE2000**, retained as a distinct variant for API
  /// stability. Behaviorally equivalent to [`Self::Ciede2000`] —
  /// both go through the LUT when `feature = "lut"` is enabled and
  /// the full-scan reference otherwise. **Default.** Returned by
  /// [`Algorithm::default`] so consumers of [`Algorithm::extract`]
  /// and crate-level entry points like `colorthief::extract` get
  /// the perceptual gold-standard out of the box.
  #[default]
  Ciede2000Exact,
}

impl Algorithm {
  /// Find the [`Color`] whose pre-computed LAB is closest to the
  /// given RGB under this algorithm's distance metric.
  ///
  /// Equivalent to dispatching to the corresponding
  /// `Color::nearest_to*` method by hand:
  ///
  /// | Variant                    | Equivalent call                                |
  /// |----------------------------|------------------------------------------------|
  /// | [`Self::DeltaE76`]         | [`Color::nearest_to`]                          |
  /// | [`Self::Cie94`]            | [`Color::nearest_to_cie94`]                    |
  /// | [`Self::Ciede2000`]        | [`Color::nearest_to_ciede2000`]                |
  /// | [`Self::Ciede2000Exact`]   | [`Color::nearest_to_ciede2000_exact`]          |
  #[inline]
  pub fn extract(&self, rgb: [u8; 3]) -> &'static Color {
    match self {
      Self::DeltaE76 => Color::nearest_to(rgb),
      Self::Cie94 => Color::nearest_to_cie94(rgb),
      Self::Ciede2000 => Color::nearest_to_ciede2000(rgb),
      Self::Ciede2000Exact => Color::nearest_to_ciede2000_exact(rgb),
    }
  }

  /// Stable string identifier for this algorithm — useful for log
  /// lines, telemetry, and search-index metadata. Mirrors the
  /// [`Family::as_str`] / [`Kind::as_str`] convention.
  #[inline]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::DeltaE76 => "delta-e-76",
      Self::Cie94 => "cie94",
      Self::Ciede2000 => "ciede2000",
      Self::Ciede2000Exact => "ciede2000-exact",
    }
  }
}

/// Convert sRGB byte triple → CIE LAB (D65 illuminant, 2° observer).
///
/// Pipeline: byte → normalized [0, 1] → linearized (sRGB EOTF) → XYZ
/// (sRGB→XYZ matrix, D65) → LAB (CIE 1976 transfer).
pub(crate) fn rgb_to_lab(rgb: [u8; 3]) -> [f32; 3] {
  let r = srgb_to_linear(rgb[0] as f32 / 255.0);
  let g = srgb_to_linear(rgb[1] as f32 / 255.0);
  let b = srgb_to_linear(rgb[2] as f32 / 255.0);

  // sRGB → XYZ (D65, 2°). Coefficients from IEC 61966-2-1, rounded to
  // f32 precision (~7 decimal digits — trailing zeros that clippy flagged
  // as excessive precision are dropped here).
  let x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375;
  let y = r * 0.2126729 + g * 0.7151522 + b * 0.072175;
  let z = r * 0.0193339 + g * 0.119192 + b * 0.9503041;

  // D65 reference white (CIE 1931, 2°).
  const XN: f32 = 0.95047;
  const YN: f32 = 1.00000;
  const ZN: f32 = 1.08883;

  let fx = lab_f(x / XN);
  let fy = lab_f(y / YN);
  let fz = lab_f(z / ZN);

  let l = 116.0 * fy - 16.0;
  let a = 500.0 * (fx - fy);
  let b_lab = 200.0 * (fy - fz);
  [l, a, b_lab]
}

/// sRGB electro-optical transfer function (gamma decode).
fn srgb_to_linear(c: f32) -> f32 {
  if c <= 0.04045 {
    c / 12.92
  } else {
    libm::powf((c + 0.055) / 1.055, 2.4)
  }
}

/// CIE LAB transfer function (`f` in the standard).
fn lab_f(t: f32) -> f32 {
  // delta = 6/29; threshold where the linear/cube-root segments meet.
  const DELTA_CUBED: f32 = 216.0 / 24389.0; // (6/29)^3
  const KAPPA_OVER_3: f32 = 841.0 / 108.0; // 1 / (3 * (6/29)^2)
  const OFFSET: f32 = 4.0 / 29.0;
  if t > DELTA_CUBED {
    libm::cbrtf(t)
  } else {
    KAPPA_OVER_3 * t + OFFSET
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  /// The dataset must always be non-empty (xtask validates at codegen
  /// time, but a runtime smoke test catches a regression where someone
  /// edits `generated.rs` by hand).
  #[test]
  fn dataset_is_non_empty() {
    assert!(!COLORS.is_empty());
  }

  /// Snapshot the entry count. Acts as a canary if upstream colornamer
  /// updates the CSV: a count change is a deliberate regen, not a silent
  /// drift. Updating this number is the right action when intentional.
  #[test]
  fn dataset_entry_count_matches_csv() {
    assert_eq!(
      COLORS.len(),
      949,
      "regenerate via `cargo xtask codegen` if the upstream CSV changed",
    );
  }

  /// Pure sRGB red must map to an entry that's at least red-flavored.
  /// Strict equality on the xkcd label is fragile (the closest match
  /// depends on the palette and could be `"red"`, `"bright red"`,
  /// `"true red"`, etc.); the family is a stable invariant.
  #[test]
  fn nearest_to_pure_red_is_in_red_family() {
    let c = Color::nearest_to([255, 0, 0]);
    assert!(
      c.family().as_str().contains("red") || c.name().contains("red"),
      "nearest to pure red was name={:?} family={:?}",
      c.name(),
      c.family().as_str(),
    );
  }

  /// Pure sRGB blue must map to a blue-family entry.
  #[test]
  fn nearest_to_pure_blue_is_in_blue_family() {
    let c = Color::nearest_to([0, 0, 255]);
    assert!(
      c.family().as_str().contains("blue") || c.name().contains("blue"),
      "nearest to pure blue was name={:?} family={:?}",
      c.name(),
      c.family().as_str(),
    );
  }

  /// Mid-gray must map to a neutral. Tests that the `is_neutral` axis
  /// reaches readers correctly via the lookup path.
  #[test]
  fn nearest_to_mid_gray_is_neutral() {
    let c = Color::nearest_to([128, 128, 128]);
    assert!(
      c.is_neutral(),
      "nearest to (128,128,128) was name={:?} is_neutral={}",
      c.name(),
      c.is_neutral(),
    );
  }

  /// sRGB → LAB on the D65 reference white must produce L=100, a=0, b=0
  /// to within float tolerance.
  #[test]
  fn rgb_to_lab_d65_white() {
    let lab = rgb_to_lab([255, 255, 255]);
    assert!((lab[0] - 100.0).abs() < 0.01, "L was {}", lab[0]);
    assert!(lab[1].abs() < 0.01, "a was {}", lab[1]);
    assert!(lab[2].abs() < 0.01, "b was {}", lab[2]);
  }

  /// sRGB → LAB on absolute black must produce L=0, a=0, b=0 exactly
  /// (the linear segment of the sRGB EOTF carries 0 through unchanged).
  #[test]
  fn rgb_to_lab_black() {
    let lab = rgb_to_lab([0, 0, 0]);
    assert!(lab[0].abs() < 1e-6, "L was {}", lab[0]);
    assert!(lab[1].abs() < 1e-6, "a was {}", lab[1]);
    assert!(lab[2].abs() < 1e-6, "b was {}", lab[2]);
  }
}