dyn_quantity 0.5.10

Representing physical quantities dynamically (i.e. via values, not via the type system)
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*!
This module contains the [`Unit`] struct and supporting code. See the
documentation string of [`Unit`] for more information.
*/

use std::ops::{Div, DivAssign, Mul, MulAssign};

use num::Complex;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::error::RootError;

/**
Struct representing a unit of measurement in the SI system via the exponents of
the base units. The unit is purely defined by the values of its fields, meaning
that it can change at runtime. The struct implements basic arithmetic functions
such as multiplication and division (via the [`Mul`], [`MulAssign`], [`Div`],
[`DivAssign`] traits), exponentiation ([`Unit::powi`]) and a fallible version
of root calculation ([`Unit::try_nthroot`]).

# Serialization and deserialization

If the `serde` feature is enabled, this struct can be serialized and
deserialized. Serialization creates the "standard"
[serde](https://crates.io/crates/serde) representation one would expect from the
`Serialize` macro.

An [`Unit`] can be deserialized from both its "standard" serialized
representation and from a [`PredefUnit`] variant:
```
use dyn_quantity::Unit;

// Direct deserialization
let str = "---\nsecond: -3\nmeter: 2\nkilogram: 1\nampere: -1\nkelvin: 0\nmol: 0\ncandela: 0";
let unit_direct: Unit = serde_yaml::from_str(str).unwrap();

// Deserialization from PredefUnit
let str = "ElectricVoltage";
let unit_predef: Unit = serde_yaml::from_str(str).unwrap();
assert_eq!(unit_predef, unit_direct);
```
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(C)]
pub struct Unit {
    /// Exponent for the SI base unit of time.
    pub second: i32,
    /// Exponent for the SI base unit of length.
    pub meter: i32,
    /// Exponent for the SI base unit of mass.
    pub kilogram: i32,
    /// Exponent for the SI base unit of electrical current.
    pub ampere: i32,
    /// Exponent for the SI base unit of temperature.
    pub kelvin: i32,
    /// Exponent for the SI base unit of amount of substance.
    pub mol: i32,
    /// Exponent for the SI base unit of luminous intensity
    pub candela: i32,
}

impl From<[i32; 7]> for Unit {
    /**
    Converts an array of seven `i32` values into `Unit`.

    The individual array elements are interpreted as follows:
    - `array[0]`: Exponent of second
    - `array[1]`: Exponent of meter
    - `array[2]`: Exponent of kilogram
    - `array[3]`: Exponent of ampere
    - `array[4]`: Exponent of kelvin
    - `array[5]`: Exponent of mol
    - `array[6]`: Exponent of candela
     */
    fn from(array: [i32; 7]) -> Self {
        return Unit {
            second: array[0],
            meter: array[1],
            kilogram: array[2],
            ampere: array[3],
            kelvin: array[4],
            mol: array[5],
            candela: array[6],
        };
    }
}

impl From<Unit> for [i32; 7] {
    /**
    Converts an `Unit` into an array of seven `i32`.

    The exponents are put into the array in the following order:
    - `array[0]`: Exponent of second
    - `array[1]`: Exponent of meter
    - `array[2]`: Exponent of kilogram
    - `array[3]`: Exponent of ampere
    - `array[4]`: Exponent of kelvin
    - `array[5]`: Exponent of mol
    - `array[6]`: Exponent of candela
     */
    fn from(value: Unit) -> Self {
        return [
            value.second,
            value.meter,
            value.kilogram,
            value.ampere,
            value.kelvin,
            value.mol,
            value.candela,
        ];
    }
}

impl Unit {
    /**
    Raises `self` to an integer power.

    # Examples
    ```
    use dyn_quantity::Unit;

    let exponents = Unit::from([0, 1, 0, 2, 0, -2, 0]);
    let array: [i32; 7] = exponents.powi(2).into();
    assert_eq!(array, [0, 2, 0, 4, 0, -4, 0]);
    ```
     */
    pub fn powi(mut self, n: i32) -> Self {
        self.second *= n;
        self.meter *= n;
        self.kilogram *= n;
        self.ampere *= n;
        self.kelvin *= n;
        self.mol *= n;
        self.candela *= n;
        return self;
    }

