dv 0.3.4

Core Rust library for DimensionalVariable, a multi-language library for handling physical quantities with units.
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
#![doc = include_str!("../DOCS.md")]

pub mod units;

pub struct DimensionalVariable {
    pub value: f64,
    pub unit: [f64; units::BASE_UNITS_SIZE],
}

/// A struct representing a dimensional variable with a value and a unit.
impl DimensionalVariable {
    /// Creates a new DimensionalVariable with the given value and unit.
    ///
    /// Rules for writing the unit string:
    /// - Use a single `/` as a delimiter between the numerator and denominator.
    /// - Use `-` as a delimiter between individual units
    /// - Exponents can be represented either by using `^` to indicate exponent (ex. `m^2`) or without the delimiter (ex. `m2`)
    /// - Inverses can be represented either by negative exponents or in the denominator (ex. `m^-2` or `1/m^2`)
    /// 
    /// Returns an error if the unit string is invalid or contains unknown units.
    pub fn new(value: f64, unit_str: &str) -> Result<Self, String> {
        // Fetch the unit details from the unit map
        let (base_unit, conversion_factor) = unit_str_to_base_unit(unit_str)
            .map_err(|e| format!("Failed to parse unit '{}': {}", unit_str, e))?;

        // Create the DimensionalVariable with the converted value
        return Ok(DimensionalVariable {
            value: value * conversion_factor,
            unit: base_unit,
        });
    }

    /// Returns the value of this DimensionalVariable.
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Converts the value of this DimensionalVariable to the specified unit.
    /// Returns an error if the unit string is invalid or incompatible.
    pub fn value_in(&self, unit_str: &str) -> Result<f64, String> {

        let (unit, conversion_factor) = unit_str_to_base_unit(unit_str)
            .map_err(|e| format!("Failed to parse unit '{}': {}", unit_str, e))?;

        // Check if the units are compatible
        if !self.check_compatibility(unit) {
            return Err(format!("Incompatible unit conversion to: {}", unit_str));
        }
        
        return Ok(self.value / conversion_factor);
    }

    pub fn check_compatibility(&self, other_unit: [f64; units::BASE_UNITS_SIZE]) -> bool {

       // If the angle unit == 1, then allow compatibility to linear units
       if self.unit[7] == 1.0 {
            // Compare only the first 7 base units (ignore the angle unit)
            return &self.unit[..units::BASE_UNITS_SIZE - 1] == &other_unit[..units::BASE_UNITS_SIZE - 1];
       }

        return self.unit == other_unit;
    }

    /// Returns the base unit array of this DimensionalVariable.
    pub fn unit(&self) -> [f64; units::BASE_UNITS_SIZE] {
        return self.unit;
    }

    /// Returns whether the variable is unitless (all base exponents are 0).
    pub fn is_unitless(&self) -> bool {
        return self.unit.iter().all(|&e| e == 0.0);
    }

    /// Fallible add with unit compatibility check.
    pub fn try_add(&self, other: &DimensionalVariable) -> Result<DimensionalVariable, String> {
        if !self.check_compatibility(other.unit) {
            return Err("Incompatible units for addition".to_string());
        }
        return Ok(DimensionalVariable { value: self.value + other.value, unit: self.unit });
    }

    /// Fallible subtraction with unit compatibility check.
    pub fn try_sub(&self, other: &DimensionalVariable) -> Result<DimensionalVariable, String> {
        if !self.check_compatibility(other.unit) {
            return Err("Incompatible units for subtraction".to_string());
        }
        return Ok(DimensionalVariable { value: self.value - other.value, unit: self.unit });
    }

    // ---- Math: powers and roots ----
    /// Raise to integer power. Units exponents are multiplied by exp.
    /// Returns a new DimensionalVariable.
    pub fn powi(&self, exp: i32) -> DimensionalVariable {
        let mut unit = self.unit;
    for i in 0..units::BASE_UNITS_SIZE { unit[i] *= exp as f64; }
        return DimensionalVariable { value: self.value.powi(exp), unit };
    }

