ferrunitas 0.4.0

A type-safe unit conversion library with compile-time dimensional analysis
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
//! Strongly typed value bound to a specific unit (`Measure<U>` runtime wrapper).
//! Main way to interact with unit-coupled values, and all arithmetic operations are implemented here.

use core::marker::PhantomData;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};

use crate::Real;
use crate::model::dimension::Dimensioned;
use crate::model::quantity::{Quantity, QuantityMarker, QuantityTag};
use crate::model::unit::Unit;

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
/// Runtime holder of a numeric value tagged with a concrete unit type `U`.
///
/// `Measure` represents a physical quantity with a specific unit (like "5 metres" or "10 kilograms").
/// It stores the value in the unit's own scale and provides type-safe operations and conversions.
///
/// Use `Measure` when you need to work with specific units and want explicit unit semantics.
/// For generic dimensional arithmetic, consider using [`Quantity`] instead.
///
/// # Key Features
///
/// - **Type Safety**: Prevents mixing incompatible units at compile time
/// - **Unit Conversions**: Convert between compatible units with zero runtime cost
/// - **Arithmetic Operations**: Add, subtract, multiply, and divide with proper dimensional checking
/// - **Display**: Automatically formats with appropriate unit symbols
///
/// # Examples
///
/// ```
/// use ferrunitas::system::*;
/// use ferrunitas::{Measure, Unit};
///
/// // Create measures with specific units
/// let length = Metre::new(100.0);
/// let time = Second::new(10.0);
///
/// // Convert between compatible units
/// let feet: Measure<Foot> = length.convert();
/// let minutes: Measure<Minute> = time.convert();
///
/// // Arithmetic operations work across compatible units
/// let longer_length = length + Centimetre::new(50.0);  // 100 m + 50 cm = 100.5 m
///
/// // Multiplication/division creates quantities with proper dimensions
/// let velocity: Velocity = length / time;  // 100 m / 10 s = 10 m/s
///
/// // Display includes unit symbols
/// println!("Distance: {}", length);  // "100 m"
/// ```
pub struct Measure<U: Unit> {
    pub(crate) value: Real,
    _phantom: PhantomData<U>,
}

impl<U: Unit> Measure<U> {
    /// Create a new measure from a value expressed in unit `U`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ferrunitas::system::*;
    /// use ferrunitas::{Measure, Unit};
    ///
    /// let distance = Metre::new(100.5);
    /// assert_eq!(distance.value(), 100.5);
    ///
    /// let mass = Kilogram::new(5i16);  // Works with any type that implements Into<Real>
    /// assert_eq!(mass.value(), 5.0);
    /// ```
    pub fn new(value: impl Into<Real>) -> Self {
        Self {
            value: value.into(),
            _phantom: PhantomData,
        }
    }

    /// Raw numeric value in unit `U` (no conversion).
    ///
    /// This returns the value as stored internally, in the specific unit this measure represents.
    /// No unit conversion is performed.
    ///
    /// # Examples
    ///
    /// ```
    /// use ferrunitas::{system::*, Unit};
    ///
    /// let distance = Metre::new(42.5);
    /// assert_eq!(distance.value(), 42.5);
    ///
    /// let feet = Foot::new(10.0);
    /// assert_eq!(feet.value(), 10.0);  // Still 10.0, not converted to metres
    /// ```
    pub fn value(&self) -> Real {
        self.value
    }