    /**
    Tries to calculate the `n`th root of self. This operation fails if any
    of the exponents is not divisible by `n`.

    # Examples
    ```
    use dyn_quantity::Unit;

    let unit = Unit::from([0, 2, 0, 2, 0, -4, 0]);

    // It is possible to calculate the square root:
    let array: [i32; 7] = unit.clone().try_nthroot(2).unwrap().into();
    assert_eq!(array, [0, 1, 0, 1, 0, -2, 0]);

    // But not the cubic root (not all exponents are divisible by 3):
    assert!(unit.try_nthroot(3).is_err());
    ```
     */
    pub fn try_nthroot(mut self, n: i32) -> Result<Self, RootError> {
        fn try_nthroot_inner(unit: &Unit, exp: i32, n: i32) -> Result<i32, RootError> {
            if exp % n == 0 {
                return Ok(exp / n);
            } else {
                return Err(RootError {
                    n,
                    unit: unit.clone(),
                });
            }
        }
        let init_exp = self.clone();
        self.second = try_nthroot_inner(&init_exp, self.second, n)?;
        self.meter = try_nthroot_inner(&init_exp, self.meter, n)?;
        self.kilogram = try_nthroot_inner(&init_exp, self.kilogram, n)?;
        self.ampere = try_nthroot_inner(&init_exp, self.ampere, n)?;
        self.kelvin = try_nthroot_inner(&init_exp, self.kelvin, n)?;
        self.mol = try_nthroot_inner(&init_exp, self.mol, n)?;
        self.candela = try_nthroot_inner(&init_exp, self.candela, n)?;
        return Ok(self);
    }

    /// Returns whether [`Unit`] is dimensionless (all exponents are zero) or
    /// not.
    pub fn is_dimensionless(&self) -> bool {
        return self.second == 0
            && self.meter == 0
            && self.kilogram == 0
            && self.ampere == 0
            && self.kelvin == 0
            && self.mol == 0
            && self.candela == 0;
    }
}

impl std::fmt::Display for Unit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "s^{} m^{} kg^{} A^{} K^{} mol^{} cd^{}",
            self.second,
            self.meter,
            self.kilogram,
            self.ampere,
            self.kelvin,
            self.mol,
            self.candela
        )
    }
}

impl Mul for Unit {
    type Output = Self;

    fn mul(mut self, rhs: Self) -> Self::Output {
        self.mul_assign(rhs);
        return self;
    }
}

impl MulAssign for Unit {
    fn mul_assign(&mut self, rhs: Self) {
        self.second += rhs.second;
        self.meter += rhs.meter;
        self.kilogram += rhs.kilogram;
        self.ampere += rhs.ampere;
        self.kelvin += rhs.kelvin;
        self.mol += rhs.mol;
        self.candela += rhs.candela;
    }
}

impl Div for Unit {
    type Output = Self;

    fn div(mut self, rhs: Self) -> Self::Output {
        self.div_assign(rhs);
        return self;
    }
}

impl DivAssign for Unit {
    fn div_assign(&mut self, rhs: Self) {
        self.second -= rhs.second;
        self.meter -= rhs.meter;
        self.kilogram -= rhs.kilogram;
        self.ampere -= rhs.ampere;
        self.kelvin -= rhs.kelvin;
        self.mol -= rhs.mol;
        self.candela -= rhs.candela;
    }
}
/**
A trait to derive [`Unit`] from a type. This trait bridges the gap
between (external) types representing physical quantities (such as e.g. the
[`Quantity`](https://docs.rs/uom/latest/uom/si/struct.Quantity.html) type from
the [uom](https://crates.io/crates/uom) crate) and [`Unit`].
 */
pub trait UnitFromType {
    /**
    This function derives an [`Unit`] from any type which implements
    [`UnitFromType`]. Its default implementation returns an [`Unit`]
    where all exponents are zero.

    # Examples
    ```
    use dyn_quantity::UnitFromType;
    use uom::si::f64::Length;

    // 64-bit floats do not represent a physical quantity
    let exp = f64::unit_from_type();
    assert_eq!(exp.meter, 0);

    // The "Length" type alias from the uom crate represents a physical quantity (length)
    let exp = Length::unit_from_type();
    assert_eq!(exp.meter, 1);
    ```
    */
    fn unit_from_type() -> Unit {
        return Unit::default();
    }
}

