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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/*!
This module contains the [`DynQuantity`] struct and code for:
- Interaction with a [`DynQuantity`]: Basic arithmetic operation, conversion
from and into other types, formatting, etc.
- Parsing of strings into [`DynQuantity`]s: See [`from_str_impl`] only available
if the `from_str` feature is enabled).
- Serialization and deserialization: See [`serde_impl`] (only available if the
`serde` feature is enabled).
- Conversion from and into [`uom::si::Quantity`] : See [`uom_impl`] (only
available if the `uom` feature is enabled).

See the documentation string of [`DynQuantity`] for more information.
*/

use num::Complex;
use num::complex::ComplexFloat;

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

use crate::error::{ConversionError, NotConvertibleFromComplexF64, RootError, UnitsNotEqual};
use crate::unit::Unit;

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

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

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

mod private {
    use super::Complex;

    pub trait Sealed {}

    impl Sealed for f64 {}
    impl Sealed for Complex<f64> {}
}

/**
This is an internal trait which is used to convert between [`f64`] and
[`Complex<f64>`]-based [`DynQuantity`] structs. It needs to be public because
it is part of the type signature of [`DynQuantity`], but it is not meant to be
implemented by external types and is therefore sealed.
*/
pub trait F64RealOrComplex:
    ComplexFloat<Real: std::fmt::Display>
    + std::ops::AddAssign
    + std::ops::SubAssign
    + std::fmt::Display
    + std::ops::Mul<f64, Output = Self>
    + std::ops::MulAssign
    + std::ops::MulAssign<f64>
    + std::ops::Div<f64, Output = Self>
    + std::ops::DivAssign
    + std::ops::DivAssign<f64>
    + std::fmt::Debug
    + private::Sealed
{
    /**
    Tries to convert from a [`Complex<f64>`] to the implementor of this trait,
    either [`Complex<f64>`] or [`f64`]. The former conversion always succeeds
    (is a no-op), while the latter fails if `number` has an imaginary component.
     */
    fn try_from_complexf64(number: Complex<f64>) -> Result<Self, NotConvertibleFromComplexF64>;

    /**
    Converts a [`Complex<f64>`] or [`f64`] to a [`Complex<f64>`]. This is
    infallible (and a no-op in case of the former conversion).
     */
    fn to_complexf64(self) -> Complex<f64>;

    /**
    Converts a [`f64`] to a [`Complex<f64>`] or [`f64`]. This is infallible
    (and a no-op in case of the latter conversion).
     */
    fn from_f64(value: f64) -> Self;

    /**
    Sets the real part of the implementor to `value`.
     */
    fn set_re_f64(&mut self, value: f64) -> ();

    /**
    Sets the imaginary part of the implementor to `value`. If the implementing
    type is [`f64`], this is a no-op.
     */
    fn set_im_f64(&mut self, value: f64) -> ();

    /**
    Calcute the `n`th root of `self`.
     */
    fn nth_root(self, n: i32) -> Self;
}

impl F64RealOrComplex for f64 {
    fn try_from_complexf64(number: Complex<f64>) -> Result<Self, NotConvertibleFromComplexF64> {
        if number.im() == 0.0 {
            return Ok(number.re());
        } else {
            return Err(NotConvertibleFromComplexF64 {
                source: number,
                target_type: "f64",
            });
        }
    }

    fn to_complexf64(self) -> Complex<f64> {
        return Complex::new(self, 0.0);
    }

    fn from_f64(value: f64) -> Self {
        return value;
    }

    fn set_re_f64(&mut self, value: f64) -> () {
        *self = value;
    }

    fn set_im_f64(&mut self, _: f64) -> () {
        ();
    }

    fn nth_root(self, n: i32) -> Self {
        return self.powf(1.0 / n as f64);
    }
}

impl F64RealOrComplex for Complex<f64> {
    fn try_from_complexf64(number: Complex<f64>) -> Result<Self, NotConvertibleFromComplexF64> {
        return Ok(Complex::<f64>::from(number));
    }

    fn to_complexf64(self) -> Complex<f64> {
        return self;
    }

    fn from_f64(value: f64) -> Self {
        return Complex::new(value, 0.0);
    }

    fn set_re_f64(&mut self, value: f64) -> () {
        self.re = value;
    }

    fn set_im_f64(&mut self, value: f64) -> () {
        self.im = value;
    }

    fn nth_root(self, n: i32) -> Self {
        return self.powf(1.0 / n as f64);
    }
}