    /// Construct from a quantity of the same dimension.
    ///
    /// Takes a dimensioned quantity and converts it to a measure with this specific unit.
    /// The quantity's raw SI value is divided by the unit's conversion factor and shifted by the unit's offset, if present.
    ///
    /// # Examples
    ///
    /// ```
    /// use ferrunitas::system::*;
    /// use ferrunitas::{Measure, Unit};
    ///
    /// // Create a length quantity (internally stored in SI base units)
    /// let length: Length = Metre::new(100.0).into_q();
    ///
    /// // Convert to different unit measures
    /// let metres = Measure::<Metre>::from_q(length);
    /// let feet = Measure::<Foot>::from_q(length);
    ///
    /// assert_eq!(metres.value(), 100.0);
    /// assert!((feet.value() - 328.084).abs() < 0.001);  // ~328 feet
    /// ```
    pub fn from_q(q: U::Quantity) -> Self {
        Self::new((q.raw_value() - U::OFFSET) / U::FACTOR)
    }
    /// Convert into a dimensioned quantity using `U`'s factor.
    ///
    /// Transforms this measure into a generic quantity of the same dimension.
    /// The value is multiplied by the unit's conversion factor (and shifted by the unit's offset) to get the SI base unit value.
    /// Quantities are useful for dimensional arithmetic and generic calculations.
    ///
    /// # Examples
    ///
    /// ```
    /// use ferrunitas::{system::*, Unit};
    ///
    /// let distance = Foot::new(10.0);
    /// let length_quantity: Length = distance.into_q();
    ///
    /// let time = Second::new(5.0);
    /// let time_quantity: Time = time.into_q();
    ///
    /// // Now we can do dimensional arithmetic
    /// let velocity: Velocity = length_quantity / time_quantity;
    /// let speed = velocity.as_measure::<MetrePerSecond>();
    ///
    /// assert!((speed.value() - 0.6096).abs() < 0.0001);  // 10 ft / 5 s ≈ 0.6096 m/s
    /// ```
    pub fn into_q(self) -> U::Quantity {
        U::Quantity::new(self.value * U::FACTOR + U::OFFSET)
    }

    /// Convert to another unit of the same dimension.
    ///
    /// Performs a unit conversion between compatible units (same physical dimension).
    /// The conversion goes through the quantity representation: measure → quantity → measure.
    ///
    /// # Examples
    ///
    /// ```
    /// use ferrunitas::system::*;
    /// use ferrunitas::{Measure, Unit};
    ///
    /// let metres = Metre::new(1000.0);
    /// let kilometres: Measure<Kilometre> = metres.convert();
    /// let feet: Measure<Foot> = metres.convert();
    ///
    /// assert_eq!(kilometres.value(), 1.0);  // 1000 m = 1 km
    /// assert!((feet.value() - 3280.84).abs() < 0.01);  // 1000 m ≈ 3280.84 ft
    ///
    /// // Type inference can determine the target unit
    /// let inches: Measure<Inch> = metres.convert();
    /// assert!((inches.value() - 39370.1).abs() < 0.1);
    /// ```
    pub fn convert<UOther>(&self) -> Measure<UOther>
    where
        UOther: Unit<Quantity = U::Quantity>,
    {
        Measure::from_q(self.into_q())
    }

    /// Equality check across different units of same dimension.
    ///
    /// Compares two measures by converting both to their underlying quantities
    /// and checking if they represent the same physical amount, regardless of units.
    /// Typical PartialEq requires type equality, this extends the equality
    /// check to measures of the same quantity.
    ///
    /// # Examples
    ///
    /// ```
    /// use ferrunitas::{system::*, Unit};
    ///
    /// let metre = Metre::new(1.0);
    /// let centimetres = Centimetre::new(100.0);
    /// let kilometre = Kilometre::new(0.001);
    ///
    /// assert!(metre.is_equal_to(&centimetres));  // 1 m = 100 cm
    /// assert!(metre.is_equal_to(&kilometre));    // 1 m = 0.001 km
    ///
    /// // Regular == only works for same unit types
    /// assert_eq!(metre, Metre::new(1.0));
    /// // assert_eq!(metre, centimetres);  // This would not compile
    /// ```
    pub fn is_equal_to<UOther>(&self, other: &Measure<UOther>) -> bool
    where
        UOther: Unit<Quantity = U::Quantity>,
    {
        self.into_q() == other.into_q()
    }

    // --------------------

    /// Const version of [`new`](Self::new) for compile-time measure creation.
    ///
    /// Creates a new measure from a value at compile time. This is useful for defining
    /// const measures or in const contexts where the regular `new` method cannot be used.
    pub(crate) const fn new_const(value: Real) -> Self {
        Self {
            value,
            _phantom: PhantomData,
        }
    }

    /// Const version of [`value`](Self::value) for compile-time value access.
    ///
    /// Returns the raw numeric value at compile time. This is useful in const contexts
    /// where the regular `value` method cannot be used.
    pub(crate) const fn value_const(&self) -> Real {
        self.value
    }
}

impl<U: Unit> core::fmt::Display for Measure<U> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.value, f)?;
        write!(f, " {}", U::ABBREV)
    }
}

// ---------------------------------------
// Operations
// ---------------------------------------

