iridium-units 0.1.0

A high-performance runtime unit-of-measure library for Rust
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
//! Unit types and operations.
//!
//! This module provides the [`Unit`] type, which represents a physical unit
//! like meter, kilogram, or m/s. Most users interact with units through
//! the predefined constants in [`crate::systems`] (e.g., `M`, `KG`, `HZ`).
//!
//! # Creating quantities
//!
//! ```
//! use iridium_units::prelude::*;
//!
//! let distance = 100.0 * KM;
//! let time = 2.0 * H;
//! let speed = &distance / &time;
//!
//! // Convert to a different unit
//! let speed_ms = speed.to(M / S).unwrap();
//! assert!((speed_ms.value() - 13.8888).abs() < 0.001);
//! ```
//!
//! # Composite units from arithmetic
//!
//! ```
//! use iridium_units::prelude::*;
//!
//! let velocity_unit = M / S;           // m/s
//! let accel_unit = M / S.pow(2);       // m/s²
//! let force_unit = KG * M / S.pow(2);  // kg·m/s² (newton)
//! ```

pub mod base;
pub mod composite;

use crate::dimension::{Dimension, Rational16};
use crate::error::{UnitError, UnitResult};
use base::BaseUnit;
use composite::CompositeUnit;
use std::fmt;
use std::ops::{Div, Mul};

/// A physical unit.
///
/// Units can be base units (like meter), named derived units (like newton),
/// composite units (like m/s), or dimensionless.
///
/// # Examples
///
/// ```
/// use iridium_units::prelude::*;
///
/// // Base units are Copy — use them directly
/// let mass = 10.0 * KG;
///
/// // Arithmetic creates composite units
/// let velocity_unit = KM / H;
///
/// // Check dimensions
/// assert_eq!((M / S).dimension(), (KM / H).dimension());
///
/// // Convert between compatible units
/// let speed = 100.0 * &(KM / H);
/// let in_ms = speed.to(M / S).unwrap();
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum Unit {
    /// A base irreducible unit (meter, second, kilogram, etc.)
    Base(BaseUnit),

    /// A composite unit from arithmetic operations (m/s, kg·m/s², etc.)
    Composite(CompositeUnit),

    /// Dimensionless with a scale factor.
    Dimensionless {
        /// Multiplicative scale factor (1.0 for pure dimensionless).
        scale: f64,
    },
}

impl Unit {
    /// Create a dimensionless unit with scale 1.
    pub fn dimensionless() -> Self {
        Unit::Dimensionless { scale: 1.0 }
    }

    /// Create a dimensionless unit with a scale factor.
    pub fn dimensionless_scaled(scale: f64) -> Self {
        Unit::Dimensionless { scale }
    }

    /// Create a unit from a base unit.
    pub fn from_base(base: &BaseUnit) -> Self {
        Unit::Base(*base)
    }

    /// Get the dimension of this unit.
    pub fn dimension(&self) -> Dimension {
        match self {
            Unit::Base(b) => b.dimension,
            Unit::Composite(c) => c.dimension(),
            Unit::Dimensionless { .. } => Dimension::DIMENSIONLESS,
        }
    }

    /// Get the scale factor relative to SI base units.
    pub fn scale(&self) -> f64 {
        match self {
            Unit::Base(b) => b.scale,
            Unit::Composite(c) => c.total_scale(),
            Unit::Dimensionless { scale } => *scale,
        }
    }

    /// Check if this unit is dimensionless.
    pub fn is_dimensionless(&self) -> bool {
        self.dimension().is_dimensionless()
    }

    /// Get the additive offset relative to the SI base unit.
    ///
    /// Most units have offset 0.0. Offset units like Celsius (273.15)
    /// and Fahrenheit (459.67) use this for affine conversions.
    /// The formula is: `SI_value = (value + offset) * scale`.
    ///
    /// Offsets are only defined for [`Unit::Base`]. Composite units are
    /// treated as interval units, so composing an offset base unit does
    /// **not** preserve its additive offset.
    pub fn offset(&self) -> f64 {
        match self {
            Unit::Base(b) => b.offset,
            Unit::Composite(_) | Unit::Dimensionless { .. } => 0.0,
        }
    }

    /// Check if this unit has an additive offset (e.g., Celsius, Fahrenheit).
    ///
    /// Only true for [`Unit::Base`] values with a non-zero offset.
    pub fn has_offset(&self) -> bool {
        self.offset() != 0.0
    }

    /// Convert a value in this unit to SI base units.
    ///
    /// For pure scale units: `value * scale`
    /// For offset base units: `(value + offset) * scale`
    ///
    /// Affine offsets are only applied for [`Unit::Base`]. Composite
    /// units are converted using scale alone (interval semantics).
    pub fn to_si(&self, value: f64) -> f64 {
        (value + self.offset()) * self.scale()
    }