    /// Raise to floating power.
    /// Returns a new DimensionalVariable.
    pub fn powf(&self, exp: f64) -> Result<DimensionalVariable, String> {
        let mut unit = self.unit;
        for i in 0..units::BASE_UNITS_SIZE { unit[i] *= exp; }
        return Ok(DimensionalVariable { value: self.value.powf(exp), unit });
    }

    /// Square root. Allowed only when all unit exponents are value >= 0 (no complex results).
    /// Returns a new DimensionalVariable.
    pub fn sqrt(&self) -> Result<DimensionalVariable, String> {
        if self.value < 0.0 {
            return Err("sqrt of negative value".to_string());
        }
        return self.powf(0.5);
    }

    // ---- Math: logarithms (unitless only) ----
    /// Natural logarithm. Requires unitless and value > 0.
    pub fn ln(&self) -> Result<f64, String> {
        if !self.is_unitless() { return Err("ln requires a unitless quantity".to_string()); }
        if self.value <= 0.0 { return Err("ln domain error (value <= 0)".to_string()); }
        Ok(self.value.ln())
    }

    /// Base-2 logarithm. Requires unitless and value > 0.
    pub fn log2(&self) -> Result<f64, String> {
        if !self.is_unitless() { return Err("log2 requires a unitless quantity".to_string()); }
        if self.value <= 0.0 { return Err("log2 domain error (value <= 0)".to_string()); }
        Ok(self.value.log2())
    }

    /// Base-10 logarithm. Requires unitless and value > 0.
    pub fn log10(&self) -> Result<f64, String> {
        if !self.is_unitless() { return Err("log10 requires a unitless quantity".to_string()); }
        if self.value <= 0.0 { return Err("log10 domain error (value <= 0)".to_string()); }
        Ok(self.value.log10())
    }

    // ---- Math: trigonometry (requires angle dimension or unitless) ----
    /// Check if the variable has angle dimension (only rad exponent is non-zero)
    fn is_angle(&self) -> bool {
        // Angle dimension: [0, 0, 0, 0, 0, 0, 0, 1] (only rad exponent is 1)
        for i in 0..units::BASE_UNITS_SIZE - 1 {
            if self.unit[i] != 0.0 {
                return false;
            }
        }
        self.unit[units::BASE_UNITS_SIZE - 1] == 1.0
    }

    /// Sine function. Requires angle (radians).
    pub fn sin(&self) -> Result<f64, String> {
        if !self.is_angle() { 
            return Err("sin requires an angle quantity".to_string()); 
        }
        Ok(self.value.sin())
    }

    /// Cosine function. Requires angle (radians).
    pub fn cos(&self) -> Result<f64, String> {
        if !self.is_angle() { 
            return Err("cos requires an angle quantity".to_string()); 
        }
        Ok(self.value.cos())
    }

    /// Tangent function. Requires angle (radians).
    pub fn tan(&self) -> Result<f64, String> {
        if !self.is_angle() { 
            return Err("tan requires an angle quantity".to_string()); 
        }
        Ok(self.value.tan())
    }

    /// Arcsine function. Requires unitless value in [-1, 1]. Returns angle in radians.
    pub fn asin(&self) -> Result<DimensionalVariable, String> {
        if !self.is_unitless() {
            return Err("asin requires a unitless quantity".to_string());
        }
        if self.value < -1.0 || self.value > 1.0 {
            return Err("asin requires a value in the range [-1, 1]".to_string());
        }
        let mut unit = [0.0; units::BASE_UNITS_SIZE];
        unit[units::BASE_UNITS_SIZE - 1] = 1.0; // radians
        Ok(DimensionalVariable { value: self.value.asin(), unit })
    }

    /// Arccosine function. Requires unitless value in [-1, 1]. Returns angle in radians.
    pub fn acos(&self) -> Result<DimensionalVariable, String> {
        if !self.is_unitless() {
            return Err("acos requires a unitless quantity".to_string());
        }
        if self.value < -1.0 || self.value > 1.0 {
            return Err("acos requires a value in the range [-1, 1]".to_string());
        }
        let mut unit = [0.0; units::BASE_UNITS_SIZE];
        unit[units::BASE_UNITS_SIZE - 1] = 1.0; // radians
        Ok(DimensionalVariable { value: self.value.acos(), unit })
    }

