dana 0.4.0

Compile-time dimensional analysis via generic types.
Documentation
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! The link between dimensionless [`Value`]s and dimensional [`Unit`]s.

#[cfg(feature = "rand")]
pub mod rand;

mod qty_from;

use core::{
    iter::Sum,
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
};
use num_traits::{Inv, MulAdd, NumCast, Pow, real::Real, Signed, Zero};
use crate::{units::{traits::*, UnitAnon}, Value};


type ValueDefault = f64;


/// A [`Quantity`] with an [anonymous unit](UnitAnon).
pub type QuantityAnon<D, V = ValueDefault> = Quantity<UnitAnon<D>, V>;


/// Dimensionless [`Value`] value paired with a dimensional [`Unit`].
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Quantity<U: Unit, V: Value = ValueDefault> {
    /// Dimensionless value. This defines *how much* of the unit is represented
    ///     by the quantity.
    pub value: V,
    /// Dimensional unit. This defines *what* is represented by the quantity.
    pub unit: U,
}

impl<U: Unit, V: Value> Quantity<U, V> {
    /// Construct a new [`Quantity`] from [`Unit`] and [`Value`].
    pub const fn new(unit: U, value: V) -> Self {
        Self { value, unit }
    }

    /// Change the unit of this quantity in-place to the base unit.
    pub fn set_base(&mut self) where
        V: MulAssign,
    {
        self.set_unit(U::base())
    }

    /// Change the unit of this quantity in-place.
    pub fn set_unit(&mut self, unit: U) where
        V: MulAssign,
    {
        self.value *= self.unit.scale_factor_v(unit).unwrap();
        self.unit = unit;
    }

    /// Return `true` if another quantity is within the given limit of this one.
    pub fn almost_eq<W>(self, rhs: Quantity<W, V>, limit: V) -> bool where
        V: Signed + PartialOrd,
        W: Unit<Dim=U::Dim>,
    {
        (self - rhs).abs().value <= limit
    }

    /// Return an equivalent quantity with its unit [anonymized](UnitAnon).
    pub fn with_anonymous(self) -> QuantityAnon<U::Dim, V> {
        self.unit.anonymous().quantity(self.value)
    }

    /// Return an equivalent quantity with the base unit of the same type.
    pub fn with_base(self) -> Self { self.with_unit(U::base()) }

    /// Return an equivalent quantity with the given unit of the same type.
    pub fn with_unit(self, unit: U) -> Self {
        if unit == self.unit {
            self
        } else {
            Self {
                value: self.value_as(unit),
                unit,
            }
        }
    }

    /// Return the value of this quantity, scaled to another unit.
    pub fn value_as<W: Unit<Dim=U::Dim>>(self, unit: W) -> V {
        self.value * self.unit.scale_factor_v(unit).unwrap()
    }

    /// Return the value of this quantity, scaled to the base unit of its type.
    pub fn value_as_base(self) -> V {
        self.value_as(U::base())
    }

    /// Return an equivalent quantity with its value as close as possible to
    ///     being within the range `[1,1000)`.
    ///
    /// This is done by repeatedly "stepping" the unit up or down. As such, it
    ///     may be quite expensive for more complex compound units.
    pub fn normalize(self) -> Self where
        U: UnitStep,
        V: Real,
    {
        if self.value.is_zero() {
            self.with_base()
        } else {
            let limit = crate::_conv_i32(3);
            let mut log: V = self.value.log10();
            let mut unit: U = self.unit;

            if log.is_sign_positive() {
                while log >= limit {
                    let Some(next) = unit.step_up() else { break };

                    let log_rel = unit.scale_factor_v::<U, V>(next).unwrap().log10();
                    let log_new = log + log_rel;

                    if log_new >= V::zero() {
                        log = log_new;
                        unit = next;
                    } else {
                        break;
                    }
                }
            } else {
                while log < V::zero() {
                    let Some(next) = unit.step_down() else { break };

                    let log_rel = unit.scale_factor_v::<U, V>(next).unwrap().log10();
                    let log_new = log + log_rel;

                    //  TODO: `<=` or `<`?
                    if log_new <= limit {
                        log = log_new;
                        unit = next;
                    } else {
                        break;
                    }
                }
            }

            self.with_unit(unit)
        }
    }

