geo_svg/
unit.rs

1use std::fmt::{Display, Formatter, Result};
2
3/// Represents a quantity in absolute CSS units.
4///
5/// Relative units `%`, `em`, `rem`, `vh` and `vw` are not supported.
6#[derive(Clone, Copy, Debug)]
7pub enum Unit {
8    /// Centimeter (cm), 37.8px
9    Centimeter(f32),
10    /// Inch (in), 2.54cm, exactly 96px, 72pt, 6pc
11    Inch(f32),
12    /// No units, defaults as appropriate based on context
13    None(f32),
14    /// Millimeter (mm), 0.1cm
15    Millimeter(f32),
16    /// Pica (pc), 1/6 in, 12pt, 16px
17    Pica(f32),
18    /// Pixel (px), 1/96 in, 2/3 pt, 1/16 pc
19    Pixel(f32),
20    /// Point (pt), 1/72 in or 4/3 px, 1/12 pc
21    Point(f32),
22    /// Quarter-millimeter (Q), 1/4 mm, or 1/40 cm
23    QuarterMillimeter(f32),
24}
25
26impl Unit {
27    /// raw value with no units
28    pub fn value(self) -> f32 {
29        match self {
30            Self::Centimeter(value) => value,
31            Self::Inch(value) => value,
32            Self::None(value) => value,
33            Self::Millimeter(value) => value,
34            Self::Pica(value) => value,
35            Self::Pixel(value) => value,
36            Self::Point(value) => value,
37            Self::QuarterMillimeter(value) => value,
38        }
39    }
40
41    /// abbreviated symbol of the unit
42    pub fn symbol(self) -> &'static str {
43        match self {
44            Self::Centimeter(_) => "cm",
45            Self::Inch(_) => "in",
46            Self::None(_) => "",
47            Self::Millimeter(_) => "mm",
48            Self::Pica(_) => "pc",
49            Self::Pixel(_) => "px",
50            Self::Point(_) => "pt",
51            Self::QuarterMillimeter(_) => "Q",
52        }
53    }
54
55    pub fn scale(self, factor: f32) -> Self {
56        match self {
57            Self::Centimeter(value) => Self::Centimeter(value * factor),
58            Self::Inch(value) => Self::Inch(value * factor),
59            Self::None(value) => Self::None(value * factor),
60            Self::Millimeter(value) => Self::Millimeter(value * factor),
61            Self::Pica(value) => Self::Pica(value * factor),
62            Self::Pixel(value) => Self::Pixel(value * factor),
63            Self::Point(value) => Self::Point(value * factor),
64            Self::QuarterMillimeter(value) => Self::QuarterMillimeter(value * factor),
65        }
66    }
67}
68
69impl Display for Unit {
70    fn fmt(&self, fmt: &mut Formatter) -> Result {
71        write!(
72            fmt,
73            "{value}{symbol}",
74            value = self.value(),
75            symbol = self.symbol()
76        )
77    }
78}