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
// This file is part of helpers4.
// Copyright (C) 2025 baxyz
// SPDX-License-Identifier: LGPL-3.0-or-later
use Rgb;
/// The WCAG contrast ratio between two colors, from `1.0` (identical) to `21.0` (black on white).
///
/// It is `(L1 + 0.05) / (L2 + 0.05)` where `L1` is the relative luminance of the lighter color
/// and `L2` of the darker one, so the order of the arguments does not matter. WCAG 2.x asks for
/// at least `4.5` for normal text and `3.0` for large text (level AA), `7.0` and `4.5` for AAA.
///
/// # Arguments
///
/// - `a` - One color, for instance the text.
/// - `b` - The other color, for instance its background.
///
/// # Returns
///
/// The ratio, `1.0..=21.0`.
///
/// # Examples
///
/// ```
/// use helpers4::color::{contrast_ratio, Rgb};
///
/// let ratio = contrast_ratio(Rgb::new(0, 0, 0), Rgb::new(255, 255, 255));
/// assert!((ratio - 21.0).abs() < 1e-9);
/// assert!(contrast_ratio(Rgb::parse("#767676")?, Rgb::new(255, 255, 255)) >= 4.5);
/// # Ok::<(), helpers4::color::ParseColorError>(())
/// ```