    /// Return an equivalent quantity with the SI unit nearest to the current
    ///     unit. If the current unit is already an SI unit, it will not be
    ///     changed.
    pub fn into_si(self) -> Self where
        U: UnitMixed,
    {
        let si: U = self.unit.to_si();

        if self.unit == si {
            self
        } else {
            self.with_unit(si)
        }
    }

    /// Return a [`QtySimd`](crate::simd::QtySimd) array, for SIMD operations,
    ///     populated by this quantity.
    #[cfg(feature = "simd")]
    pub fn to_simd<const N: usize, S>(self) -> crate::simd::QtySimd<U, V, N, S> where
        core::simd::LaneCount<N>: core::simd::SupportedLaneCount,
        V: crate::simd::QtySimdValue,
        S: crate::simd::QtySimdScale,
        f64: num_traits::AsPrimitive<S>,
    {
        crate::simd::QtySimd::from_qty(self)
    }
}


//region Methods for mathematical operations.
impl<U: Unit, V: Value> Quantity<U, V> {
    //region Positive exponents.
    /// Return the square of this quantity.
    pub fn squared(self) -> Quantity<<U as CanSquare>::Output, <V as Mul<V>>::Output> where
        U: CanSquare,
    {
        Quantity {
            value: self.value.clone() * self.value,
            unit: self.unit.squared(),
        }
    }

    /// Return the cube of this quantity.
    pub fn cubed(self) -> Quantity<<U as CanCube>::Output, <V as Mul<V>>::Output> where
        U: CanCube,
    {
        Quantity {
            value: self.value.clone() * self.value.clone() * self.value,
            unit: self.unit.cubed(),
        }
    }

    /// Return an arbitrary integer power of this quantity.
    pub fn pow<const E: i32>(self) -> Quantity<
        U::Output,
        <V as Pow<V>>::Output,
    > where
        U: CanPow<E>,
        V: Pow<V>,
        <V as Pow<V>>::Output: Value,
    {
        Quantity {
            value: self.value.pow(crate::_conv_i32(E)),
            unit: self.unit.pow(),
        }
    }
    //endregion

    //region Roots.
    /// Return the square root of this quantity.
    pub fn sqrt(self) -> Quantity<<U as CanSquareRoot>::Output, V> where
        U: CanSquareRoot,
        V: Real,
    {
        Quantity {
            value: self.value.sqrt(),
            unit: self.unit.sqrt(),
        }
    }

    /// Return the cube root of this quantity.
    pub fn cbrt(self) -> Quantity<<U as CanCubeRoot>::Output, V> where
        U: CanCubeRoot,
        V: Real,
    {
        Quantity {
            value: self.value.cbrt(),
            unit: self.unit.cbrt(),
        }
    }

    /// Return the root to an arbitrary integer degree of this quantity.
    pub fn root<const D: i32>(self) -> Quantity<
        U::Output,
        <V as Pow<<V as Inv>::Output>>::Output,
    > where
        U: CanRoot<D>,
        V: Inv + Pow<<V as Inv>::Output>,
        <V as Pow<<V as Inv>::Output>>::Output: Value,
    {
        Quantity {
            value: self.value.pow(crate::_conv_i32::<V>(D).inv()),
            unit: self.unit.root(),
        }
    }
    //endregion
}
//endregion


//region Methods for scalar operations.
impl<U: Unit, V: Value> Quantity<U, V> {
    /// Return an equivalent quantity, with the value converted to another type
    ///     via [`Into::into`].
    pub fn value_into<X>(self) -> Quantity<U, X> where
        V: Into<X>,
        X: Value,
    {
        Quantity::new(self.unit, self.value.into())
    }

    /// Return an equivalent quantity, with the value converted to another type
    ///     via [`TryInto::try_into`].
    pub fn value_try_into<X>(self) -> Result<Quantity<U, X>, V::Error> where
        V: TryInto<X>,
        X: Value,
    {
        Ok(Quantity::new(self.unit, self.value.try_into()?))
    }
}
//endregion