impl UnitFromType for f64 {}

impl UnitFromType for Complex<f64> {}

/**
An enum representing predefined [`Unit`]s.

This enum serves two purposes:
* It can be a constructor for [`Unit`] via the [`From`] / [`Into`] implementations:
```
use dyn_quantity::{Unit, PredefUnit};

let unit: Unit = PredefUnit::ElectricCurrent.into();
assert_eq!(unit.ampere, 1);

let unit: Unit = PredefUnit::Area.into();
assert_eq!(unit.meter, 2);
```
* When deserializing an [`Unit`], it can be used instead of the explicit struct
implementation:
```
use dyn_quantity::Unit;

let str = "Volume";
let unit: Unit = serde_yaml::from_str(str).unwrap();
assert_eq!(unit.meter, 3);
```
 */
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum PredefUnit {
    /// No unit
    None,
    /// SI base units representation: s (second)
    Time,
    /// SI base units representation: m (meter)
    Length,
    /// SI base units representation: kg (kilogram)
    Mass,
    /// SI base units representation: A (ampere)
    ElectricCurrent,
    /// SI base units representation: K (kelvin)
    Temperature,
    /// SI base units representation: mol (mol)
    AmountOfSubstance,
    /// SI base units representation: cd (candela)
    LuminousIntensity,
    /// SI base units representation: m^2 (square meter)
    Area,
    /// SI base units representation: m^3 (cubic meter)
    Volume,
    /// SI base units representation: s^-3*m^2*kg*A*-1 (voltage)
    ElectricVoltage,
    /// SI base units representation: s^-2*m*kg (newton)
    Force,
    /// SI base units representation: s^-2*m^2*kg (newton meter)
    Torque,
    /// SI base units representation: s^-3*m^2*kg (watt)
    Power,
    /// SI base units representation: s^-2*m^2*kg (energy)
    Energy,
    /// SI base units representation: s^-1 (hertz)
    Frequency,
    /// SI base units representation: s^-1*m (meter per second)
    Velocity,
    /// SI base units representation: s^-1 (rad per second)
    AngularVelocity,
    /// SI base units representation: s^-2*m^2*kg*A^-1 (weber)
    MagneticFlux,
    /// SI base units representation: s^-2*kg*A^-1 (tesla)
    MagneticFluxDensity,
    /// SI base units representation: m*A^-1 (ampere per meter)
    MagneticFieldStrength,
    /// SI base units representation: s^-2*m^2*kg*A^-2 (henry)
    Inductance,
    /// SI base units representation: s^3*m^-2*kg^-1*A^2 (siemens)
    ElectricConductance,
    /// SI base units representation: s^-3*m^2*kg*A^-2 (ohm)
    ElectricResistance,
    /// SI base units representation: s^3*m^-2*kg^-1*A^2 (siemens)
    ElectricConductivity,
    /// SI base units representation: s^-3*m^3*kg*A^-2 (ohm)
    ElectricResistivity,
}