/**
This type represents a physical quantity via its numerical `value` and a unit of
measurement (field `exponents`). The unit of measurement is not defined via the
type system, but rather via the values of the [`Unit`]. This means that
the unit of measurement is not fixed at compile time, but can change dynamically
at runtime.

This property is very useful when e.g. parsing a user-provided string to a
physical quantity. For this case, [`DynQuantity`] implements the
[`FromStr`](`std::str::FromStr`) trait. The module documentation
[`from_str`](crate::quantity::from_str_impl) has more information regarding the
available syntax.

The `V` generic parameter needs to implement [`F64RealOrComplex`].
Currently, implementors are [`f64`] and [`Complex<f64>`]. It is possible to
convert between those two types using the methods provided by [`F64RealOrComplex`].
In general, you likely want `V` to be [`f64`] except when dealing with complex
quantities such as alternating currents.

This struct can also be pretty-print the quantity it represents via its
[`std::fmt::Display`] implementation:

```
use std::str::FromStr;
use dyn_quantity::DynQuantity;

let quantity = DynQuantity::<f64>::from_str("9.81 m/s^2").expect("parseable");
assert_eq!(quantity.to_string(), "9.81 s^-2 m".to_string());
```

# Conversion into uom `Quantity`

If the `uom` feature is enabled, a [`DynQuantity`] can be (fallible)
converted into a
[`Quantity`](https://docs.rs/uom/latest/uom/si/struct.Quantity.html) via
[`TryFrom`]. In combination with the aforementioned parsing capabilities, this
allows fallible parsing of strings to statically-typed physical quantities.

# 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.

When deserializing however, multiple options are available:
1) Using the "standard" serialized representation of a struct. For example, the
yaml representation of a [`DynQuantity<f64>`] looks like this:
```text
---
value: 2.0
exponents:
    second: 0
    meter: 1
    kilogram: 0
    ampere: 1
    kelvin: 0
    mol: 0
    candela: 0
```

2) Deserializing directly from a string. This uses the [`std::str::FromStr`]
implementation under the hood, see the
[`from_str`](crate::quantity::from_str_impl) module documentation. Only
available if the `from_str` feature is enabled.
3) Deserialize directly from a real or complex value. This option is mainly here
to allow deserializing a serialized [uom](https://crates.io/crates/uom) quantity
(whose serialized representation is simply its numerical value without any
units). For example, deserializing `5.0` into [`DynQuantity<f64>`] produces the
same result as deserializing:
```text
---
value: 5.0
exponents:
    second: 0
    meter: 0
    kilogram: 0
    ampere: 0
    kelvin: 0
    mol: 0
    candela: 0
```

The three different possibilities are realized via a crate-internal untagged enum.
*/
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[repr(C)]
pub struct DynQuantity<V: F64RealOrComplex> {
    /**
    The value of the physical quantity.
     */
    pub value: V,
    /**
    The (SI) base units of the physical quantity, represented by their exponents.
     */
    pub unit: Unit,
}

impl<V: F64RealOrComplex> DynQuantity<V> {
    /**
    Returns a new instance of `Self`.
     */
    pub fn new<U: Into<Unit>>(value: V, unit: U) -> Self {
        return Self {
            value,
            unit: unit.into(),
        };
    }

    /**
    Fallible addition of `self` and `other`.

    Physical quantities can only be added together if their units are identical.
    Hence, this function first compares the `.unit` fields of `self` and
    `other`. If they are identical, the `value` fields are added up and the
    resulting quantity is returned. Otherwise, a [`UnitsNotEqual`]
    error is returned.

    # Examples
    ```
    use std::str::FromStr;
    use dyn_quantity::DynQuantity;

    let curr1 = DynQuantity::<f64>::from_str("1 A").expect("valid");
    let curr2 = DynQuantity::<f64>::from_str("1 V*A / V").expect("valid");
    let volt1 = DynQuantity::<f64>::from_str("-5 V").expect("valid");

    // The currents can be added ...
    let curr_sum = curr1.try_add(&curr2).expect("can be added");
    assert_eq!(curr_sum.value, 2.0);
    assert_eq!(curr_sum.unit.ampere, 1);

    // ... but adding a current to a voltage fails.
    assert!(volt1.try_add(&curr1).is_err());
    ```
     */
    pub fn try_add(&self, other: &Self) -> Result<Self, UnitsNotEqual> {
        let mut output = self.clone();
        output.try_add_assign(other)?;
        return Ok(output);
    }

