From 9544e651ba9245808d5b52d7f6d53841b69441ec Mon Sep 17 00:00:00 2001 From: Raph Levien Date: Tue, 1 Jan 2019 21:15:43 -0800 Subject: [PATCH] Add missing conv.rs file I forgot to "git add" it. --- piet/src/conv.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 piet/src/conv.rs diff --git a/piet/src/conv.rs b/piet/src/conv.rs new file mode 100644 index 0000000..f1f440f --- /dev/null +++ b/piet/src/conv.rs @@ -0,0 +1,67 @@ +//! Conversions of fundamental numeric and geometric types. + +use kurbo::Vec2; + +/// This is our own implementation of a "lossy From" trait, representing +/// a conversion that can have precision loss. It is essentially adapted +/// from . +/// +/// If and when such a trait is standardized, we should switch to that. +/// Alternatively, a case can be made it should move somewhere else, or +/// we should adopt a similar trait (it has some similarity to AsPrimitive +/// from num_traits). +pub trait RoundFrom { + fn round_from(x: T) -> Self; +} + +/// The companion to `RoundFrom`. As with `From` and `Into`, a blanket +/// implementation is provided; for the most part, implement `RoundFrom`. +pub trait RoundInto { + fn round_into(self) -> T; +} + +impl RoundInto for T +where + U: RoundFrom, +{ + fn round_into(self) -> U { + U::round_from(self) + } +} + +impl RoundFrom for f32 { + fn round_from(x: f64) -> f32 { + x as f32 + } +} + +impl RoundFrom for (f32, f32) { + fn round_from(p: Vec2) -> (f32, f32) { + (p.x as f32, p.y as f32) + } +} + +impl RoundFrom<(f32, f32)> for Vec2 { + fn round_from(p: (f32, f32)) -> Vec2 { + Vec2::new(p.0 as f64, p.1 as f64) + } +} + +impl RoundFrom for (f64, f64) { + fn round_from(p: Vec2) -> (f64, f64) { + (p.x, p.y) + } +} + +impl RoundFrom<(f64, f64)> for Vec2 { + fn round_from(p: (f64, f64)) -> Vec2 { + Vec2::new(p.0, p.1) + } +} + +/// Blanket implementation, no conversion needed. +impl RoundFrom for T { + fn round_from(x: T) -> T { + x + } +} -- 2.34.2