    /// Convert a value from SI base units to this unit.
    ///
    /// For simple units: `si_value / scale`
    /// For offset units: `si_value / scale - offset`
    pub fn from_si(&self, si_value: f64) -> f64 {
        si_value / self.scale() - self.offset()
    }

    /// Get the conversion factor to convert from this unit to another.
    ///
    /// This returns a single multiplicative factor, which only works for
    /// units without additive offsets. For offset units like Celsius or
    /// Fahrenheit, use [`Quantity::to`](crate::Quantity::to) instead.
    ///
    /// Returns `Err` if the units have incompatible dimensions or if
    /// either unit has an additive offset.
    pub fn conversion_factor(&self, to: &Unit) -> UnitResult<f64> {
        if self.dimension() != to.dimension() {
            return Err(UnitError::DimensionMismatch {
                from: self.to_string(),
                to: to.to_string(),
            });
        }
        // Identity conversion is always valid, even for offset units
        if self == to {
            return Ok(1.0);
        }
        if self.has_offset() || to.has_offset() {
            return Err(UnitError::OffsetConversion {
                from: self.to_string(),
                to: to.to_string(),
            });
        }
        Ok(self.scale() / to.scale())
    }

    /// Convert this unit to a composite representation.
    pub fn to_composite(&self) -> CompositeUnit {
        match self {
            Unit::Base(b) => CompositeUnit::from_base(b.symbol, b.dimension, b.scale),
            Unit::Composite(c) => c.clone(),
            Unit::Dimensionless { scale } => CompositeUnit::dimensionless(*scale),
        }
    }

    /// Raise this unit to a power.
    pub fn pow(&self, exp: impl Into<Rational16>) -> Unit {
        let exp = exp.into();
        if exp.is_zero() {
            return Unit::dimensionless();
        }
        if exp == Rational16::ONE {
            return self.clone();
        }
        Unit::Composite(self.to_composite().pow(exp))
    }

    /// Take the square root of this unit.
    pub fn sqrt(&self) -> Unit {
        self.pow(Rational16::new(1, 2))
    }

    /// Invert this unit (raise to power -1).
    pub fn inv(&self) -> Unit {
        self.pow(Rational16::new(-1, 1))
    }

    /// Get the symbol/string representation for this unit.
    pub fn symbol(&self) -> String {
        match self {
            Unit::Base(b) => b.symbol.to_string(),
            Unit::Composite(c) => c.to_string(),
            Unit::Dimensionless { scale } => {
                if (*scale - 1.0).abs() < 1e-15 {
                    "".to_string()
                } else {
                    format!("{}", scale)
                }
            }
        }
    }
}

impl fmt::Display for Unit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Unit::Base(b) => write!(f, "{}", b.symbol),
            Unit::Composite(c) => write!(f, "{}", c),
            Unit::Dimensionless { scale } => {
                if (*scale - 1.0).abs() < 1e-15 {
                    write!(f, "dimensionless")
                } else {
                    write!(f, "{}", scale)
                }
            }
        }
    }
}

impl From<BaseUnit> for Unit {
    fn from(b: BaseUnit) -> Unit {
        Unit::Base(b)
    }
}

impl From<&BaseUnit> for Unit {
    fn from(b: &BaseUnit) -> Unit {
        Unit::Base(*b)
    }
}

impl From<&Unit> for Unit {
    fn from(u: &Unit) -> Unit {
        u.clone()
    }
}

// Unit * Unit
impl Mul for Unit {
    type Output = Unit;

    fn mul(self, rhs: Unit) -> Unit {
        Unit::Composite(self.to_composite().mul(&rhs.to_composite()))
    }
}

impl Mul for &Unit {
    type Output = Unit;

    fn mul(self, rhs: &Unit) -> Unit {
        Unit::Composite(self.to_composite().mul(&rhs.to_composite()))
    }
}

impl Mul<&Unit> for Unit {
    type Output = Unit;

    fn mul(self, rhs: &Unit) -> Unit {
        Unit::Composite(self.to_composite().mul(&rhs.to_composite()))
    }
}

impl Mul<Unit> for &Unit {
    type Output = Unit;

    fn mul(self, rhs: Unit) -> Unit {
        Unit::Composite(self.to_composite().mul(&rhs.to_composite()))
    }
}

// Unit / Unit
impl Div for Unit {
    type Output = Unit;

    fn div(self, rhs: Unit) -> Unit {
        Unit::Composite(self.to_composite().div(&rhs.to_composite()))
    }
}

impl Div for &Unit {
    type Output = Unit;

    fn div(self, rhs: &Unit) -> Unit {
        Unit::Composite(self.to_composite().div(&rhs.to_composite()))
    }
}

impl Div<&Unit> for Unit {
    type Output = Unit;

    fn div(self, rhs: &Unit) -> Unit {
        Unit::Composite(self.to_composite().div(&rhs.to_composite()))
    }
}

impl Div<Unit> for &Unit {
    type Output = Unit;