    /**
    Like [`DynQuantity::try_add`], but assigns the sum of `self` and `other` to
    `self` instead of returning it. If the addition fails, `self` is not modified.

    # Examples
    ```
    use std::str::FromStr;
    use dyn_quantity::DynQuantity;

    let mut curr1 = DynQuantity::<f64>::from_str("1 A").expect("valid");
    let curr2 = DynQuantity::<f64>::from_str("1 V*A / V").expect("valid");
    let mut volt1 = DynQuantity::<f64>::from_str("-5 V").expect("valid");

    // curr1 gets overwritten
    curr1.try_add_assign(&curr2).expect("can be added");
    assert_eq!(curr1.value, 2.0);
    assert_eq!(curr1.unit.ampere, 1);

    // volt1 does not get modified because the addition failed
    let volt_cpy = volt1.clone();
    assert!(volt1.try_add_assign(&curr1).is_err());
    assert_eq!(volt1, volt_cpy);
    ```
     */
    pub fn try_add_assign(&mut self, other: &Self) -> Result<(), UnitsNotEqual> {
        if self.unit == other.unit {
            self.value += other.value;
            return Ok(());
        } else {
            return Err(UnitsNotEqual(self.unit.clone(), other.unit.clone()));
        }
    }

    /**
    Fallible subtraction of `self` and `other`.

    Physical quantities can only be subtracted from each other if their units are identical.
    Hence, this function first compares the `.unit` fields of `self` and
    `other`. If they are identical, the `value` fields are subtracted up and the
    resulting quantity is returned. Otherwise, a [`UnitsNotEqual`]
    error is returned.

    # Examples
    ```
    use std::str::FromStr;
    use dyn_quantity::DynQuantity;

    let curr1 = DynQuantity::<f64>::from_str("1 A").expect("valid");
    let curr2 = DynQuantity::<f64>::from_str("1 V*A / V").expect("valid");
    let volt1 = DynQuantity::<f64>::from_str("-5 V").expect("valid");

    // The currents can be subtracted ...
    let curr_sum = curr1.try_sub(&curr2).expect("can be added");
    assert_eq!(curr_sum.value, 0.0);
    assert_eq!(curr_sum.unit.ampere, 1);

    // ... but sbutracting a current from a voltage fails.
    assert!(volt1.try_sub(&curr1).is_err());
    ```
     */
    pub fn try_sub(&self, other: &Self) -> Result<Self, UnitsNotEqual> {
        let mut output = self.clone();
        output.try_sub_assign(other)?;
        return Ok(output);
    }

    /**
    Like [`DynQuantity::try_sub`], but assigns the difference of `self` and `other` to
    `self` instead of returning it. If the subtraction fails, `self` is not modified.

    # Examples
    ```
    use std::str::FromStr;
    use dyn_quantity::DynQuantity;

    let mut curr1 = DynQuantity::<f64>::from_str("1 A").expect("valid");
    let curr2 = DynQuantity::<f64>::from_str("1 V*A / V").expect("valid");
    let mut volt1 = DynQuantity::<f64>::from_str("-5 V").expect("valid");

    // curr1 gets overwritten
    curr1.try_sub_assign(&curr2).expect("can be added");
    assert_eq!(curr1.value, 0.0);
    assert_eq!(curr1.unit.ampere, 1);

    // volt1 does not get modified because the addition failed
    let volt_cpy = volt1.clone();
    assert!(volt1.try_sub_assign(&curr1).is_err());
    assert_eq!(volt1, volt_cpy);
    ```
     */
    pub fn try_sub_assign(&mut self, other: &Self) -> Result<(), UnitsNotEqual> {
        if self.unit == other.unit {
            self.value -= other.value;
            return Ok(());
        } else {
            return Err(UnitsNotEqual(self.unit.clone(), other.unit.clone()));
        }
    }

    /**
    Raises `self` to an integer power.

    # Examples
    ```
    use std::str::FromStr;
    use dyn_quantity::DynQuantity;

    let curr = DynQuantity::<f64>::from_str("2 A^2").expect("valid");
    let result = curr.powi(3);
    assert_eq!(result.value, 8.0);
    assert_eq!(result.unit.ampere, 6);
    ```
     */
    pub fn powi(mut self, n: i32) -> Self {
        self.value = self.value.powi(n);
        self.unit = self.unit.powi(n);
        return self;
    }

    /**
    Tries to calculate the `n`th root of self.
     */
    pub fn try_nthroot(mut self, n: i32) -> Result<Self, RootError> {
        self.unit = self.unit.try_nthroot(n)?;
        self.value = self.value.nth_root(n);
        return Ok(self);
    }
}

