Skip to main content

typst_library/layout/
abs.rs

1use std::fmt::{self, Debug, Formatter};
2use std::iter::Sum;
3use std::ops::{Add, Div, Mul, Neg, Rem};
4
5use ecow::EcoString;
6use typst_utils::{Numeric, NumericLength, Scalar};
7
8use crate::foundations::{Fold, Repr, Value, cast, repr};
9
10/// An absolute length.
11#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
12pub struct Abs(Scalar);
13
14impl Abs {
15    /// The zero length.
16    pub const fn zero() -> Self {
17        Self(Scalar::ZERO)
18    }
19
20    /// The infinite length.
21    pub const fn inf() -> Self {
22        Self(Scalar::INFINITY)
23    }
24
25    /// Create an absolute length from a number of raw units.
26    pub const fn raw(raw: f64) -> Self {
27        Self(Scalar::new(raw))
28    }
29
30    /// Create an absolute length from a value in a unit.
31    pub fn with_unit(val: f64, unit: AbsUnit) -> Self {
32        Self(Scalar::new(val * unit.raw_scale()))
33    }
34
35    /// Create an absolute length from a number of points.
36    pub fn pt(pt: f64) -> Self {
37        Self::with_unit(pt, AbsUnit::Pt)
38    }
39
40    /// Create an absolute length from a number of millimeters.
41    pub fn mm(mm: f64) -> Self {
42        Self::with_unit(mm, AbsUnit::Mm)
43    }
44
45    /// Create an absolute length from a number of centimeters.
46    pub fn cm(cm: f64) -> Self {
47        Self::with_unit(cm, AbsUnit::Cm)
48    }
49
50    /// Create an absolute length from a number of inches.
51    pub fn inches(inches: f64) -> Self {
52        Self::with_unit(inches, AbsUnit::In)
53    }
54
55    /// Get the value of this absolute length in raw units.
56    pub const fn to_raw(self) -> f64 {
57        self.0.get()
58    }
59
60    /// Get the value of this absolute length in raw units.
61    pub const fn scalar(self) -> Scalar {
62        self.0
63    }
64
65    /// Get the value of this absolute length in a unit.
66    pub fn to_unit(self, unit: AbsUnit) -> f64 {
67        self.to_raw() / unit.raw_scale()
68    }
69
70    /// Convert this to a number of points.
71    pub fn to_pt(self) -> f64 {
72        self.to_unit(AbsUnit::Pt)
73    }
74
75    /// Convert this to a number of millimeters.
76    pub fn to_mm(self) -> f64 {
77        self.to_unit(AbsUnit::Mm)
78    }
79
80    /// Convert this to a number of centimeters.
81    pub fn to_cm(self) -> f64 {
82        self.to_unit(AbsUnit::Cm)
83    }
84
85    /// Convert this to a number of inches.
86    pub fn to_inches(self) -> f64 {
87        self.to_unit(AbsUnit::In)
88    }
89
90    /// The absolute value of this length.
91    pub fn abs(self) -> Self {
92        Self::raw(self.to_raw().abs())
93    }
94
95    /// The minimum of this and another absolute length.
96    pub fn min(self, other: Self) -> Self {
97        Self(self.0.min(other.0))
98    }
99
100    /// Set to the minimum of this and another absolute length.
101    pub fn set_min(&mut self, other: Self) {
102        *self = (*self).min(other);
103    }
104
105    /// The maximum of this and another absolute length.
106    pub fn max(self, other: Self) -> Self {
107        Self(self.0.max(other.0))
108    }
109
110    /// Set to the maximum of this and another absolute length.
111    pub fn set_max(&mut self, other: Self) {
112        *self = (*self).max(other);
113    }
114
115    /// Whether the other absolute length fits into this one (i.e. is smaller).
116    /// Allows for a bit of slack.
117    pub fn fits(self, other: Self) -> bool {
118        self.0 + AbsUnit::EPS >= other.0
119    }
120
121    /// Compares two absolute lengths for whether they are approximately equal.
122    pub fn approx_eq(self, other: Self) -> bool {
123        self == other || (self - other).to_raw().abs() < AbsUnit::EPS
124    }
125
126    /// Whether the size is close to zero or negative.
127    pub fn approx_empty(self) -> bool {
128        self.to_raw() <= AbsUnit::EPS
129    }
130
131    /// Returns a number that represent the sign of this length
132    pub fn signum(self) -> f64 {
133        self.0.get().signum()
134    }
135}
136
137impl NumericLength for Abs {}
138
139impl Numeric for Abs {
140    fn zero() -> Self {
141        Self::zero()
142    }
143
144    fn is_finite(self) -> bool {
145        self.0.is_finite()
146    }
147}
148
149impl Debug for Abs {
150    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
151        write!(f, "{:?}pt", self.to_pt())
152    }
153}
154
155impl Repr for Abs {
156    fn repr(&self) -> EcoString {
157        repr::format_float_with_unit(self.to_pt(), "pt")
158    }
159}
160
161impl Neg for Abs {
162    type Output = Self;
163
164    fn neg(self) -> Self {
165        Self(-self.0)
166    }
167}
168
169impl Add for Abs {
170    type Output = Self;
171
172    fn add(self, other: Self) -> Self {
173        Self(self.0 + other.0)
174    }
175}
176
177typst_utils::sub_impl!(Abs - Abs -> Abs);
178
179impl Mul<f64> for Abs {
180    type Output = Self;
181
182    fn mul(self, other: f64) -> Self {
183        Self(self.0 * other)
184    }
185}
186
187impl Mul<Abs> for f64 {
188    type Output = Abs;
189
190    fn mul(self, other: Abs) -> Abs {
191        other * self
192    }
193}
194
195impl Div<f64> for Abs {
196    type Output = Self;
197
198    fn div(self, other: f64) -> Self {
199        Self(self.0 / other)
200    }
201}
202
203impl Div for Abs {
204    type Output = f64;
205
206    fn div(self, other: Self) -> f64 {
207        self.to_raw() / other.to_raw()
208    }
209}
210
211typst_utils::assign_impl!(Abs += Abs);
212typst_utils::assign_impl!(Abs -= Abs);
213typst_utils::assign_impl!(Abs *= f64);
214typst_utils::assign_impl!(Abs /= f64);
215
216impl Rem for Abs {
217    type Output = Self;
218
219    fn rem(self, other: Self) -> Self::Output {
220        Self(self.0 % other.0)
221    }
222}
223
224impl Sum for Abs {
225    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
226        Self(iter.map(|s| s.0).sum())
227    }
228}
229
230impl<'a> Sum<&'a Self> for Abs {
231    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
232        Self(iter.map(|s| s.0).sum())
233    }
234}
235
236impl Fold for Abs {
237    fn fold(self, _: Self) -> Self {
238        self
239    }
240}
241
242cast! {
243    Abs,
244    self => Value::Length(self.into()),
245}
246
247/// Different units of absolute measurement.
248#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
249pub enum AbsUnit {
250    /// Points.
251    Pt,
252    /// Millimeters.
253    Mm,
254    /// Centimeters.
255    Cm,
256    /// Inches.
257    In,
258}
259
260impl AbsUnit {
261    /// The epsilon for approximate length comparisons.
262    const EPS: f64 = 1e-4;
263
264    /// How many raw units correspond to a value of `1.0` in this unit.
265    const fn raw_scale(self) -> f64 {
266        // We choose a raw scale which has an integer conversion value to all
267        // four units of interest, so that whole numbers in all units can be
268        // represented accurately.
269        match self {
270            AbsUnit::Pt => 127.0,
271            AbsUnit::Mm => 360.0,
272            AbsUnit::Cm => 3600.0,
273            AbsUnit::In => 9144.0,
274        }
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn test_length_unit_conversion() {
284        assert!((Abs::mm(150.0).to_cm() - 15.0) < 1e-4);
285    }
286}