From d821633f50f7f4c9edc49b6ac5e88d43802cb206 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Thu, 19 Jun 2025 17:20:17 +0200 Subject: Generic casting for `Axes` --- crates/typst-library/src/layout/axes.rs | 62 +++++++++++++++++---------------- 1 file changed, 32 insertions(+), 30 deletions(-) (limited to 'crates/typst-library/src') diff --git a/crates/typst-library/src/layout/axes.rs b/crates/typst-library/src/layout/axes.rs index 7a73ba79..e4303f98 100644 --- a/crates/typst-library/src/layout/axes.rs +++ b/crates/typst-library/src/layout/axes.rs @@ -4,9 +4,12 @@ use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Deref, Not}; use typst_utils::Get; -use crate::diag::bail; -use crate::foundations::{array, cast, Array, Resolve, Smart, StyleChain}; -use crate::layout::{Abs, Dir, Length, Ratio, Rel, Size}; +use crate::diag::{bail, HintedStrResult}; +use crate::foundations::{ + array, cast, Array, CastInfo, FromValue, IntoValue, Reflect, Resolve, Smart, + StyleChain, Value, +}; +use crate::layout::{Abs, Dir, Rel, Size}; /// A container with a horizontal and vertical component. #[derive(Default, Copy, Clone, Eq, PartialEq, Hash)] @@ -275,40 +278,39 @@ impl BitAndAssign for Axes { } } -cast! { - Axes>, - self => array![self.x, self.y].into_value(), - array: Array => { - let mut iter = array.into_iter(); - match (iter.next(), iter.next(), iter.next()) { - (Some(a), Some(b), None) => Axes::new(a.cast()?, b.cast()?), - _ => bail!("point array must contain exactly two entries"), - } - }, +impl Reflect for Axes { + fn input() -> CastInfo { + Array::input() + } + + fn output() -> CastInfo { + Array::output() + } + + fn castable(value: &Value) -> bool { + Array::castable(value) + } } -cast! { - Axes, - self => array![self.x, self.y].into_value(), - array: Array => { +impl FromValue for Axes { + fn from_value(value: Value) -> HintedStrResult { + let array = value.cast::()?; let mut iter = array.into_iter(); match (iter.next(), iter.next(), iter.next()) { - (Some(a), Some(b), None) => Axes::new(a.cast()?, b.cast()?), - _ => bail!("ratio array must contain exactly two entries"), + (Some(a), Some(b), None) => Ok(Axes::new(a.cast()?, b.cast()?)), + _ => bail!( + "array must contain exactly two items"; + hint: "the first item determines the value for the X axis \ + and the second item the value for the Y axis" + ), } - }, + } } -cast! { - Axes, - self => array![self.x, self.y].into_value(), - array: Array => { - let mut iter = array.into_iter(); - match (iter.next(), iter.next(), iter.next()) { - (Some(a), Some(b), None) => Axes::new(a.cast()?, b.cast()?), - _ => bail!("length array must contain exactly two entries"), - } - }, +impl IntoValue for Axes { + fn into_value(self) -> Value { + array![self.x.into_value(), self.y.into_value()].into_value() + } } impl Resolve for Axes { -- cgit v1.2.3