From 7b6f3a0ab9ae0dac19f62b62b9ecc96ea942a89e Mon Sep 17 00:00:00 2001 From: Martin Haug Date: Mon, 2 May 2022 15:49:46 +0200 Subject: A new `Cast` implementation for `Sides` Reinstate circle --- src/eval/value.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) (limited to 'src/eval') diff --git a/src/eval/value.rs b/src/eval/value.rs index 6ce815a4..c32614df 100644 --- a/src/eval/value.rs +++ b/src/eval/value.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use super::{ops, Args, Array, Dict, Func, RawLength}; use crate::diag::{with_alternative, StrResult}; use crate::geom::{ - Angle, Color, Dir, Em, Fraction, Length, Paint, Ratio, Relative, RgbaColor, + Angle, Color, Dir, Em, Fraction, Length, Paint, Ratio, Relative, RgbaColor, Sides, }; use crate::library::text::RawNode; use crate::model::{Content, Layout, LayoutNode}; @@ -596,6 +596,44 @@ impl Cast for Smart { } } +impl Cast for Sides { + fn is(value: &Value) -> bool { + matches!(value, Value::Dict(_)) || T::is(value) + } + + fn cast(value: Value) -> StrResult { + match value { + Value::Dict(dict) => { + for (key, _) in &dict { + if !matches!( + key.as_str(), + "left" | "top" | "right" | "bottom" | "x" | "y" | "rest" + ) { + return Err(format!("unexpected key {key:?}")); + } + } + + let sides = Sides { + left: dict.get("left".into()).or_else(|_| dict.get("x".into())), + top: dict.get("top".into()).or_else(|_| dict.get("y".into())), + right: dict.get("right".into()).or_else(|_| dict.get("x".into())), + bottom: dict.get("bottom".into()).or_else(|_| dict.get("y".into())), + } + .map(|side| { + side.or_else(|_| dict.get("rest".into())) + .and_then(|v| T::cast(v.clone())) + .unwrap_or_default() + }); + + Ok(sides) + } + v => T::cast(v) + .map(Sides::splat) + .map_err(|msg| with_alternative(msg, "dictionary")), + } + } +} + dynamic! { Dir: "direction", } -- cgit v1.2.3 From 9b4397cdab25daff448cefb179a4699f64fa3d3f Mon Sep 17 00:00:00 2001 From: Martin Haug Date: Mon, 2 May 2022 18:25:53 +0200 Subject: Tests for the new shape API --- src/eval/value.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/eval') diff --git a/src/eval/value.rs b/src/eval/value.rs index c32614df..352906aa 100644 --- a/src/eval/value.rs +++ b/src/eval/value.rs @@ -596,7 +596,10 @@ impl Cast for Smart { } } -impl Cast for Sides { +impl Cast for Sides +where + T: Cast + Default + Clone, +{ fn is(value: &Value) -> bool { matches!(value, Value::Dict(_)) || T::is(value) } -- cgit v1.2.3