/// Addition - works on different units but requires same quantity
impl<U1, U2> Add<Measure<U2>> for Measure<U1>
where
    U1: Unit,
    U2: Unit<Quantity = U1::Quantity>,
    U1::Quantity: Add<U2::Quantity, Output = U1::Quantity>,
{
    type Output = Self;

    fn add(self, rhs: Measure<U2>) -> Self::Output {
        Self::from_q(self.into_q() + rhs.into_q())
    }
}

/// Addition - with another quantity
impl<U, D, T> Add<Quantity<D, T>> for Measure<U>
where
    U: Unit<Quantity = Quantity<D, T>>,
    D: Dimensioned + Add<Output = D>,
    T: QuantityTag,
{
    type Output = Self;

    fn add(self, rhs: Quantity<D, T>) -> Self::Output {
        Self::from_q(self.into_q() + rhs)
    }
}

/// Assigned Addition - works on different units but requires same quantity
impl<U1, U2> AddAssign<Measure<U2>> for Measure<U1>
where
    U1: Unit,
    U2: Unit<Quantity = U1::Quantity>,
    U1::Quantity: Add<U2::Quantity, Output = U1::Quantity>,
{
    fn add_assign(&mut self, rhs: Measure<U2>) {
        self.value += rhs.convert::<U1>().value;
    }
}

/// Assigned Addition - with another quantity
impl<U, D, T> AddAssign<Quantity<D, T>> for Measure<U>
where
    U: Unit<Quantity = Quantity<D, T>>,
    D: Dimensioned + Add<Output = D>,
    T: QuantityTag,
{
    fn add_assign(&mut self, rhs: Quantity<D, T>) {
        self.value += rhs.as_measure::<U>().value;
    }
}

/// Subtraction - works on different units but requires same quantity
impl<U1, U2> Sub<Measure<U2>> for Measure<U1>
where
    U1: Unit,
    U2: Unit<Quantity = U1::Quantity>,
    U1::Quantity: Sub<U2::Quantity, Output = U1::Quantity>,
{
    type Output = Self;

    fn sub(self, rhs: Measure<U2>) -> Self::Output {
        Self::from_q(self.into_q() - rhs.into_q())
    }
}

/// Subtraction - with another quantity
impl<U, D, T> Sub<Quantity<D, T>> for Measure<U>
where
    U: Unit<Quantity = Quantity<D, T>>,
    D: Dimensioned + Sub<Output = D>,
    T: QuantityTag,
{
    type Output = Self;

    fn sub(self, rhs: Quantity<D, T>) -> Self::Output {
        Self::from_q(self.into_q() - rhs)
    }
}

/// Assigned Subtraction - works on different units but requires same quantity
impl<U1, U2> SubAssign<Measure<U2>> for Measure<U1>
where
    U1: Unit,
    U2: Unit<Quantity = U1::Quantity>,
    U1::Quantity: Sub<U2::Quantity, Output = U1::Quantity>,
{
    fn sub_assign(&mut self, rhs: Measure<U2>) {
        self.value -= rhs.convert::<U1>().value;
    }
}

/// Assigned Subtraction - with another quantity
impl<U, D, T> SubAssign<Quantity<D, T>> for Measure<U>
where
    U: Unit<Quantity = Quantity<D, T>>,
    D: Dimensioned + Sub<Output = D>,
    T: QuantityTag,
{
    fn sub_assign(&mut self, rhs: Quantity<D, T>) {
        self.value -= rhs.as_measure::<U>().value;
    }
}

/// Multiplication - just with unit assumes measure of 1.0
impl<U1: Unit, U2: Unit> Mul<U2> for Measure<U1>
where
    U1::Quantity: Mul<U2::Quantity>,
{
    type Output = <U1::Quantity as Mul<U2::Quantity>>::Output;

    fn mul(self, _rhs: U2) -> Self::Output {
        self.into_q() * U2::new(1.0).into_q()
    }
}

/// Multiplication - works with any unit but result is quantity
impl<U1: Unit, U2: Unit> Mul<Measure<U2>> for Measure<U1>
where
    U1::Quantity: Mul<U2::Quantity>,
{
    type Output = <U1::Quantity as Mul<U2::Quantity>>::Output;

    fn mul(self, rhs: Measure<U2>) -> Self::Output {
        self.into_q() * rhs.into_q()
    }
}

