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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use core::{
    fmt::Display,
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign},
};

use num::{traits::Pow, NumCast};

use super::*;

// Note: PartialEq and Eq are implemented on errors for assert_eq!

/// Returned when incompatible units are used together
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InconsistentUnits {
    expected: SI,
    found: SI,
}

impl Display for InconsistentUnits {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("Expected ")?;
        self.expected.fmt(f)?;
        f.write_str("; Found ")?;
        self.found.fmt(f)
    }
}

/// Returned when `DynQuantity.format_as` fails
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatAsError<'a> {
    IncompatibleUnits(InconsistentUnits),
    ParseError(crate::ParseError<'a>),
}

impl<'a> Display for FormatAsError<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::IncompatibleUnits(v) => v.fmt(f),
            Self::ParseError(v) => v.fmt(f),
        }
    }
}

// TODO: Change when https://github.com/rust-lang/rust/issues/103765
#[cfg(feature = "std")]
impl std::error::Error for InconsistentUnits {}
#[cfg(feature = "std")]
impl<'a> std::error::Error for FormatAsError<'a> {}

/// A value with dimensionality, checked at runtime
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DynQuantity<V>(pub V, pub SI);

impl<V: Display> Display for DynQuantity<V> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.0.fmt(f)?;
        f.write_str(" ")?;
        self.1.fmt(f)?;

        Ok(())
    }
}

impl<V> DynQuantity<V> {
    /// Take the power to an integer
    ///
    /// ```
    /// # use const_units::{DynQuantity, units::{meter}};
    /// assert_eq!(DynQuantity(2., meter).powi(2), DynQuantity(4., meter.powi(2)));
    /// ```
    pub fn powi(self, exp: i32) -> DynQuantity<V::Output>
    where
        V: Pow<i32>,
    {
        DynQuantity(self.0.pow(exp), self.1.powi(exp))
    }

    /// Take the power to a fraction
    ///
    /// ```
    /// # use const_units::{DynQuantity, units::{meter}};
    /// assert_eq!(DynQuantity(4., meter).powf((1, 2)), DynQuantity(2., meter.powf((1, 2))));
    /// ```
    pub fn powf(self, exp: (i32, u32)) -> DynQuantity<V::Output>
    where
        V: Pow<f64>,
    {
        DynQuantity(self.0.pow(exp.0 as f64 / exp.1 as f64), self.1.powf(exp))
    }

    /// Convert a `DynQuantity` to a different set of units
    ///
    /// Okay
    /// ```
    /// # use const_units::{DynQuantity, units::{minute, second, meter}};
    /// // Converting minutes to seconds
    /// assert_eq!(DynQuantity(1., minute).convert_to(second), Ok(DynQuantity(60., second)));
    /// // Can't convert meters to seconds
    /// assert!(DynQuantity(1., meter).convert_to(second).is_err())
    /// ```
    pub fn convert_to(mut self, mut new_units: SI) -> Result<DynQuantity<V>, InconsistentUnits>
    where
        V: Mul<V, Output = V> + Div<V, Output = V> + NumCast,
    {
        if !self.1.same_dimension(new_units) {
            self.1.scale = (1, 1);
            new_units.scale = (1, 1);
            return Err(InconsistentUnits {
                expected: self.1,
                found: new_units,
            });
        }

        let scale = self.1.div(new_units).scale;

        Ok(DynQuantity(
            self.0 * V::from(scale.0).expect("Casting the scale value to type V to work")
                / V::from(scale.1).expect("Casting the scale value to type V to work"),
            new_units,
        ))
    }

    /// Add two `DynQuantity`s. Will return an error if they have different units.
    pub fn checked_add<R>(
        self,
        rhs: DynQuantity<R>,
    ) -> Result<DynQuantity<<V as Add<R>>::Output>, InconsistentUnits>
    where
        V: Add<R>,
    {
        if self.1 != rhs.1 {
            return Err(InconsistentUnits {
                expected: self.1,
                found: rhs.1,
            });
        }

        Ok(DynQuantity(self.0 + rhs.0, self.1))
    }

    /// Subtract two `DynQuantity`s. Will return an error if they have different units.
    pub fn checked_sub<R>(
        self,
        rhs: DynQuantity<R>,
    ) -> Result<DynQuantity<<V as Sub<R>>::Output>, InconsistentUnits>
    where
        V: Sub<R>,
    {
        if self.1 != rhs.1 {
            return Err(InconsistentUnits {
                expected: self.1,
                found: rhs.1,
            });
        }

        Ok(DynQuantity(self.0 - rhs.0, self.1))
    }
}

impl<V: Display> DynQuantity<V> {
    /// Write the quantity to a formatter using the given units. Must be parseable by `crate::si`. Will return `core::fmt::Error` if `units` couldn't be parsed or if they aren't equal to the `DynQuantity`'s units.
    ///
    /// For copy/paste purposes: `⋅`
    #[allow(private_bounds)]
    pub fn write_as(
        &self,
        units: &'static str,
        f: &mut core::fmt::Formatter,
    ) -> Result<(), core::fmt::Error> {
        if Ok(self.1) != si_checked(units) {
            return Err(core::fmt::Error);
        }

        write!(f, "{} {units}", self.0)
    }