impl<V: F64RealOrComplex> std::fmt::Display for DynQuantity<V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.value.im() == V::zero().im() {
            write!(f, "{}", self.value.re())?;
        } else {
            write!(f, "({})", self.value)?;
        }

        // Go through all units and add them, if their exponents aren't zero
        if self.unit.second != 0 {
            if self.unit.second == 1 {
                write!(f, " s")?;
            } else {
                write!(f, " s^{}", self.unit.second)?;
            }
        }
        if self.unit.meter != 0 {
            if self.unit.meter == 1 {
                write!(f, " m")?;
            } else {
                write!(f, " m^{}", self.unit.meter)?;
            }
        }
        if self.unit.kilogram != 0 {
            if self.unit.kilogram == 1 {
                write!(f, " kg")?;
            } else {
                write!(f, " kg^{}", self.unit.kilogram)?;
            }
        }
        if self.unit.ampere != 0 {
            if self.unit.ampere == 1 {
                write!(f, " A")?;
            } else {
                write!(f, " A^{}", self.unit.ampere)?;
            }
        }
        if self.unit.kelvin != 0 {
            if self.unit.kelvin == 1 {
                write!(f, " K")?;
            } else {
                write!(f, " K^{}", self.unit.kelvin)?;
            }
        }
        if self.unit.mol != 0 {
            if self.unit.mol == 1 {
                write!(f, " mol")?;
            } else {
                write!(f, " mol^{}", self.unit.mol)?;
            }
        }
        if self.unit.candela != 0 {
            if self.unit.candela == 1 {
                write!(f, " cd")?;
            } else {
                write!(f, " cd^{}", self.unit.candela)?;
            }
        }

        return Ok(());
    }
}

impl<V: F64RealOrComplex> Mul for DynQuantity<V> {
    type Output = Self;

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

impl<V: F64RealOrComplex> Mul<f64> for DynQuantity<V> {
    type Output = Self;

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

impl<V: F64RealOrComplex> MulAssign for DynQuantity<V> {
    fn mul_assign(&mut self, rhs: Self) {
        self.value *= rhs.value;
        self.unit *= rhs.unit;
    }
}

impl<V: F64RealOrComplex> MulAssign<f64> for DynQuantity<V> {
    fn mul_assign(&mut self, rhs: f64) {
        self.value *= rhs;
    }
}

impl<V: F64RealOrComplex> Div for DynQuantity<V> {
    type Output = Self;

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

impl<V: F64RealOrComplex> Div<f64> for DynQuantity<V> {
    type Output = Self;

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

impl<V: F64RealOrComplex> DivAssign for DynQuantity<V> {
    fn div_assign(&mut self, rhs: Self) {
        if self.value.is_infinite() {
            let mut value = self.value / rhs.value;
            if value.re().is_nan() {
                value.set_re_f64(0.0);
            }
            if value.im().is_nan() {
                value.set_im_f64(0.0);
            }
            self.value = value;
        } else {
            self.value /= rhs.value;
        }
        self.unit /= rhs.unit;
    }
}

impl<V: F64RealOrComplex> DivAssign<f64> for DynQuantity<V> {
    fn div_assign(&mut self, rhs: f64) {
        if self.value.is_infinite() {
            let mut value: V = self.value / rhs;
            if value.re().is_nan() {
                value.set_re_f64(0.0);
            }
            if value.im().is_nan() {
                value.set_im_f64(0.0);
            }
            self.value = value;
        } else {
            self.value /= rhs;
        }
    }
}

impl TryFrom<DynQuantity<Complex<f64>>> for DynQuantity<f64> {
    type Error = NotConvertibleFromComplexF64;