/// Multiplication - with another quantity
impl<U, D1, D2, T1, T2> Mul<Quantity<D2, T2>> for Measure<U>
where
    U: Unit<Quantity = Quantity<D1, T1>>,
    D1: Dimensioned + Mul<D2>,
    D2: Dimensioned,
    T1: QuantityTag,
    T2: QuantityTag,
    <D1 as Mul<D2>>::Output: Dimensioned,
{
    type Output = <Quantity<D1, T1> as Mul<Quantity<D2, T2>>>::Output;

    fn mul(self, rhs: Quantity<D2, T2>) -> Self::Output {
        self.into_q() * rhs
    }
}

/// Division - just with unit assumes measure of 1.0
impl<U1: Unit, U2: Unit> Div<U2> for Measure<U1>
where
    U1::Quantity: Div<U2::Quantity>,
{
    type Output = <U1::Quantity as Div<U2::Quantity>>::Output;

    fn div(self, _rhs: U2) -> Self::Output {
        self.into_q() / U2::new(1.0).into_q()
    }
}

/// Division - works with any unit but result is quantity
impl<U1: Unit, U2: Unit> Div<Measure<U2>> for Measure<U1>
where
    U1::Quantity: Div<U2::Quantity>,
{
    type Output = <U1::Quantity as Div<U2::Quantity>>::Output;

    fn div(self, rhs: Measure<U2>) -> Self::Output {
        self.into_q() / rhs.into_q()
    }
}

/// Division - with another quantity
impl<U, D1, D2, T1, T2> Div<Quantity<D2, T2>> for Measure<U>
where
    U: Unit<Quantity = Quantity<D1, T1>>,
    D1: Dimensioned + Div<D2>,
    D2: Dimensioned,
    T1: QuantityTag,
    T2: QuantityTag,
    <D1 as Div<D2>>::Output: Dimensioned,
{
    type Output = <Quantity<D1, T1> as Div<Quantity<D2, T2>>>::Output;

    fn div(self, rhs: Quantity<D2, T2>) -> Self::Output {
        self.into_q() / rhs
    }
}

/// RHS Scalar multiplication - no effect on unit or quantity
impl<U: Unit> Mul<Real> for Measure<U> {
    type Output = Self;

    fn mul(self, scalar: Real) -> Self::Output {
        Self::new(self.value * scalar)
    }
}

/// LHS Scalar multiplication - no effect on unit or quantity
impl<U: Unit> Mul<Measure<U>> for Real {
    type Output = Measure<U>;

    fn mul(self, rhs: Measure<U>) -> Self::Output {
        Measure::new(self * rhs.value)
    }
}

/// RHS Assigned scalar multiplication - no effect on unit or quantity
impl<U: Unit> MulAssign<Real> for Measure<U> {
    fn mul_assign(&mut self, scalar: Real) {
        self.value *= scalar;
    }
}

/// RHS Scalar division - no effect on unit or quantity
impl<U: Unit> Div<Real> for Measure<U> {
    type Output = Self;

    fn div(self, scalar: Real) -> Self::Output {
        Self::new(self.value / scalar)
    }
}

/// LHS Scalar division - has to invert quantity, so result cant be unit
impl<U: Unit> Div<Measure<U>> for Real
where
    Real: Div<U::Quantity>,
{
    type Output = <Real as Div<U::Quantity>>::Output;

    fn div(self, rhs: Measure<U>) -> Self::Output {
        self / rhs.into_q()
    }
}