    /// Format the quantity using the given units. Must be parseable by `crate::si`.
    ///
    /// Multiplication symbol for copy/paste purposes: `⋅`
    ///
    /// Okay:
    /// ```
    /// # use const_units::{DynQuantity, units::{newton}};
    /// assert_eq!(DynQuantity(1., newton).format_as("N"), Ok("1 N".to_owned()));
    /// assert!(DynQuantity(1., newton).format_as("K").is_err());
    /// ```
    #[allow(private_bounds)]
    #[cfg(any(feature = "std", test))]
    pub fn format_as(&self, units: &'static str) -> Result<std::string::String, FormatAsError> {
        let si = match si_checked(units) {
            Ok(v) => v,
            Err(e) => return Err(FormatAsError::ParseError(e)),
        };

        if self.1 != si {
            return Err(FormatAsError::IncompatibleUnits(InconsistentUnits {
                expected: self.1,
                found: si,
            }));
        }

        Ok(format!("{} {units}", self.0))
    }
}

#[cfg(feature = "const")]
impl<V, const UNITS: SI> TryFrom<DynQuantity<V>> for crate::Quantity<V, UNITS> {
    type Error = InconsistentUnits;

    fn try_from(value: DynQuantity<V>) -> Result<Self, Self::Error> {
        if value.1 != UNITS {
            return Err(InconsistentUnits {
                expected: UNITS,
                found: value.1,
            });
        }

        Ok(crate::Quantity(value.0))
    }
}

impl<V: PartialOrd> PartialOrd for DynQuantity<V> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        if self.1 != other.1 {
            return None;
        }

        self.0.partial_cmp(&other.0)
    }
}

impl<R, T: Add<R>> Add<DynQuantity<R>> for DynQuantity<T> {
    type Output = DynQuantity<<T as Add<R>>::Output>;

    fn add(self, rhs: DynQuantity<R>) -> Self::Output {
        match self.checked_add(rhs) {
            Ok(v) => v,
            Err(e) => panic!("{e}"),
        }
    }
}

/// Units must be the same for addition
impl<R, T: Sub<R>> Sub<DynQuantity<R>> for DynQuantity<T> {
    type Output = DynQuantity<<T as Sub<R>>::Output>;

    fn sub(self, rhs: DynQuantity<R>) -> Self::Output {
        match self.checked_sub(rhs) {
            Ok(v) => v,
            Err(e) => panic!("{e}"),
        }
    }
}

/// Units must be the same for addition
impl<R, T: AddAssign<R>> AddAssign<DynQuantity<R>> for DynQuantity<T> {
    fn add_assign(&mut self, rhs: DynQuantity<R>) {
        if self.1 != rhs.1 {
            panic!(
                "{}",
                InconsistentUnits {
                    expected: self.1,
                    found: rhs.1
                }
            );
        }

        self.0 += rhs.0
    }
}

/// Units must be the same for addition
impl<R, T: SubAssign<R>> SubAssign<DynQuantity<R>> for DynQuantity<T> {
    fn sub_assign(&mut self, rhs: DynQuantity<R>) {
        if self.1 != rhs.1 {
            panic!(
                "{}",
                InconsistentUnits {
                    expected: self.1,
                    found: rhs.1
                }
            );
        }

        self.0 -= rhs.0
    }
}

impl<R, T: MulAssign<R>> MulAssign<DynQuantity<R>> for DynQuantity<T> {
    fn mul_assign(&mut self, rhs: DynQuantity<R>) {
        if rhs.1 != DIMENSIONLESS {
            panic!(
                "{}",
                InconsistentUnits {
                    expected: DIMENSIONLESS,
                    found: rhs.1,
                }
            );
        }

        self.0 *= rhs.0;
    }
}

impl<R, T: DivAssign<R>> DivAssign<DynQuantity<R>> for DynQuantity<T> {
    fn div_assign(&mut self, rhs: DynQuantity<R>) {
        if rhs.1 != DIMENSIONLESS {
            panic!(
                "{}",
                InconsistentUnits {
                    expected: DIMENSIONLESS,
                    found: rhs.1,
                }
            );
        }

        self.0 /= rhs.0;
    }
}

impl<R, T: Mul<R>> Mul<DynQuantity<R>> for DynQuantity<T> {
    type Output = DynQuantity<<T as Mul<R>>::Output>;

    fn mul(self, rhs: DynQuantity<R>) -> Self::Output {
        DynQuantity(self.0 * rhs.0, self.1.mul(rhs.1))
    }
}

impl<R, T: Div<R>> Div<DynQuantity<R>> for DynQuantity<T> {
    type Output = DynQuantity<<T as Div<R>>::Output>;

    fn div(self, rhs: DynQuantity<R>) -> Self::Output {
        DynQuantity(self.0 / rhs.0, self.1.div(rhs.1))
    }
}