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
use super::{Number, Rational, Unit, UnitSet};
use crate::output::{Format, Formatted};
use crate::Error;
use std::fmt::{self, Display};
use std::ops::{Div, Mul, Neg};
#[derive(Clone, Debug, Eq)]
pub struct Numeric {
pub value: Number,
pub unit: UnitSet,
}
impl Numeric {
pub fn new<V: Into<Number>, U: Into<UnitSet>>(value: V, unit: U) -> Self {
Numeric {
value: value.into(),
unit: unit.into(),
}
}
pub fn scalar(value: impl Into<Number>) -> Numeric {
Numeric {
value: value.into(),
unit: UnitSet::scalar(),
}
}
pub fn as_unit(&self, unit: Unit) -> Option<Number> {
self.unit
.scale_to_unit(&unit)
.map(|scale| &self.value * &scale)
}
pub fn as_unitset(&self, unit: &UnitSet) -> Option<Number> {
self.unit.scale_to(unit).map(|scale| &self.value * &scale)
}
pub fn as_unit_def(&self, unit: Unit) -> Option<Number> {
if self.is_no_unit() {
Some(self.value.clone())
} else {
self.as_unit(unit)
}
}
pub fn as_ratio(&self) -> Result<Rational, Error> {
self.value.as_ratio()
}
pub fn is_no_unit(&self) -> bool {
self.unit.is_none()
}
pub fn format(&self, format: Format) -> Formatted<Numeric> {
Formatted {
value: self,
format,
}
}
}
impl PartialEq for Numeric {
fn eq(&self, other: &Numeric) -> bool {
self.partial_cmp(other) == Some(std::cmp::Ordering::Equal)
}
}
impl PartialOrd for Numeric {
fn partial_cmp(&self, other: &Numeric) -> Option<std::cmp::Ordering> {
if self.unit == other.unit {
self.value.partial_cmp(&other.value)
} else if let Some(scaled) = other.as_unitset(&self.unit) {
self.value.partial_cmp(&scaled)
} else {
None
}
}
}
impl Neg for &Numeric {
type Output = Numeric;
fn neg(self) -> Self::Output {
Numeric {
value: -&self.value,
unit: self.unit.clone(),
}
}
}
impl Div for &Numeric {
type Output = Numeric;
fn div(self, rhs: Self) -> Self::Output {
Numeric {
value: &self.value / &rhs.value,
unit: &self.unit / &rhs.unit,
}
}
}
impl Mul for &Numeric {
type Output = Numeric;
fn mul(self, rhs: Self) -> Self::Output {
Numeric {
value: &self.value * &rhs.value,
unit: &self.unit * &rhs.unit,
}
}
}
impl<'a> Display for Formatted<'a, Numeric> {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
let mut unit = self.value.unit.clone();
let value = &self.value.value * &unit.simplify();
value.format(self.format).fmt(out)?;
unit.fmt(out)
}
}