//region Methods for unit operations.
/// Unit conversion.
impl<U: Unit, V: Value> Quantity<U, V> {
    /// Perform trait-based unit conversion to the default of a unit type. This
    ///     kind of conversion can cross between [`Unit`] types.
    pub fn convert<W: Unit>(self) -> Quantity<W, V> where
        U: ConvertInto<W>,
    {
        self.convert_to(W::base())
    }

    /// Perform trait-based unit conversion to a specific unit. This kind of
    ///     conversion can cross between [`Unit`] types.
    pub fn convert_to<W: Unit>(self, unit: W) -> Quantity<W, V> where
        U: ConvertInto<W>,
    {
        self.unit.conversion_into(unit).quantity(self.value)
    }

    /// Cancel out units entirely, returning a scalar.
    pub fn cancel(self) -> V where
        U: Cancel,
    {
        self.value * self.unit.cancel()
    }
}

impl<U: Unit, V: Value> Quantity<crate::units::UnitPow<U, typenum::P1>, V> where
    U::Dim: crate::dimension::CanDimPowType<typenum::P1>,
{
    /// Return an equivalent quantity with its exponent removed.
    pub fn cancel_exponent(self) -> Quantity<U, V> {
        self.unit.0.quantity(self.value)
    }
}
//endregion


//region Standard library operators.
//region Negation.
impl<U: Unit, V: Value> Neg for Quantity<U, V> where
    V: Neg, <V as Neg>::Output: Value,
{
    type Output = Quantity<U, <V as Neg>::Output>;

    fn neg(self) -> Self::Output {
        Quantity {
            value: self.value.neg(),
            unit: self.unit,
        }
    }
}
//endregion

//region Addition/subtraction between same-unit quantities.
impl<U: Unit, V: Value, W: Unit, X: Value> Add<Quantity<W, X>> for Quantity<U, V> where
    W: ConvertInto<U>,
    V: Add<X>, <V as Add<X>>::Output: Value,
{
    type Output = Quantity<U, <V as Add<X>>::Output>;

    fn add(self, rhs: Quantity<W, X>) -> Self::Output {
        Quantity {
            value: self.value + rhs.convert_to(self.unit).value,
            unit: self.unit,
        }
    }
}

impl<U: Unit, V: Value, W: Unit, X: Value> Sub<Quantity<W, X>> for Quantity<U, V> where
    W: ConvertInto<U>,
    V: Sub<X>, <V as Sub<X>>::Output: Value,
{
    type Output = Quantity<U, <V as Sub<X>>::Output>;

    fn sub(self, rhs: Quantity<W, X>) -> Self::Output {
        Quantity {
            value: self.value - rhs.convert_to(self.unit).value,
            unit: self.unit,
        }
    }
}

impl<U: Unit, V: Value, W: Unit, X: Value> AddAssign<Quantity<W, X>> for Quantity<U, V> where
    W: ConvertInto<U>,
    V: AddAssign<X>,
{
    fn add_assign(&mut self, rhs: Quantity<W, X>) {
        self.value += rhs.convert_to(self.unit).value;
    }
}

impl<U: Unit, V: Value, W: Unit, X: Value> SubAssign<Quantity<W, X>> for Quantity<U, V> where
    W: ConvertInto<U>,
    V: SubAssign<X>,
{
    fn sub_assign(&mut self, rhs: Quantity<W, X>) {
        self.value -= rhs.convert_to(self.unit).value;
    }
}
//endregion

//region Division/multiplication between quantities.
impl<U: Unit, V: Value, W: Unit, X: Value> Div<Quantity<W, X>> for Quantity<U, V> where
    U: Div<W>, <U as Div<W>>::Output: Unit,
    V: Div<X>, <V as Div<X>>::Output: Value,
{
    type Output = Quantity<U::Output, <V as Div<X>>::Output>;

    fn div(self, rhs: Quantity<W, X>) -> Self::Output {
        Quantity {
            value: self.value / rhs.value,
            unit: self.unit / rhs.unit,
        }
    }
}

impl<U: Unit, V: Value, W: Unit, X: Value> Mul<Quantity<W, X>> for Quantity<U, V> where
    U: Mul<W>, <U as Mul<W>>::Output: Unit,
    V: Mul<X>, <V as Mul<X>>::Output: Value,
{
    type Output = Quantity<U::Output, <V as Mul<X>>::Output>;

    fn mul(self, rhs: Quantity<W, X>) -> Self::Output {
        Quantity {
            value: self.value * rhs.value,
            unit: self.unit * rhs.unit,
        }
    }
}
//endregion

