diff options
| author | Laurenz <laurmaedje@gmail.com> | 2020-10-10 22:19:36 +0200 |
|---|---|---|
| committer | Laurenz <laurmaedje@gmail.com> | 2020-10-10 22:19:36 +0200 |
| commit | 92c01da36016e94ff20163806ddcbcf7e33d4031 (patch) | |
| tree | 1a900b3c11edcc93e9153fada3ce92310db5768b /src/geom/relative.rs | |
| parent | 42500d5ed85539c5ab04dd3544beaf802da29be9 (diff) | |
Switch back to custom geometry types, unified with layout primitives 🏞
Diffstat (limited to 'src/geom/relative.rs')
| -rw-r--r-- | src/geom/relative.rs | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/src/geom/relative.rs b/src/geom/relative.rs new file mode 100644 index 00000000..037c83dc --- /dev/null +++ b/src/geom/relative.rs @@ -0,0 +1,92 @@ +use super::*; + +/// A relative length. +/// +/// _Note_: `50%` is represented as `0.5` here, but stored as `50.0` in the +/// corresponding [literal]. +/// +/// [literal]: ../syntax/ast/enum.Lit.html#variant.Percent +#[derive(Default, Copy, Clone, PartialEq, PartialOrd)] +pub struct Relative(f64); + +impl Relative { + /// A ratio of `0%` represented as `0.0`. + pub const ZERO: Self = Self(0.0); + + /// A ratio of `100%` represented as `1.0`. + pub const ONE: Self = Self(1.0); + + /// Create a new relative value. + pub fn new(ratio: f64) -> Self { + Self(ratio) + } + + /// Get the underlying ratio. + pub fn get(self) -> f64 { + self.0 + } + + /// Evaluate the relative length with `one` being `100%`. + pub fn eval(self, one: Length) -> Length { + self.get() * one + } +} + +impl Display for Relative { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{:.2}%", self.0) + } +} + +impl Debug for Relative { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + Display::fmt(self, f) + } +} + +impl Neg for Relative { + type Output = Self; + + fn neg(self) -> Self { + Self(-self.0) + } +} + +impl Add for Relative { + type Output = Self; + + fn add(self, other: Self) -> Self { + Self(self.0 + other.0) + } +} + +sub_impl!(Relative - Relative -> Relative); + +impl Mul<f64> for Relative { + type Output = Self; + + fn mul(self, other: f64) -> Self { + Self(self.0 * other) + } +} + +impl Mul<Relative> for f64 { + type Output = Relative; + + fn mul(self, other: Relative) -> Relative { + other * self + } +} + +impl Div<f64> for Relative { + type Output = Self; + + fn div(self, other: f64) -> Self { + Self(self.0 / other) + } +} + +assign_impl!(Relative += Relative); +assign_impl!(Relative -= Relative); +assign_impl!(Relative *= f64); +assign_impl!(Relative /= f64); |