/// RHS Assigned scalar division - no effect on unit or quantity
impl<U: Unit> DivAssign<Real> for Measure<U> {
    fn div_assign(&mut self, scalar: Real) {
        self.value /= scalar;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{common::assert_almost_equal, system::*};
    use alloc::format;

    #[test]
    fn test_new_and_value() {
        // Test basic construction and value access
        let distance = Measure::<Metre>::new(100.5);
        assert_eq!(distance.value(), 100.5);

        let mass = Measure::<Kilogram>::new(5i16); // Test with integer
        assert_eq!(mass.value(), 5.0);

        let time = Measure::<Second>::new(2.34);
        assert_eq!(time.value(), 2.34);

        // Test with negative values
        let temperature = Measure::<Kelvin>::new(-273.15);
        assert_eq!(temperature.value(), -273.15);
    }

    #[test]
    fn test_from_q_and_into_q() {
        // Test round-trip conversion: measure -> quantity -> measure
        let original = Metre::new(100.0);
        let quantity = original.into_q();
        let restored = Measure::<Metre>::from_q(quantity);

        assert_eq!(original.value(), restored.value());
        assert_eq!(original, restored);

        // Test other direction
        let mass_quantity = Mass::new(2.5);
        let mass_kg = Measure::<Kilogram>::from_q(mass_quantity);
        let mass_restored = mass_kg.into_q();
        assert_eq!(mass_quantity.raw_value(), mass_restored.raw_value());

        // Test conversion through different unit
        let mass_g = Measure::<Gram>::from_q(mass_quantity);
        assert_eq!(mass_g.value(), 2500.0); // 2.5 kg = 2500 g
    }

    #[test]
    fn test_convert() {
        // Test unit conversions
        let metres = Metre::new(1000.0);

        // Convert to kilometres
        let kilometres: Measure<Kilometre> = metres.convert();
        assert_eq!(kilometres.value(), 1.0); // 1000 m = 1 km

        // Convert to centimetres
        let centimetres: Measure<Centimetre> = metres.convert();
        assert_eq!(centimetres.value(), 100000.0); // 1000 m = 100000 cm

        // Test with mass units
        let kilograms = Kilogram::new(2.0);
        let grams: Measure<Gram> = kilograms.convert();
        assert_almost_equal!(grams.value(), 2000.0); // 2 kg = 2000 g

        // Test with time units
        let minutes = Minute::new(2.0);
        let seconds: Measure<Second> = minutes.convert();
        assert_eq!(seconds.value(), 120.0); // 2 min = 120 s
    }

    #[test]
    fn test_is_equal_to() {
        // Test equality across different units of same dimension
        let metre = Metre::new(1.0);
        let centimetres = Centimetre::new(100.0);
        let millimetres = Millimetre::new(1000.0);
        let kilometre = Kilometre::new(0.001);

        // Test equality
        assert!(metre.is_equal_to(&centimetres)); // 1 m = 100 cm
        assert!(metre.is_equal_to(&millimetres)); // 1 m = 1000 mm
        assert!(metre.is_equal_to(&kilometre)); // 1 m = 0.001 km

        // Test symmetry
        assert!(centimetres.is_equal_to(&metre));
        assert!(kilometre.is_equal_to(&metre));

        // Test inequality
        let different_metre = Metre::new(2.0);
        assert!(!metre.is_equal_to(&different_metre));

        // Test with mass units
        let kilogram = Kilogram::new(1.0);
        let grams = Gram::new(1000.0);
        assert!(kilogram.is_equal_to(&grams)); // 1 kg = 1000 g
    }

    #[test]
    #[allow(clippy::clone_on_copy)]
    fn test_derived_traits() {
        let measure1 = Metre::new(42.0);
        let measure2 = Metre::new(42.0);
        let measure3 = Metre::new(24.0);

        // Test Debug
        let debug_output = format!("{:?}", measure1);
        assert!(debug_output.contains("Measure"));
        assert!(debug_output.contains("42"));

        // Test Clone
        let cloned = measure1.clone();
        assert_eq!(measure1, cloned);

        // Test Copy (automatic via assignment)
        let copied = measure1;
        assert_eq!(measure1, copied);

        // Test PartialEq
        assert_eq!(measure1, measure2);
        assert_ne!(measure1, measure3);

        // Test PartialOrd
        assert!(measure1 == measure2);
        assert!(measure1 != measure3);
        assert!(measure3 < measure1);
        assert!(measure1 > measure3);
    }

    #[test]
    fn test_const_functions_equivalence() {
        // Test that const functions return the same values as their non-const equivalents
        // Use let instead of const to avoid const-fold optimization

        // Test new_const vs new
        let const_measure: Measure<Metre> = Measure::new_const(42.5);
        let regular_measure = Metre::new(42.5);

        assert_eq!(const_measure.value(), regular_measure.value());
        assert_eq!(const_measure, regular_measure);

        // Test value_const vs value
        let const_value: Real = const_measure.value_const();
        let regular_value = regular_measure.value();

        assert_eq!(const_value, regular_value);
        assert_eq!(const_value, 42.5);

        // Test with different unit and value
        let const_mass: Measure<Kilogram> = Measure::new_const(123.456);
        let regular_mass = Kilogram::new(123.456);

        assert_eq!(const_mass.value_const(), regular_mass.value());
        assert_eq!(const_mass, regular_mass);
    }
}