    /// Arctangent function. Requires unitless value. Returns angle in radians.
    pub fn atan(&self) -> Result<DimensionalVariable, String> {
        if !self.is_unitless() {
            return Err("atan requires a unitless quantity".to_string());
        }
        let mut unit = [0.0; units::BASE_UNITS_SIZE];
        unit[units::BASE_UNITS_SIZE - 1] = 1.0; // radians
        Ok(DimensionalVariable { value: self.value.atan(), unit })
    }

    // ---- Scalar helpers on single values ----
    /// Negate the value, keeping the same unit.
    pub fn neg(&self) -> DimensionalVariable {
        DimensionalVariable { value: -self.value, unit: self.unit }
    }

    /// Returns the absolute value, keeping the same unit.
    pub fn abs(&self) -> DimensionalVariable {
        DimensionalVariable { value: self.value.abs(), unit: self.unit }
    }
 
}

impl std::fmt::Display for DimensionalVariable {
    /// Formats the DimensionalVariable as a string in the form "value unit".
    /// 
    /// The unit is displayed in fraction style (e.g., "m/s^2") with:
    /// - Positive exponents in the numerator
    /// - Negative exponents in the denominator (as positive values)
    /// - Exponents of 1 are omitted
    /// - Units with exponent 0 are omitted
    /// - Unitless quantities show "(unitless)"
    /// 
    /// Examples:
    /// - 9.81 m/s^2 for acceleration
    /// - 100 kg*m^2/s^2 for energy
    /// - 3.14 rad for angle
    /// - 5 (unitless) for dimensionless quantities
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut numerator_parts: Vec<String> = Vec::new();
        let mut denominator_parts: Vec<String> = Vec::new();

        for (i, &exp) in self.unit.iter().enumerate() {
            if exp == 0.0 {
                continue;
            }

            let unit_symbol = units::BASE_UNITS[i];

            if exp > 0.0 {
                if exp == 1.0 {
                    numerator_parts.push(unit_symbol.to_string());
                } else if exp == exp.trunc() {
                    // Integer exponent
                    numerator_parts.push(format!("{}^{}", unit_symbol, exp as i32));
                } else {
                    // Fractional exponent
                    numerator_parts.push(format!("{}^{}", unit_symbol, exp));
                }
            } else {
                let abs_exp = exp.abs();
                if abs_exp == 1.0 {
                    denominator_parts.push(unit_symbol.to_string());
                } else if abs_exp == abs_exp.trunc() {
                    // Integer exponent
                    denominator_parts.push(format!("{}^{}", unit_symbol, abs_exp as i32));
                } else {
                    // Fractional exponent
                    denominator_parts.push(format!("{}^{}", unit_symbol, abs_exp));
                }
            }
        }

        let unit_str = if numerator_parts.is_empty() && denominator_parts.is_empty() {
            "(unitless)".to_string()
        } else if denominator_parts.is_empty() {
            numerator_parts.join("*")
        } else if numerator_parts.is_empty() {
            format!("1/{}", denominator_parts.join("*"))
        } else {
            format!("{}/{}", numerator_parts.join("*"), denominator_parts.join("*"))
        };

        write!(f, "{} {}", self.value, unit_str)
    }
}

/// Arcsin function for f64 input, returns DimensionalVariable in radians.
pub fn asin(x: f64) -> Result<DimensionalVariable, String> {
    return DimensionalVariable::new(x, "").unwrap().asin();
}

/// Arccos function for f64 input, returns DimensionalVariable in radians.
pub fn acos(x: f64) -> Result<DimensionalVariable, String> {
    return DimensionalVariable::new(x, "").unwrap().acos();
}

/// Arctan function for f64 input, returns DimensionalVariable in radians.
pub fn atan(x: f64) -> Result<DimensionalVariable, String> {
    return DimensionalVariable::new(x, "").unwrap().atan();
}