impl From<PredefUnit> for Unit {
    fn from(value: PredefUnit) -> Self {
        match value {
            PredefUnit::None => Default::default(),
            PredefUnit::Time => Self {
                second: 1,
                meter: 0,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Length => Self {
                second: 0,
                meter: 1,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Mass => Self {
                second: 0,
                meter: 0,
                kilogram: 1,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::ElectricCurrent => Self {
                second: 0,
                meter: 0,
                kilogram: 0,
                ampere: 1,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Temperature => Self {
                second: 0,
                meter: 0,
                kilogram: 0,
                ampere: 0,
                kelvin: 1,
                mol: 0,
                candela: 0,
            },
            PredefUnit::AmountOfSubstance => Self {
                second: 0,
                meter: 0,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 1,
                candela: 0,
            },
            PredefUnit::LuminousIntensity => Self {
                second: 0,
                meter: 0,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 1,
            },
            PredefUnit::Area => Self {
                second: 0,
                meter: 2,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Volume => Self {
                second: 0,
                meter: 3,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::ElectricVoltage => Self {
                second: -3,
                meter: 2,
                kilogram: 1,
                ampere: -1,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Force => Self {
                second: -2,
                meter: 1,
                kilogram: 1,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Torque => Self {
                second: -2,
                meter: 2,
                kilogram: 1,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Power => Self {
                second: -3,
                meter: 2,
                kilogram: 1,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Energy => Self {
                second: -2,
                meter: 2,
                kilogram: 1,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Frequency => Self {
                second: -1,
                meter: 0,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Velocity => Self {
                second: -1,
                meter: 1,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::AngularVelocity => Self {
                second: -1,
                meter: 0,
                kilogram: 0,
                ampere: 0,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::MagneticFlux => Self {
                second: -2,
                meter: 2,
                kilogram: 1,
                ampere: -1,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::MagneticFluxDensity => Self {
                second: -2,
                meter: 0,
                kilogram: 1,
                ampere: -1,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::MagneticFieldStrength => Self {
                second: 0,
                meter: -1,
                kilogram: 0,
                ampere: 1,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::Inductance => Self {
                second: -2,
                meter: 2,
                kilogram: 1,
                ampere: -2,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::ElectricConductance => Self {
                second: 3,
                meter: -2,
                kilogram: -1,
                ampere: 2,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::ElectricResistance => Self {
                second: -3,
                meter: 2,
                kilogram: 1,
                ampere: -2,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::ElectricConductivity => Self {
                second: 3,
                meter: -3,
                kilogram: -1,
                ampere: 2,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
            PredefUnit::ElectricResistivity => Self {
                second: -3,
                meter: 3,
                kilogram: 1,
                ampere: -2,
                kelvin: 0,
                mol: 0,
                candela: 0,
            },
        }
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    /*!
    This module is only available if the [`serde`] feature is enabled.
    It contains the serialization and deserialization implementations for
    [`Unit`].
    */
    use super::{PredefUnit, Unit};
    use deserialize_untagged_verbose_error::DeserializeUntaggedVerboseError;
    use serde::de::{Deserialize, Deserializer};
    use serde::ser::{Serialize, SerializeStruct, Serializer};

    impl Serialize for Unit {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut state = serializer.serialize_struct("Unit", 7)?;
            state.serialize_field("second", &self.second)?;
            state.serialize_field("meter", &self.meter)?;
            state.serialize_field("kilogram", &self.kilogram)?;
            state.serialize_field("ampere", &self.ampere)?;
            state.serialize_field("kelvin", &self.kelvin)?;
            state.serialize_field("mol", &self.mol)?;
            state.serialize_field("candela", &self.candela)?;
            state.end()
        }
    }

    #[derive(serde::Deserialize)]
    struct UnitAlias {
        second: i32,
        meter: i32,
        kilogram: i32,
        ampere: i32,
        kelvin: i32,
        mol: i32,
        candela: i32,
    }

    /**
    An [`Unit`] can be deserialized a couple of different representations.
     */
    #[derive(DeserializeUntaggedVerboseError)]
    enum UnitVariants {
        /**
        Native representation of [`Unit`] (via an alias struct in order
        to avoid infinite recursion)-
         */
        Unit(UnitAlias),
        /**
        Deserialization from a [`PredefUnit`].
         */
        PredefUnit(PredefUnit),
    }

    impl<'de> Deserialize<'de> for Unit {
        fn deserialize<D>(deserializer: D) -> Result<Unit, D::Error>
        where
            D: Deserializer<'de>,
        {
            let variants = UnitVariants::deserialize(deserializer)?;
            match variants {
                UnitVariants::Unit(alias) => {
                    return Ok(Unit {
                        second: alias.second,
                        meter: alias.meter,
                        kilogram: alias.kilogram,
                        ampere: alias.ampere,
                        kelvin: alias.kelvin,
                        mol: alias.mol,
                        candela: alias.candela,
                    });
                }
                UnitVariants::PredefUnit(common_units) => {
                    return Ok(common_units.into());
                }
            }
        }
    }
}