//region Division/multiplication between quantities and scalars.
impl<U: Unit, V: Value, X: Value> Div<X> for Quantity<U, V> where
    V: Div<X>, <V as Div<X>>::Output: Value,
{
    type Output = Quantity<U, <V as Div<X>>::Output>;

    fn div(self, rhs: X) -> Self::Output {
        Quantity {
            value: self.value / rhs,
            unit: self.unit,
        }
    }
}

impl<U: Unit, V: Value, X: Value> Mul<X> for Quantity<U, V> where
    V: Mul<X>, <V as Mul<X>>::Output: Value,
{
    type Output = Quantity<U, <V as Mul<X>>::Output>;

    fn mul(self, rhs: X) -> Self::Output {
        Quantity {
            value: self.value * rhs,
            unit: self.unit,
        }
    }
}

impl<U: Unit, V: Value, X: Value> DivAssign<X> for Quantity<U, V> where
    V: DivAssign<X>,
{
    fn div_assign(&mut self, rhs: X) {
        self.value /= rhs;
    }
}

impl<U: Unit, V: Value, X: Value> MulAssign<X> for Quantity<U, V> where
    V: MulAssign<X>,
{
    fn mul_assign(&mut self, rhs: X) {
        self.value *= rhs;
    }
}
//endregion

//region Division/multiplication between quantities and pure units.
/*impl<U: Unit, V: Value> Quantity<U, V> {
    pub fn div_unit<W: Unit>(self, rhs: W) -> Quantity<<U as Div<W>>::Output, V> where
        U: Div<W>, <U as Div<W>>::Output: Unit,
    {
        Quantity {
            value: self.value,
            unit: self.unit / rhs,
        }
    }

    pub fn mul_unit<W: Unit>(self, rhs: W) -> Quantity<<U as Mul<W>>::Output, V> where
        U: Mul<W>, <U as Mul<W>>::Output: Unit,
    {
        Quantity {
            value: self.value,
            unit: self.unit * rhs,
        }
    }
}*/
//endregion

//region Comparison between quantities.
//region Equivalence.
impl<U: Unit, V: Value, W: Unit, X: Value> PartialEq<Quantity<W, X>>
for Quantity<U, V> where
    W: ConvertInto<U>,
    V: PartialEq<X>,
{
    fn eq(&self, other: &Quantity<W, X>) -> bool {
        let comp = other.clone().convert_to(self.unit);
        self.value.eq(&comp.value)
    }
}

impl<U: Unit, V: Value + Eq> Eq for Quantity<U, V> where
    Quantity<U, V>: PartialEq,
{}
//endregion

//region Ordering.
impl<U: Unit, V: Value, W: Unit, X: Value> PartialOrd<Quantity<W, X>>
for Quantity<U, V> where
    W: ConvertInto<U>,
    V: PartialOrd<X>,
{
    fn partial_cmp(&self, other: &Quantity<W, X>) -> Option<core::cmp::Ordering> {
        let comp = other.clone().convert_to(self.unit);
        self.value.partial_cmp(&comp.value)
    }
}

impl<U: Unit, V: Value + Ord> Ord for Quantity<U, V> where
    U: ConvertInto<U>,
    Quantity<U, V>: PartialOrd,
{
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        let comp = other.clone().convert_to(self.unit);
        self.value.cmp(&comp.value)
    }
}
//endregion
//endregion

impl<U: Unit, V: Value> Sum for Quantity<U, V> {
    fn sum<I: Iterator<Item=Self>>(mut iter: I) -> Self {
        //  NOTE: Read the first quantity in order to use its unit. Starting at
        //      zero would cause all quantities in the iterator to be converted
        //      to the base unit (potentially losing precision unnecessarily).
        match iter.next() {
            Some(qty) => iter.fold(qty, Add::add),
            None => Self::zero(),
        }
    }
}
//endregion


//region Traits from `num_traits`.
impl<U: Unit, V: Value + Signed> Quantity<U, V> {
    /// Return the absolute value of this quantity.
    pub fn abs(self) -> Self {
        Self::new(self.unit, self.value.abs())
    }
}