/// Convert a unit string like "m/s^2" or "kg-m/s^2" into base unit exponents and a conversion factor.
/// Returns an error if the unit string is invalid or contains unknown units.
fn unit_str_to_base_unit(units_str: &str) -> Result<([f64; units::BASE_UNITS_SIZE], f64), String> {

    // Start by removing any parentheses or brackets
    let cleaned_units_str = units_str.replace(['(', ')', '[', ']'], "");

    // Split the cleaned string by '/' to separate numerator and denominator
    let parts: Vec<&str> = cleaned_units_str.split('/').collect();
    if parts.len() > 2 {
        return Err("Unit string can only have one '/'".to_string());
    }

    let mut base_unit =  [0.0; units::BASE_UNITS_SIZE];
    let mut conversion_factor: f64 = 1.0;

    for i in 0..parts.len() {
        // Detect whether it's the numerator or denominator
        let denominator_multiplier = if i == 1 { -1 } else { 1 };

        // Split by '-' to handle individual units, but keep '-' that is an exponent sign (after '^')
        let units: Vec<&str> = {
            let s = parts[i];
            let mut out = Vec::new();
            let mut start = 0usize;
            let mut prev: Option<char> = None;
            for (idx, ch) in s.char_indices() {
                if ch == '-' && prev != Some('^') {
                    if idx > start {
                        out.push(&s[start..idx]);
                    }
                    start = idx + ch.len_utf8();
                }
                prev = Some(ch);
            }
            if start < s.len() {
                out.push(&s[start..]);
            }
            out
        };
        for unit_str in units {

            let (base, power) = read_unit_power(unit_str)?;

            let unit_map = units::unit_map();
            let unit = unit_map.get(base)
                .ok_or_else(|| format!("Unknown unit: {}", base))?; 

            for j in 0..units::BASE_UNITS_SIZE {
                base_unit[j] += unit.base_unit[j] * (power * denominator_multiplier) as f64;
            }

            // Apply the conversion factor
            conversion_factor *= unit.conversion_factor.powi(power * denominator_multiplier);
        }
    }

    return Ok((base_unit, conversion_factor));
}

/// Parse a token like "m3", "m-2", or "m^3"/"m^-2" into (base, power).
/// If no trailing exponent is found, defaults to power = 1.
/// Returns an error if a trailing '^' has no number.
fn read_unit_power(unit: &str) -> Result<(&str, i32), String> {
    let u = unit.trim();
    if u.is_empty() {
        return Err("Empty unit token".to_string());
    }

    let bytes = u.as_bytes();

    // Find the trailing digits
    let mut end = u.len();
    while end > 0 && bytes[end - 1].is_ascii_digit() {
        end -= 1;
    }

    if end == u.len() {
        // No trailing digits. If it ends with '^', that's an error; otherwise power = 1.
        if end > 0 && bytes[end - 1] == b'^' {
            return Err(format!("Missing exponent after '^' in \"{}\"", u));
        }
        return Ok((u, 1));
    }

    let mut start = end;
    if start > 0 && (bytes[start - 1] == b'-') {
        start -= 1;
    }

    let exp_str = &u[start..];
    let exp: i32 = exp_str
        .parse()
        .map_err(|_| format!("Unable to read numeric power from \"{}\"", u))?;

    // Base is everything before the exponent; strip a trailing '^' if present.
    let mut base_end = start;
    if base_end > 0 && bytes[base_end - 1] == b'^' {
        base_end -= 1;
    }
    let base = u[..base_end].trim();
    if base.is_empty() {
        return Err(format!("Missing unit symbol before exponent in \"{}\"", u));
    }

    Ok((base, exp))
}

// ---- Helpers for unit arithmetic ----
/// Add two unit exponent arrays element-wise.
fn add_unit_exponents(a: [f64; units::BASE_UNITS_SIZE], b: [f64; units::BASE_UNITS_SIZE]) -> [f64; units::BASE_UNITS_SIZE] {
    let mut out = a;
    for i in 0..units::BASE_UNITS_SIZE { out[i] += b[i]; }
    out
}

/// Subtract two unit exponent arrays element-wise.
fn sub_unit_exponents(a: [f64; units::BASE_UNITS_SIZE], b: [f64; units::BASE_UNITS_SIZE]) -> [f64; units::BASE_UNITS_SIZE] {
    let mut out = a;
    for i in 0..units::BASE_UNITS_SIZE { out[i] -= b[i]; }
    out
}