    fn try_from(quantity: DynQuantity<Complex<f64>>) -> Result<Self, Self::Error> {
        if quantity.value.im() == 0.0 {
            return Ok(DynQuantity::new(quantity.value.re(), quantity.unit));
        } else {
            return Err(NotConvertibleFromComplexF64 {
                source: quantity.value,
                target_type: "f64",
            });
        }
    }
}

impl From<DynQuantity<f64>> for DynQuantity<Complex<f64>> {
    fn from(value: DynQuantity<f64>) -> Self {
        return DynQuantity::new(Complex::new(value.value, 0.0), value.unit);
    }
}

impl From<&DynQuantity<f64>> for DynQuantity<f64> {
    fn from(value: &DynQuantity<f64>) -> Self {
        return DynQuantity::new(value.value, value.unit);
    }
}

impl From<&DynQuantity<f64>> for DynQuantity<Complex<f64>> {
    fn from(value: &DynQuantity<f64>) -> Self {
        return DynQuantity::new(Complex::new(value.value, 0.0), value.unit);
    }
}

impl From<&DynQuantity<Complex<f64>>> for DynQuantity<Complex<f64>> {
    fn from(value: &DynQuantity<Complex<f64>>) -> Self {
        return DynQuantity::new(value.value, value.unit);
    }
}

impl From<f64> for DynQuantity<f64> {
    fn from(value: f64) -> Self {
        return DynQuantity::new(value, Unit::default());
    }
}

impl From<f64> for DynQuantity<Complex<f64>> {
    fn from(value: f64) -> Self {
        return DynQuantity::new(Complex::new(value, 0.0), Unit::default());
    }
}

impl From<Complex<f64>> for DynQuantity<Complex<f64>> {
    fn from(value: Complex<f64>) -> Self {
        return DynQuantity::new(value, Unit::default());
    }
}

impl From<&f64> for DynQuantity<f64> {
    fn from(value: &f64) -> Self {
        return DynQuantity::new(value.clone(), Unit::default());
    }
}

impl From<&Complex<f64>> for DynQuantity<Complex<f64>> {
    fn from(value: &Complex<f64>) -> Self {
        return DynQuantity::new(value.clone(), Unit::default());
    }
}

impl TryFrom<DynQuantity<f64>> for f64 {
    type Error = ConversionError;

    fn try_from(quantity: DynQuantity<f64>) -> Result<Self, Self::Error> {
        // If the unit is dimensionless, the conversion succeeds, otherwise it fails
        if quantity.unit.is_dimensionless() {
            return Ok(quantity.value);
        } else {
            return Err(ConversionError::UnitMismatch {
                expected: Unit::default(),
                found: quantity.unit,
            });
        }
    }
}

impl TryFrom<DynQuantity<f64>> for Complex<f64> {
    type Error = ConversionError;

    fn try_from(quantity: DynQuantity<f64>) -> Result<Self, Self::Error> {
        let re = f64::try_from(quantity)?;
        return Ok(Complex::new(re, 0.0));
    }
}

impl TryFrom<DynQuantity<Complex<f64>>> for Complex<f64> {
    type Error = ConversionError;

    fn try_from(quantity: DynQuantity<Complex<f64>>) -> Result<Self, Self::Error> {
        // If the unit is dimensionless, the conversion succeeds, otherwise it fails
        if quantity.unit.is_dimensionless() {
            return Ok(quantity.value);
        } else {
            return Err(ConversionError::UnitMismatch {
                expected: Unit::default(),
                found: quantity.unit,
            });
        }
    }
}

impl TryFrom<DynQuantity<Complex<f64>>> for f64 {
    type Error = ConversionError;

    fn try_from(quantity: DynQuantity<Complex<f64>>) -> Result<Self, Self::Error> {
        let c = Complex::<f64>::try_from(quantity)?;
        if c.im == 0.0 {
            return Ok(c.re);
        } else {
            return Err(ConversionError::NotConvertibleFromComplexF64(
                NotConvertibleFromComplexF64 {
                    source: c,
                    target_type: "f64",
                },
            ));
        }
    }
}

// ========================================================

/**
Converts a slice of [`DynQuantity`] to a vector of their values `V`. In
constrast to [`to_vec_checked`], this function does not check whether the units
of the individual [`DynQuantity`] elements are identical.
*/
pub fn to_vec<V: F64RealOrComplex>(quantity_slice: &[DynQuantity<V>]) -> Vec<V> {
    let mut output: Vec<V> = Vec::with_capacity(quantity_slice.len());
    for element in quantity_slice.iter() {
        output.push(element.value)
    }
    return output;
}

/**
Checks if all units of the [`DynQuantity`] elements are identical. If that is
the case, it converts the slice to a vector of their values `V`.
*/
pub fn to_vec_checked(quantity_slice: &[DynQuantity<f64>]) -> Result<Vec<f64>, ConversionError> {
    let mut output: Vec<f64> = Vec::with_capacity(quantity_slice.len());
    if let Some(first_element) = quantity_slice.first() {
        let first_elem_unit = first_element.unit;
        for element in quantity_slice.iter() {
            if element.unit != first_elem_unit {
                return Err(ConversionError::UnitMismatch {
                    expected: first_elem_unit,
                    found: element.unit,
                });
            }
            output.push(element.value)
        }
    }
    return Ok(output);
}