1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use libm;
use crate::Vec2;
use core::fmt;
use core::ops::{Mul, MulAssign};
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Size {
pub width: f64,
pub height: f64,
}
impl Size {
pub const ZERO: Size = Size::new(0., 0.);
#[inline]
pub const fn new(width: f64, height: f64) -> Self {
Size { width, height }
}
pub fn clamp(self, min: Size, max: Size) -> Self {
let width = self.width.max(min.width).min(max.width);
let height = self.height.max(min.height).min(max.height);
Size { width, height }
}
#[inline]
pub const fn to_vec2(self) -> Vec2 {
Vec2::new(self.width, self.height)
}
#[inline]
pub fn round(self) -> Size {
Size::new(libm::round(self.width), libm::round(self.height))
}
}
impl fmt::Debug for Size {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}W×{:?}H", self.width, self.height)
}
}
impl fmt::Display for Size {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "(")?;
fmt::Display::fmt(&self.width, formatter)?;
write!(formatter, "×")?;
fmt::Display::fmt(&self.height, formatter)?;
write!(formatter, ")")
}
}
impl MulAssign<f64> for Size {
#[inline]
fn mul_assign(&mut self, other: f64) {
*self = Size {
width: self.width * other,
height: self.height * other,
};
}
}
impl Mul<Size> for f64 {
type Output = Size;
#[inline]
fn mul(self, other: Size) -> Size {
other * self
}
}
impl Mul<f64> for Size {
type Output = Size;
#[inline]
fn mul(self, other: f64) -> Size {
Size {
width: self.width * other,
height: self.height * other,
}
}
}
impl From<(f64, f64)> for Size {
#[inline]
fn from(v: (f64, f64)) -> Size {
Size {
width: v.0,
height: v.1,
}
}
}
impl From<Size> for (f64, f64) {
#[inline]
fn from(v: Size) -> (f64, f64) {
(v.width, v.height)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display() {
let s = Size::new(-0.12345, 9.87654);
assert_eq!(format!("{}", s), "(-0.12345×9.87654)");
let s = Size::new(-0.12345, 9.87654);
assert_eq!(format!("{:+6.2}", s), "( -0.12× +9.88)");
}
}