// ---- Operator trait impls ----
use std::ops::{Add, Sub, Mul, Div, Neg, AddAssign, SubAssign, MulAssign, DivAssign};
use std::cmp::Ordering;

// Keep only reference-based binary ops to avoid duplication. Autoref handles owned values.
impl<'a, 'b> Add<&'b DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn add(self, rhs: &'b DimensionalVariable) -> Self::Output {
        return self.try_add(rhs).expect("Incompatible units for addition");
    }
}

// Delegating wrappers for owned LHS/RHS
impl Add<DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn add(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Add<&DimensionalVariable>>::add(&self, &rhs)
    }
}

impl<'b> Add<&'b DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn add(self, rhs: &'b DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Add<&DimensionalVariable>>::add(&self, rhs)
    }
}

impl<'a> Add<DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn add(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Add<&DimensionalVariable>>::add(self, &rhs)
    }
}

impl<'a, 'b> Sub<&'b DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn sub(self, rhs: &'b DimensionalVariable) -> Self::Output {
        return self.try_sub(rhs).expect("Incompatible units for subtraction");
    }
}

impl Sub<DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn sub(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Sub<&DimensionalVariable>>::sub(&self, &rhs)
    }
}

impl<'b> Sub<&'b DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn sub(self, rhs: &'b DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Sub<&DimensionalVariable>>::sub(&self, rhs)
    }
}

impl<'a> Sub<DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn sub(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Sub<&DimensionalVariable>>::sub(self, &rhs)
    }
}

impl<'a, 'b> Mul<&'b DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn mul(self, rhs: &'b DimensionalVariable) -> Self::Output {
        DimensionalVariable { value: self.value * rhs.value, unit: add_unit_exponents(self.unit, rhs.unit) }
    }
}

impl Mul<DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn mul(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Mul<&DimensionalVariable>>::mul(&self, &rhs)
    }
}

impl<'b> Mul<&'b DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn mul(self, rhs: &'b DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Mul<&DimensionalVariable>>::mul(&self, rhs)
    }
}

impl<'a> Mul<DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn mul(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Mul<&DimensionalVariable>>::mul(self, &rhs)
    }
}

impl<'a, 'b> Div<&'b DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn div(self, rhs: &'b DimensionalVariable) -> Self::Output {
        DimensionalVariable { value: self.value / rhs.value, unit: sub_unit_exponents(self.unit, rhs.unit) }
    }
}

impl Div<DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn div(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Div<&DimensionalVariable>>::div(&self, &rhs)
    }
}

impl<'b> Div<&'b DimensionalVariable> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn div(self, rhs: &'b DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Div<&DimensionalVariable>>::div(&self, rhs)
    }
}

impl<'a> Div<DimensionalVariable> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn div(self, rhs: DimensionalVariable) -> Self::Output {
        <&DimensionalVariable as Div<&DimensionalVariable>>::div(self, &rhs)
    }
}

// Assignment ops: implement only for &DimensionalVariable RHS. Owned RHS will autoref.
impl AddAssign<&DimensionalVariable> for DimensionalVariable {
    fn add_assign(&mut self, rhs: &DimensionalVariable) {
        *self = self.try_add(rhs).expect("Incompatible units for addition assignment");
    }
}

impl SubAssign<&DimensionalVariable> for DimensionalVariable {
    fn sub_assign(&mut self, rhs: &DimensionalVariable) {
        *self = self.try_sub(rhs).expect("Incompatible units for subtraction assignment");
    }
}

impl MulAssign<&DimensionalVariable> for DimensionalVariable {
    fn mul_assign(&mut self, rhs: &DimensionalVariable) {
        self.value *= rhs.value;
        self.unit = add_unit_exponents(self.unit, rhs.unit);
    }
}

impl DivAssign<&DimensionalVariable> for DimensionalVariable {
    fn div_assign(&mut self, rhs: &DimensionalVariable) {
        self.value /= rhs.value;
        self.unit = sub_unit_exponents(self.unit, rhs.unit);
    }
}

