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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// quan.rs
//
// Copyright (C) 2021-2022  Douglas P Lau
//
use core::fmt;
use core::marker::PhantomData;
use core::ops::{Add, Div, Mul, Sub};

/// Measure of mass.
///
/// Mass is a "base quantity", with units such as `kg` and `lb`.
///
/// ## Example
///
/// ```rust
/// use mag::mass::{kg, lb};
///
/// let a = 2.5 * kg;
/// assert_eq!(a.to_string(), "2.5 kg");
/// assert_eq!(a + 4.5 * kg, 7 * kg);
/// assert_eq!(a.to(), 5.511556554621939 * lb);
/// ```
///
/// # Example: Solar Mass Units
/// ```rust
/// use mag::{declare_unit, mass::kg, quan::Mass};
///
/// declare_unit!(M, "M☉", Mass, 1.988_47e33,);
///
/// let sun = 1 * M;
/// assert_eq!(sun.to_string(), "1 M☉");
/// assert_eq!(sun.to(), 1.988_47e30 * kg);
/// ```
///
/// [mass]: struct.Mass.html
/// [unit]: ../mass/index.html
/// [to]: struct.Quantity.html#method.to
///
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct Mass;

/// Thermodynamic _temperature_.
///
/// Temperature is a "base quantity" with units such as DegC and DegF.
///
/// ## Example
///
/// ```rust
/// use mag::temp::{DegC, DegF};
///
/// let a = 98.6 * DegF;
/// assert_eq!(a.to_string(), "98.6 °F");
/// assert_eq!(a.to(), 37 * DegC);
/// assert_eq!((22.8 * DegC).to_string(), "22.8 °C");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct Temperature;

/// Unit of measure
pub trait Unit {
    /// Unit label
    const LABEL: &'static str;

    /// Factor to convert to base unit
    const FACTOR: f64;

    /// Value of (absolute) zero
    const ZERO: f64;

    /// Measure (length, mass, etc.)
    type Measure;

    /// Convert a value to another unit of the same measure
    fn convert<T>(val: f64) -> f64
    where
        T: Unit<Measure = Self::Measure>,
    {
        val * (Self::FACTOR / T::FACTOR)
    }
}

/// Define a custom [unit] of measure.
///
/// * `unit` Unit struct name
/// * `label` Standard unit label
/// * `measure` A base or derived measure
/// * `factor` Factor to convert
/// * `zero` (Absolute) zero point
///
/// [Unit]: quan/trait.Unit.html
#[macro_export]
macro_rules! declare_unit {
    ($(#[$doc:meta])*
        $unit:ident,
        $label:expr,
        $measure:ident,
        $factor:expr,
    ) => {
        $(#[$doc])*
        #[allow(non_camel_case_types)]
        #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
        pub struct $unit;

        impl $crate::quan::Unit for $unit {
            type Measure = $measure;
            const LABEL: &'static str = $label;
            const FACTOR: f64 = $factor;
            const ZERO: f64 = 0.0;
        }

        impl core::ops::Mul<$unit> for f64 {
            type Output = $crate::quan::Quantity<$unit>;
            fn mul(self, _unit: $unit) -> Self::Output {
                Self::Output::new(self)
            }
        }

        impl core::ops::Mul<$unit> for i32 {
            type Output = $crate::quan::Quantity<$unit>;
            fn mul(self, _unit: $unit) -> Self::Output {
                Self::Output::new(self)
            }
        }
    };
    ($(#[$doc:meta])*
        $unit:ident,
        $label:expr,
        $measure:ident,
        $factor:expr,
        $zero:expr,
    ) => {
        $(#[$doc])*
        #[allow(non_camel_case_types)]
        #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
        pub struct $unit;

        impl $crate::quan::Unit for $unit {
            type Measure = $measure;
            const LABEL: &'static str = $label;
            const FACTOR: f64 = $factor;
            const ZERO: f64 = $zero;

            /// Convert a value to another unit of the same measure
            fn convert<T>(val: f64) -> f64
            where
                T: $crate::quan::Unit<Measure = Self::Measure>,
            {
                let v = (val - Self::ZERO) * Self::FACTOR;
                v / T::FACTOR + T::ZERO
            }
        }

        impl core::ops::Mul<$unit> for f64 {
            type Output = $crate::quan::Quantity<$unit>;
            fn mul(self, _unit: $unit) -> Self::Output {
                Self::Output::new(self)
            }
        }

        impl core::ops::Mul<$unit> for i32 {
            type Output = $crate::quan::Quantity<$unit>;
            fn mul(self, _unit: $unit) -> Self::Output {
                Self::Output::new(self)
            }
        }
    };
}

/// Quantity is a value with an associated unit
///
/// Units must be the same for operations with two Quantity operands.  The [to]
/// method can be used for conversion.
///
/// ## Operations
///
/// * f64 `*` [Unit] `=> Quantity<Unit>`
/// * i32 `*` [Unit] `=> Quantity<Unit>`
/// * `Quantity<Unit> + Quantity<Unit> => Quantity<Unit>`
/// * `Quantity<Unit> - Quantity<Unit> => Quantity<Unit>`
///
/// [to]: #method.to
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct Quantity<U>
where
    U: Unit,
{
    /// Quantity of units
    pub value: f64,

    /// Unit of measure
    unit: PhantomData<U>,
}

impl<U> Quantity<U>
where
    U: Unit,
{
    /// Create a new quantity
    pub fn new<V>(value: V) -> Self
    where
        V: Into<f64>,
    {
        Self {
            value: value.into(),
            unit: PhantomData,
        }
    }

    /// Convert quantity to the specified units
    pub fn to<T>(self) -> Quantity<T>
    where
        T: Unit<Measure = <U>::Measure>,
    {
        Quantity::new(U::convert::<T>(self.value))
    }
}

impl<U> fmt::Display for Quantity<U>
where
    U: Unit,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.value.fmt(f)?;
        write!(f, " {}", U::LABEL)
    }
}

impl<U> Add for Quantity<U>
where
    U: Unit,
{
    type Output = Self;
    fn add(self, other: Self) -> Self::Output {
        Self::new(self.value + other.value)
    }
}

impl<U> Sub for Quantity<U>
where
    U: Unit,
{
    type Output = Self;
    fn sub(self, other: Self) -> Self::Output {
        Self::new(self.value - other.value)
    }
}

/// Marker trait for units which can be scaled by multiplication (or division)
///
/// * `Quantity<Unit> * f64 => Quantity<Unit>`
/// * `f64 * Quantity<Unit> => Quantity<Unit>`
/// * `Quantity<Unit> / f64 => Quantity<Unit>`
pub trait MulUnit {}

impl MulUnit for Mass {}

impl<U, M, V> Mul<V> for Quantity<U>
where
    U: Unit<Measure = M>,
    M: MulUnit,
    V: Into<f64>,
{
    type Output = Self;
    fn mul(self, scalar: V) -> Self::Output {
        Self::new(self.value * scalar.into())
    }
}

impl<U, M> Mul<Quantity<U>> for f64
where
    U: Unit<Measure = M>,
    M: MulUnit,
{
    type Output = Quantity<U>;
    fn mul(self, quan: Self::Output) -> Self::Output {
        Self::Output::new(self * quan.value)
    }
}

impl<U, M> Div<f64> for Quantity<U>
where
    U: Unit<Measure = M>,
    M: MulUnit,
{
    type Output = Self;
    fn div(self, scalar: f64) -> Self::Output {
        Self::new(self.value / scalar)
    }
}