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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use super::{Number, Unit};
use num_traits::one;
use std::fmt::{self, Display};
use std::ops::{Div, Mul};
#[derive(Clone, PartialEq, Eq)]
pub struct UnitSet {
units: Vec<(Unit, i8)>,
}
impl UnitSet {
pub fn scalar() -> Self {
UnitSet { units: vec![] }
}
pub fn is_none(&self) -> bool {
self.units.iter().all(|(u, _)| *u == Unit::None)
}
pub fn is_percent(&self) -> bool {
self.units == [(Unit::Percent, 1)]
}
pub fn is_compatible(&self, other: &Self) -> bool {
use std::collections::BTreeMap;
let dim = |t: &Self| {
t.units.iter().fold(
BTreeMap::<_, i8>::new(),
|mut a, (unit, power)| {
*a.entry(unit.dimension()).or_insert(0) += *power;
a
},
)
};
self.is_none() || other.is_none() || dim(self) == dim(other)
}
pub fn scale_to(&self, other: &UnitSet) -> Option<Number> {
if let [(u, 1)] = other.units.as_slice() {
self.scale_to_unit(u)
} else if other.is_none() {
self.scale_to_unit(&Unit::None)
} else {
None
}
}
pub fn scale_to_unit(&self, other: &Unit) -> Option<Number> {
if let [(u, 1)] = self.units.as_slice() {
u.scale_to(other)
} else if self.is_none() {
Unit::None.scale_to(other)
} else {
None
}
}
pub fn simplify(&mut self) -> Number {
let mut factor = one();
if self.units.len() > 1 {
for i in 1..(self.units.len()) {
let (a, b) = self.units.split_at_mut(i);
let (au, ap) = a.last_mut().unwrap();
for (bu, bp) in b {
if let Some(f) = bu.scale_to(au) {
factor = factor * f.powi(i32::from(*bp));
*ap += *bp;
*bp = 0;
}
}
}
}
self.units.retain(|(_u, p)| *p != 0);
factor
}
}
impl Div for &UnitSet {
type Output = UnitSet;
fn div(self, rhs: Self) -> Self::Output {
let mut result = self.clone();
'rhs: for (ru, rp) in &rhs.units {
for (lu, lp) in &mut result.units {
if lu == ru {
*lp -= rp;
continue 'rhs;
}
}
result.units.push((ru.clone(), -rp));
}
result.units.retain(|(_u, p)| *p != 0);
result
}
}
impl Mul for &UnitSet {
type Output = UnitSet;
fn mul(self, rhs: Self) -> Self::Output {
let mut result = self.clone();
'rhs: for (ru, rp) in &rhs.units {
for (lu, lp) in &mut result.units {
if lu == ru {
*lp += rp;
continue 'rhs;
}
}
result.units.push((ru.clone(), *rp));
}
result.units.retain(|(_u, p)| *p != 0);
result
}
}
impl From<Unit> for UnitSet {
fn from(unit: Unit) -> Self {
UnitSet {
units: if unit == Unit::None {
vec![]
} else {
vec![(unit, 1)]
},
}
}
}
impl Display for UnitSet {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
let pos: Vec<_> =
self.units.iter().filter(|(_u, p)| *p > 0).collect();
let neg: Vec<_> =
self.units.iter().filter(|(_u, p)| *p < 0).collect();
if let Some(((u, p), rest)) = pos.split_first() {
write_one(out, u, *p)?;
for (u, p) in rest {
out.write_str("*")?;
write_one(out, u, p.abs())?;
}
if let Some(((u, p), rest)) = neg.split_first() {
out.write_str("/")?;
write_one(out, u, p.abs())?;
for (u, p) in rest {
out.write_str("*")?;
write_one(out, u, p.abs())?;
}
}
} else {
match neg.split_first() {
None => (),
Some(((u, p), [])) => {
write_one(out, u, *p)?;
}
Some(((u, p), rest)) => {
out.write_str("(")?;
write_one(out, u, p.abs())?;
for (u, p) in rest {
out.write_str("*")?;
write_one(out, u, p.abs())?;
}
out.write_str(")^-1")?;
}
}
}
Ok(())
}
}
fn write_one(out: &mut fmt::Formatter, u: &Unit, p: i8) -> fmt::Result {
u.fmt(out)?;
if p != 1 {
write!(out, "^{}", p)?;
}
Ok(())
}
impl fmt::Debug for UnitSet {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
out.write_str("UnitSet ")?;
out.debug_list().entries(&self.units).finish()
}
}