// Scalar ops
impl<'a> Mul<f64> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn mul(self, rhs: f64) -> Self::Output {
        DimensionalVariable { value: self.value * rhs, unit: self.unit }
    }
}

impl Mul<f64> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn mul(self, rhs: f64) -> Self::Output {
        <&DimensionalVariable as Mul<f64>>::mul(&self, rhs)
    }
}

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

impl<'a> Div<f64> for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn div(self, rhs: f64) -> Self::Output {
        DimensionalVariable { value: self.value / rhs, unit: self.unit }
    }
}

impl Div<f64> for DimensionalVariable {
    type Output = DimensionalVariable;
    fn div(self, rhs: f64) -> Self::Output {
        <&DimensionalVariable as Div<f64>>::div(&self, rhs)
    }
}

impl DivAssign<f64> for DimensionalVariable {
    fn div_assign(&mut self, rhs: f64) {
        self.value /= rhs;
    }
}

// Symmetric scalar ops
impl<'a> Mul<&'a DimensionalVariable> for f64 {
    type Output = DimensionalVariable;
    fn mul(self, rhs: &'a DimensionalVariable) -> Self::Output {
        DimensionalVariable { value: self * rhs.value, unit: rhs.unit }
    }
}

impl Mul<DimensionalVariable> for f64 {
    type Output = DimensionalVariable;
    fn mul(self, rhs: DimensionalVariable) -> Self::Output {
        <f64 as Mul<&DimensionalVariable>>::mul(self, &rhs)
    }
}

impl<'a> Div<&'a DimensionalVariable> for f64 {
    type Output = DimensionalVariable;
    fn div(self, rhs: &'a DimensionalVariable) -> Self::Output {
    DimensionalVariable { value: self / rhs.value, unit: sub_unit_exponents([0.0; units::BASE_UNITS_SIZE], rhs.unit) }
    }
}

impl Div<DimensionalVariable> for f64 {
    type Output = DimensionalVariable;
    fn div(self, rhs: DimensionalVariable) -> Self::Output {
        <f64 as Div<&DimensionalVariable>>::div(self, &rhs)
    }
}

// Unary negation on references and delegating owned variant
impl<'a> Neg for &'a DimensionalVariable {
    type Output = DimensionalVariable;
    fn neg(self) -> Self::Output {
        DimensionalVariable { value: -self.value, unit: self.unit }
    }
}

impl Neg for DimensionalVariable {
    type Output = DimensionalVariable;
    fn neg(self) -> Self::Output {
        <&DimensionalVariable as Neg>::neg(&self)
    }
}

// ---- Comparisons: equalities and ordering ----
impl PartialEq for DimensionalVariable {
    fn eq(&self, other: &Self) -> bool {
        if !self.check_compatibility(other.unit) {
            return false;
        }
        self.value == other.value
    }
}

impl PartialOrd for DimensionalVariable {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if !self.check_compatibility(other.unit) { return None; }
        self.value.partial_cmp(&other.value)
    }
}

#[cfg(test)]
mod tests {
    use super::read_unit_power;

    #[test]
    fn read_unit_power_basic_cases() {
        assert_eq!(read_unit_power("m").unwrap(), ("m", 1));
        assert_eq!(read_unit_power("m3").unwrap(), ("m", 3));
        assert_eq!(read_unit_power("m^3").unwrap(), ("m", 3));
        assert_eq!(read_unit_power("m^-2").unwrap(), ("m", -2));
        assert_eq!(read_unit_power("m-2").unwrap(), ("m", -2));
        assert_eq!(read_unit_power("  kg^2 ").unwrap(), ("kg", 2));
        assert_eq!(read_unit_power("undef").unwrap(), ("undef", 1));    // We don't check for known units here
    }

    #[test]
    fn read_unit_power_errors() {
        assert!(read_unit_power("").is_err());
        let err = read_unit_power("m^").unwrap_err();
        assert!(err.contains("Missing exponent"));
        let err = read_unit_power("^2").unwrap_err();
        assert!(err.contains("Missing unit symbol"));
    }
}