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
use core::{
    fmt::Display,
    marker::ConstParamTy,
    ops::{Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Sub, SubAssign},
};

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

use super::*;

impl ConstParamTy for SI {}

/// A value with dimensionality
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Quantity<V, const UNITS: SI>(pub V);

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

        Ok(())
    }
}

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

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

    /// Convert a `Quantity` to a different set of units
    ///
    /// Okay
    /// ```
    /// # #![feature(generic_const_exprs)]
    /// # use const_units::{Quantity, units::{minute, second}};
    /// // Converting minutes to seconds
    /// assert_eq!(Quantity::<f64, { minute }>(1.).convert_to::<{ second }>(), Quantity::<f64, { second }>(60.))
    /// ```
    ///
    /// Broken
    /// ```compile_fail
    /// # #![feature(generic_const_exprs)]
    /// # use const_units::{Quantity, units::{meter, second}};
    /// // Can't convert meters to seconds
    /// assert_eq!(Quantity::<f64, { meter }>(1.).convert_to::<{ second }>(), Quantity::<f64, { second }>(1.))
    /// ```
    pub fn convert_to<const NEW_UNITS: SI>(self) -> Quantity<V, NEW_UNITS>
    where
        assertion::Bool<{ UNITS.same_dimension(NEW_UNITS) }>: assertion::True,
        V: Mul<V, Output = V> + Div<V, Output = V> + NumCast,
    {
        let scale = UNITS.div(NEW_UNITS).scale;

        Quantity(
            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"),
        )
    }
}

#[cfg(feature = "dyn")]
impl<V, const UNITS: SI> From<Quantity<V, UNITS>> for crate::DynQuantity<V> {
    fn from(value: Quantity<V, UNITS>) -> Self {
        crate::DynQuantity(value.0, UNITS)
    }
}

/// Utility types for bounding const-generics by a boolean expression
pub mod assertion {
    /// Implemented by `Bool` if COND is true
    pub trait True {}

    /// Represents a constant boolean value, implements `True` if COND is true
    pub struct Bool<const COND: bool>();

    impl True for Bool<true> {}
}

impl<V: Display, const UNITS: SI> Quantity<V, UNITS> {
    /// Write the quantity to a formatter using the given units. Must be parseable by `crate::si`.
    ///
    /// For copy/paste purposes: `⋅`
    #[allow(private_bounds)]
    pub fn write_as<const AS: &'static str>(
        &self,
        f: &mut core::fmt::Formatter,
    ) -> Result<(), core::fmt::Error>
    where
        assertion::Bool<{ crate::si(AS).const_eq(UNITS) }>: assertion::True,
    {
        write!(f, "{} {AS}", 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::{Quantity, units::{newton}};
    /// assert_eq!(Quantity::<f64, newton>(1.).format_as::<"N">(), "1 N");
    /// ```
    ///
    /// Broken:
    /// ```compile_fail
    /// # use const_units::{Quantity, units::{newton}};
    /// assert_eq!(Quantity::<f64, newton>(1.).format_as::<"K">(), "1 K");
    /// ```
    #[allow(private_bounds)]
    #[cfg(any(feature = "std", test))]
    pub fn format_as<const AS: &'static str>(&self) -> std::string::String
    where
        assertion::Bool<{ crate::si(AS).const_eq(UNITS) }>: assertion::True,
    {
        format!("{} {AS}", self.0)
    }
}

/// Arbitrary math operations are only reasonable on dimensionless values
impl<V> Deref for Quantity<V, DIMENSIONLESS> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Arbitrary math operations are only reasonable on dimensionless values
impl<V> DerefMut for Quantity<V, DIMENSIONLESS> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Units must be the same for addition
impl<R, O, T: Add<R, Output = O>, const UNITS: SI> Add<Quantity<R, UNITS>> for Quantity<T, UNITS> {
    type Output = Quantity<O, UNITS>;

    fn add(self, rhs: Quantity<R, UNITS>) -> Self::Output {
        Quantity(self.0 + rhs.0)
    }
}

/// Units must be the same for addition
impl<R, O, T: Sub<R, Output = O>, const UNITS: SI> Sub<Quantity<R, UNITS>> for Quantity<T, UNITS> {
    type Output = Quantity<O, UNITS>;

    fn sub(self, rhs: Quantity<R, UNITS>) -> Self::Output {
        Quantity(self.0 - rhs.0)
    }
}

/// Units must be the same for addition
impl<R, T: AddAssign<R>, const UNITS: SI> AddAssign<Quantity<R, UNITS>> for Quantity<T, UNITS> {
    fn add_assign(&mut self, rhs: Quantity<R, UNITS>) {
        self.0 += rhs.0;
    }
}

/// Units must be the same for addition
impl<R, T: SubAssign<R>, const UNITS: SI> SubAssign<Quantity<R, UNITS>> for Quantity<T, UNITS> {
    fn sub_assign(&mut self, rhs: Quantity<R, UNITS>) {
        self.0 -= rhs.0;
    }
}

/// Scaling by a dimensionless value is OK
impl<R, T: MulAssign<R>, const UNITS: SI> MulAssign<Quantity<R, DIMENSIONLESS>>
    for Quantity<T, UNITS>
{
    fn mul_assign(&mut self, rhs: Quantity<R, DIMENSIONLESS>) {
        self.0 *= rhs.0;
    }
}

/// Scaling by a dimensionless value is OK
impl<R, T: DivAssign<R>, const UNITS: SI> DivAssign<Quantity<R, DIMENSIONLESS>>
    for Quantity<T, UNITS>
{
    fn div_assign(&mut self, rhs: Quantity<R, DIMENSIONLESS>) {
        self.0 /= rhs.0;
    }
}

// https://stackoverflow.com/questions/66361365/unconstrained-generic-constant-when-adding-const-generics

/// Multiplications multiplies the units
impl<R, O, T: Mul<R, Output = O>, const LHS_UNITS: SI, const RHS_UNITS: SI>
    Mul<Quantity<R, RHS_UNITS>> for Quantity<T, LHS_UNITS>
where
    Quantity<O, { SI::mul(LHS_UNITS, RHS_UNITS) }>: Sized,
{
    type Output = Quantity<O, { SI::mul(LHS_UNITS, RHS_UNITS) }>;

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

/// Division divides the units
impl<R, O, T: Div<R, Output = O>, const LHS_UNITS: SI, const RHS_UNITS: SI>
    Div<Quantity<R, RHS_UNITS>> for Quantity<T, LHS_UNITS>
where
    Quantity<O, { SI::div(LHS_UNITS, RHS_UNITS) }>: Sized,
{
    type Output = Quantity<O, { SI::div(LHS_UNITS, RHS_UNITS) }>;

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