piet/
conv.rs

1// Copyright 2019 the Piet Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Conversions of fundamental numeric and geometric types.
5
6use kurbo::Vec2;
7
8/// A trait for types that can be converted with precision loss.
9///
10/// This is our own implementation of a "lossy From" trait. It is essentially
11/// adapted from <https://github.com/rust-lang/rfcs/pull/2484>.
12///
13/// If and when such a trait is standardized, we should switch to that.
14/// Alternatively, a case can be made it should move somewhere else, or
15/// we should adopt a similar trait (it has some similarity to AsPrimitive
16/// from num_traits).
17pub trait RoundFrom<T> {
18    /// Performs the conversion.
19    fn round_from(x: T) -> Self;
20}
21
22/// The companion to `RoundFrom`.
23///
24/// As with `From` and `Into`, a blanket implementation is provided;
25/// for the most part, implement `RoundFrom`.
26pub trait RoundInto<T> {
27    /// Performs the conversion.
28    fn round_into(self) -> T;
29}
30
31impl<T, U> RoundInto<U> for T
32where
33    U: RoundFrom<T>,
34{
35    fn round_into(self) -> U {
36        U::round_from(self)
37    }
38}
39
40impl RoundFrom<f64> for f32 {
41    fn round_from(x: f64) -> f32 {
42        x as f32
43    }
44}
45
46impl RoundFrom<f32> for f64 {
47    fn round_from(x: f32) -> f64 {
48        x as f64
49    }
50}
51
52impl RoundFrom<Vec2> for (f32, f32) {
53    fn round_from(p: Vec2) -> (f32, f32) {
54        (p.x as f32, p.y as f32)
55    }
56}
57
58impl RoundFrom<(f32, f32)> for Vec2 {
59    fn round_from(p: (f32, f32)) -> Vec2 {
60        Vec2::new(p.0 as f64, p.1 as f64)
61    }
62}
63
64impl RoundFrom<Vec2> for (f64, f64) {
65    fn round_from(p: Vec2) -> (f64, f64) {
66        (p.x, p.y)
67    }
68}
69
70impl RoundFrom<(f64, f64)> for Vec2 {
71    fn round_from(p: (f64, f64)) -> Vec2 {
72        Vec2::new(p.0, p.1)
73    }
74}
75
76/// Blanket implementation, no conversion needed.
77impl<T> RoundFrom<T> for T {
78    fn round_from(x: T) -> T {
79        x
80    }
81}