typst_library/layout/
size.rs

1use std::ops::{Add, Div, Mul, Neg};
2
3use typst_utils::Numeric;
4
5use crate::layout::{Abs, Axes, Point, Ratio};
6
7/// A size in 2D.
8pub type Size = Axes<Abs>;
9
10impl Size {
11    /// The zero value.
12    pub const fn zero() -> Self {
13        Self { x: Abs::zero(), y: Abs::zero() }
14    }
15
16    /// Whether the other size fits into this one (smaller width and height).
17    pub fn fits(self, other: Self) -> bool {
18        self.x.fits(other.x) && self.y.fits(other.y)
19    }
20
21    /// Convert to a point.
22    pub fn to_point(self) -> Point {
23        Point::new(self.x, self.y)
24    }
25
26    /// Converts to a ratio of width to height.
27    pub fn aspect_ratio(self) -> Ratio {
28        Ratio::new(self.x / self.y)
29    }
30}
31
32impl Numeric for Size {
33    fn zero() -> Self {
34        Self::zero()
35    }
36
37    fn is_finite(self) -> bool {
38        self.x.is_finite() && self.y.is_finite()
39    }
40}
41
42impl Neg for Size {
43    type Output = Self;
44
45    fn neg(self) -> Self {
46        Self { x: -self.x, y: -self.y }
47    }
48}
49
50impl Add for Size {
51    type Output = Self;
52
53    fn add(self, other: Self) -> Self {
54        Self { x: self.x + other.x, y: self.y + other.y }
55    }
56}
57
58typst_utils::sub_impl!(Size - Size -> Size);
59
60impl Mul<f64> for Size {
61    type Output = Self;
62
63    fn mul(self, other: f64) -> Self {
64        Self { x: self.x * other, y: self.y * other }
65    }
66}
67
68impl Mul<Size> for f64 {
69    type Output = Size;
70
71    fn mul(self, other: Size) -> Size {
72        other * self
73    }
74}
75
76impl Div<f64> for Size {
77    type Output = Self;
78
79    fn div(self, other: f64) -> Self {
80        Self { x: self.x / other, y: self.y / other }
81    }
82}
83
84typst_utils::assign_impl!(Size -= Size);
85typst_utils::assign_impl!(Size += Size);
86typst_utils::assign_impl!(Size *= f64);
87typst_utils::assign_impl!(Size /= f64);