impl<U: Unit, V: Value + Real> Quantity<U, V> {
    /// Cast the value to another type through the [`NumCast`] trait.
    pub fn value_cast<X: Value>(self) -> Option<Quantity<U, X>> {
        Some(Quantity::new(self.unit, NumCast::from(self.value)?))
    }

    /// Return the smallest quantity with an integer value greater than or equal
    ///     to this one.
    pub fn ceil(self) -> Self {
        Self::new(self.unit, self.value.ceil())
    }

    /// Return the largest quantity with an integer value less than or equal to
    ///     this one.
    pub fn floor(self) -> Self {
        Self::new(self.unit, self.value.floor())
    }

    /// Return the largest quantity with the integer value nearest to this one.
    pub fn round(self) -> Self {
        Self::new(self.unit, self.value.round())
    }

    /// Return a quantity with only the integer part of the value of this one.
    pub fn trunc(self) -> Self {
        Self::new(self.unit, self.value.trunc())
    }
}

// impl<U: Unit, V: Scalar> num_traits:: for Quantity<U, V> {}

impl<U: Unit, V: Value> Inv for Quantity<U, V> where
    U: Inv, <U as Inv>::Output: Unit,
    V: Inv, <V as Inv>::Output: Value,
{
    type Output = Quantity<<U as Inv>::Output, <V as Inv>::Output>;

    fn inv(self) -> Self::Output {
        Quantity::new(self.unit.inv(), self.value.inv())
    }
}


impl<U: Unit, V: Value> Zero for Quantity<U, V> {
    fn zero() -> Self {
        U::base().zero()
    }

    fn is_zero(&self) -> bool {
        self.value.is_zero()
    }
}


impl<U, V, UMul, VMul, UAdd, VAdd> MulAdd<
    Quantity<UMul, VMul>,
    Quantity<UAdd, VAdd>,
> for Quantity<U, V> where
    U: Unit, UMul: Unit, UAdd: Unit,
    V: Value, VMul: Value, VAdd: Value,
    U: Mul<UMul>, <U as Mul<UMul>>::Output: Unit<Dim=UAdd::Dim>,
    V: MulAdd<VMul, VAdd>, <V as MulAdd<VMul, VAdd>>::Output: Value,
{
    type Output = Quantity<
        <U as Mul<UMul>>::Output,
        <V as MulAdd<VMul, VAdd>>::Output,
    >;

    fn mul_add(
        self,
        qty_mul: Quantity<UMul, VMul>,
        qty_add: Quantity<UAdd, VAdd>,
    ) -> Self::Output {
        let u_out = self.unit * qty_mul.unit;

        let v_mul = qty_mul.value;
        let v_add = qty_add.convert_to(u_out).value;
        let v_out = self.value.mul_add(v_mul, v_add);

        u_out.quantity(v_out)
    }
}
//endregion


// impl<U: Unit, V: Scalar + From<X>, X: Scalar> From<Quantity<U, X>> for Quantity<U, V> {
//     fn from(qty: Quantity<U, X>) -> Self {
//         Self::new(qty.unit, qty.value.into())
//     }
// }
//
// impl<U: Unit, V: Scalar + TryFrom<X>, X: Scalar> TryFrom<Quantity<U, X>> for Quantity<U, V> {
//     type Error = V::Error;
//
//     fn try_from(qty: Quantity<U, X>) -> Result<Self, Self::Error> {
//         Ok(Self::new(qty.unit, qty.value.try_into()?))
//     }
// }


macro_rules! impl_fmt {
    ($($fmt:path),+$(,)?) => {$(
    impl<U: Unit, V: Value> $fmt for Quantity<U, V> where V: $fmt {
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
            <V as $fmt>::fmt(&self.value, f)?;
            write!(f, " {}", self.unit)
        }
    }
    )+};
}

impl_fmt!(
    core::fmt::Display,
    core::fmt::Octal,
    core::fmt::LowerHex,
    core::fmt::UpperHex,
    core::fmt::Pointer,
    core::fmt::Binary,
    core::fmt::LowerExp,
    core::fmt::UpperExp,
);