    fn div(self, rhs: Unit) -> Unit {
        Unit::Composite(self.to_composite().div(&rhs.to_composite()))
    }
}

// BaseUnit * BaseUnit → Unit
impl Mul for BaseUnit {
    type Output = Unit;

    fn mul(self, rhs: BaseUnit) -> Unit {
        Unit::from(self) * Unit::from(rhs)
    }
}

// BaseUnit / BaseUnit → Unit
impl Div for BaseUnit {
    type Output = Unit;

    fn div(self, rhs: BaseUnit) -> Unit {
        Unit::from(self) / Unit::from(rhs)
    }
}

// BaseUnit * Unit → Unit
impl Mul<Unit> for BaseUnit {
    type Output = Unit;

    fn mul(self, rhs: Unit) -> Unit {
        Unit::from(self) * rhs
    }
}

// Unit * BaseUnit → Unit
impl Mul<BaseUnit> for Unit {
    type Output = Unit;

    fn mul(self, rhs: BaseUnit) -> Unit {
        self * Unit::from(rhs)
    }
}

// BaseUnit / Unit → Unit
impl Div<Unit> for BaseUnit {
    type Output = Unit;

    fn div(self, rhs: Unit) -> Unit {
        Unit::from(self) / rhs
    }
}

// Unit / BaseUnit → Unit
impl Div<BaseUnit> for Unit {
    type Output = Unit;

    fn div(self, rhs: BaseUnit) -> Unit {
        self / Unit::from(rhs)
    }
}

// &Unit * BaseUnit, &Unit / BaseUnit
impl Mul<BaseUnit> for &Unit {
    type Output = Unit;

    fn mul(self, rhs: BaseUnit) -> Unit {
        self * &Unit::from(rhs)
    }
}

impl Div<BaseUnit> for &Unit {
    type Output = Unit;

    fn div(self, rhs: BaseUnit) -> Unit {
        self / &Unit::from(rhs)
    }
}

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

    fn meter() -> Unit {
        Unit::Base(BaseUnit::new("meter", "m", &[], Dimension::LENGTH, 1.0))
    }

    fn second() -> Unit {
        Unit::Base(BaseUnit::new("second", "s", &[], Dimension::TIME, 1.0))
    }

    fn kilometer() -> Unit {
        Unit::Base(BaseUnit::new(
            "kilometer",
            "km",
            &[],
            Dimension::LENGTH,
            1000.0,
        ))
    }

    #[test]
    fn test_unit_division() {
        let velocity = meter() / second();
        let dim = velocity.dimension();
        assert_eq!(dim.length, Rational16::ONE);
        assert_eq!(dim.time, Rational16::new(-1, 1));
    }

    #[test]
    fn test_conversion_factor() {
        let m = meter();
        let km = kilometer();
        let factor = km.conversion_factor(&m).unwrap();
        assert!((factor - 1000.0).abs() < 1e-10);
    }

    #[test]
    fn test_incompatible_conversion() {
        let m = meter();
        let s = second();
        let result = m.conversion_factor(&s);
        assert!(matches!(result, Err(UnitError::DimensionMismatch { .. })));
    }

    #[test]
    fn test_unit_power() {
        let m = meter();
        let m2 = m.pow(2);
        let dim = m2.dimension();
        assert_eq!(dim.length, Rational16::new(2, 1));
    }

    #[test]
    fn test_unit_sqrt() {
        let m = meter();
        let m2 = &m * &m;
        let sqrt_m2 = m2.sqrt();
        let dim = sqrt_m2.dimension();
        assert_eq!(dim.length, Rational16::ONE);
    }

    #[test]
    fn test_offset_unit_conversion_factor_rejected() {
        let kelvin = Unit::Base(BaseUnit::new(
            "kelvin",
            "K",
            &[],
            Dimension::TEMPERATURE,
            1.0,
        ));
        let celsius = Unit::Base(BaseUnit::with_offset(
            "celsius",
            "°C",
            &[],
            Dimension::TEMPERATURE,
            1.0,
            273.15,
        ));
        let result = celsius.conversion_factor(&kelvin);
        assert!(matches!(result, Err(UnitError::OffsetConversion { .. })));
    }

    #[test]
    fn test_offset_unit_identity_conversion_ok() {
        let celsius = Unit::Base(BaseUnit::with_offset(
            "celsius",
            "°C",
            &[],
            Dimension::TEMPERATURE,
            1.0,
            273.15,
        ));
        let result = celsius.conversion_factor(&celsius);
        assert!(result.is_ok());
        assert!((result.unwrap() - 1.0).abs() < 1e-15);
    }

    #[test]
    fn test_pow_one_preserves_unit() {
        let celsius = Unit::Base(BaseUnit::with_offset(
            "celsius",
            "°C",
            &[],
            Dimension::TEMPERATURE,
            1.0,
            273.15,
        ));
        let powered = celsius.pow(1);
        assert!(powered.has_offset());
        assert_eq!(celsius, powered);
    }
}