Skip to main content

parsec_css/values/
units.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The dimensions of CSS Values and Units Level 4: every unit, what it
5//! measures, and how the absolute ones convert to their canonical unit.
6
7use std::fmt;
8
9/// What a dimension measures.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum Kind {
12    Length,
13    Angle,
14    Time,
15    Frequency,
16    Resolution,
17    Flex,
18}
19
20macro_rules! units {
21    ($($unit:ident $text:literal $kind:ident $factor:expr,)*) => {
22        /// A unit, from the dimension tokens CSS knows.
23        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
24        pub enum Unit {
25            $($unit,)*
26        }
27
28        impl Unit {
29
30            /// The unit as CSS writes it, in lowercase.
31            pub fn as_str(self) -> &'static str {
32                match self {
33                    $(Unit::$unit => $text,)*
34                }
35            }
36
37            fn from_lowercase(unit: &str) -> Option<Unit> {
38                match unit {
39                    $($text => Some(Unit::$unit),)*
40                    _ => None,
41                }
42            }
43
44            pub fn kind(self) -> Kind {
45                match self {
46                    $(Unit::$unit => Kind::$kind,)*
47                }
48            }
49
50            /// How many of the canonical unit (`px`, `deg`, `s`, `hz`,
51            /// `dppx`) one of this is, for the units with a fixed ratio.
52            pub fn to_canonical(self) -> Option<f64> {
53                match self {
54                    $(Unit::$unit => $factor,)*
55                }
56            }
57        }
58    };
59}
60
61const FONT: Option<f64> = None;
62
63units! {
64    // Font-relative lengths.
65    Em "em" Length FONT,
66    Rem "rem" Length FONT,
67    Ex "ex" Length FONT,
68    Rex "rex" Length FONT,
69    Cap "cap" Length FONT,
70    Rcap "rcap" Length FONT,
71    Ch "ch" Length FONT,
72    Rch "rch" Length FONT,
73    Ic "ic" Length FONT,
74    Ric "ric" Length FONT,
75    Lh "lh" Length FONT,
76    Rlh "rlh" Length FONT,
77    // Viewport lengths: default, small, large and dynamic.
78    Vw "vw" Length FONT,
79    Vh "vh" Length FONT,
80    Vi "vi" Length FONT,
81    Vb "vb" Length FONT,
82    Vmin "vmin" Length FONT,
83    Vmax "vmax" Length FONT,
84    Svw "svw" Length FONT,
85    Svh "svh" Length FONT,
86    Svi "svi" Length FONT,
87    Svb "svb" Length FONT,
88    Svmin "svmin" Length FONT,
89    Svmax "svmax" Length FONT,
90    Lvw "lvw" Length FONT,
91    Lvh "lvh" Length FONT,
92    Lvi "lvi" Length FONT,
93    Lvb "lvb" Length FONT,
94    Lvmin "lvmin" Length FONT,
95    Lvmax "lvmax" Length FONT,
96    Dvw "dvw" Length FONT,
97    Dvh "dvh" Length FONT,
98    Dvi "dvi" Length FONT,
99    Dvb "dvb" Length FONT,
100    Dvmin "dvmin" Length FONT,
101    Dvmax "dvmax" Length FONT,
102    // Container query lengths.
103    Cqw "cqw" Length FONT,
104    Cqh "cqh" Length FONT,
105    Cqi "cqi" Length FONT,
106    Cqb "cqb" Length FONT,
107    Cqmin "cqmin" Length FONT,
108    Cqmax "cqmax" Length FONT,
109    // Absolute lengths.
110    Px "px" Length Some(1.0),
111    Cm "cm" Length Some(96.0 / 2.54),
112    Mm "mm" Length Some(96.0 / 25.4),
113    Q "q" Length Some(96.0 / 101.6),
114    In "in" Length Some(96.0),
115    Pt "pt" Length Some(96.0 / 72.0),
116    Pc "pc" Length Some(16.0),
117    Deg "deg" Angle Some(1.0),
118    Grad "grad" Angle Some(0.9),
119    Rad "rad" Angle Some(180.0 / std::f64::consts::PI),
120    Turn "turn" Angle Some(360.0),
121    S "s" Time Some(1.0),
122    Ms "ms" Time Some(0.001),
123    Hz "hz" Frequency Some(1.0),
124    Khz "khz" Frequency Some(1000.0),
125    Dppx "dppx" Resolution Some(1.0),
126    X "x" Resolution Some(1.0),
127    Dpi "dpi" Resolution Some(1.0 / 96.0),
128    Dpcm "dpcm" Resolution Some(2.54 / 96.0),
129    Fr "fr" Flex FONT,
130}
131
132impl Unit {
133    /// The unit a dimension token's unit names, ignoring ASCII case.
134    pub fn parse(unit: &str) -> Option<Unit> {
135        // Units are nearly always written in lowercase already.
136        if !unit.bytes().any(|b| b.is_ascii_uppercase()) {
137            return Unit::from_lowercase(unit);
138        }
139        let mut buf = [0; 32];
140        let lower = lowercase(unit, &mut buf)?;
141        Unit::from_lowercase(lower)
142    }
143
144    /// The canonical unit of its kind, if it has one.
145    pub fn canonical(self) -> Option<Unit> {
146        self.to_canonical()?;
147        Some(match self.kind() {
148            Kind::Length => Unit::Px,
149            Kind::Angle => Unit::Deg,
150            Kind::Time => Unit::S,
151            Kind::Frequency => Unit::Hz,
152            Kind::Resolution => Unit::Dppx,
153            Kind::Flex => return None,
154        })
155    }
156}
157
158impl fmt::Display for Unit {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        f.write_str(self.as_str())
161    }
162}
163
164/// `s` in ASCII lowercase, in `buf`, without allocating; `None` if it's
165/// longer than any keyword this is used to look up.
166pub(crate) fn lowercase<'b>(s: &str, buf: &'b mut [u8; 32]) -> Option<&'b str> {
167    let out = buf.get_mut(..s.len())?;
168    out.copy_from_slice(s.as_bytes());
169    out.make_ascii_lowercase();
170    // Only ASCII bytes changed, so it's still UTF-8.
171    std::str::from_utf8(out).ok()
172}
173
174/// A number, a value with a unit, written as CSSOM serializes one: to six
175/// significant figures, without an exponent, `-0` as `0`.
176pub fn write_number(out: &mut impl fmt::Write, v: f64) -> fmt::Result {
177    if v.is_nan() {
178        return out.write_str("NaN");
179    }
180    if v.is_infinite() {
181        return out.write_str(if v > 0.0 { "infinity" } else { "-infinity" });
182    }
183    if v == v.trunc() && v.abs() < 1e15 {
184        return write!(out, "{}", v as i64);
185    }
186    let magnitude = v.abs().log10().floor() as i32;
187    let decimals = (5 - magnitude).clamp(0, 20) as usize;
188    let s = format!("{v:.decimals$}");
189    let s = if s.contains('.') {
190        s.trim_end_matches('0').trim_end_matches('.')
191    } else {
192        &s
193    };
194    out.write_str(if s == "-0" { "0" } else { s })
195}
196
197/// [`write_number`] into a new string.
198pub fn number_to_string(v: f64) -> String {
199    let mut s = String::new();
200    write_number(&mut s, v).unwrap();
201    s
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn numbers_to_six_figures() {
210        let cases = [
211            (1.0, "1"),
212            (0.5, "0.5"),
213            (1.0 / 3.0, "0.333333"),
214            (-0.0, "0"),
215            (-0.0000001, "-0.0000001"),
216            (123.456789, "123.457"),
217            (1e6 + 0.25, "1000000"),
218            (0.000012345678, "0.0000123457"),
219            (f64::INFINITY, "infinity"),
220        ];
221        for (v, s) in cases {
222            assert_eq!(number_to_string(v), s, "{v}");
223        }
224    }
225
226    #[test]
227    fn units_parse_in_any_case() {
228        assert_eq!(Unit::parse("PX"), Some(Unit::Px));
229        assert_eq!(Unit::parse("kHz"), Some(Unit::Khz));
230        assert_eq!(Unit::parse("pxx"), None);
231        assert_eq!(Unit::In.to_canonical(), Some(96.0));
232        assert_eq!(Unit::Em.canonical(), None);
233    }
234}