1use rust_decimal::prelude::FromPrimitive;
2use rust_decimal::Decimal;
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::sync::{OnceLock, RwLock};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub enum Dimension {
9 Mass,
10 Length,
11 Volume,
12 Currency,
13 Time,
14 Temperature,
15 Count,
16 Custom(String),
17}
18
19impl Dimension {
20 pub fn parse(name: &str) -> Self {
22 match name.to_ascii_lowercase().as_str() {
23 "mass" => Dimension::Mass,
24 "length" => Dimension::Length,
25 "volume" => Dimension::Volume,
26 "currency" => Dimension::Currency,
27 "time" => Dimension::Time,
28 "temperature" => Dimension::Temperature,
29 "count" => Dimension::Count,
30 other => Dimension::Custom(other.to_string()),
31 }
32 }
33}
34
35impl std::str::FromStr for Dimension {
36 type Err = ();
37
38 fn from_str(s: &str) -> Result<Self, Self::Err> {
39 Ok(Dimension::parse(s))
40 }
41}
42
43impl std::fmt::Display for Dimension {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 Dimension::Mass => write!(f, "Mass"),
47 Dimension::Length => write!(f, "Length"),
48 Dimension::Volume => write!(f, "Volume"),
49 Dimension::Currency => write!(f, "Currency"),
50 Dimension::Time => write!(f, "Time"),
51 Dimension::Temperature => write!(f, "Temperature"),
52 Dimension::Count => write!(f, "Count"),
53 Dimension::Custom(s) => write!(f, "{}", s),
54 }
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59pub struct Unit {
60 symbol: String,
61 name: String,
62 dimension: Dimension,
63 base_factor: Decimal,
64 base_unit: String,
65}
66
67impl std::fmt::Display for Unit {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 write!(f, "{}", self.symbol)
70 }
71}
72
73impl Unit {
74 pub fn new(
75 symbol: impl Into<String>,
76 name: impl Into<String>,
77 dimension: Dimension,
78 base_factor: Decimal,
79 base_unit: impl Into<String>,
80 ) -> Self {
81 let symbol = symbol.into();
82 Self {
83 symbol,
84 name: name.into(),
85 dimension,
86 base_factor,
87 base_unit: base_unit.into(),
88 }
89 }
90
91 pub fn new_base(
92 symbol: impl Into<String>,
93 name: impl Into<String>,
94 dimension: Dimension,
95 ) -> Result<Self, UnitError> {
96 let symbol = symbol.into();
97 let base_unit = symbol.clone();
98 Ok(Self {
99 symbol,
100 name: name.into(),
101 dimension,
102 base_factor: Decimal::ONE,
103 base_unit,
104 })
105 }
106
107 pub fn with_base(mut self, base_unit: impl Into<String>) -> Self {
108 self.base_unit = base_unit.into();
109 self
110 }
111
112 pub fn symbol(&self) -> &str {
113 &self.symbol
114 }
115 pub fn name(&self) -> &str {
116 &self.name
117 }
118 pub fn dimension(&self) -> &Dimension {
119 &self.dimension
120 }
121 pub fn base_factor(&self) -> Decimal {
122 self.base_factor
123 }
124 pub fn base_unit(&self) -> &str {
125 &self.base_unit
126 }
127}
128
129pub trait UnitConversion {
130 fn convert_to_base(&self, value: Decimal) -> Decimal;
131 fn convert_from_base(&self, value: Decimal) -> Decimal;
132}
133
134impl UnitConversion for Unit {
135 fn convert_to_base(&self, value: Decimal) -> Decimal {
136 value * self.base_factor
137 }
138
139 fn convert_from_base(&self, value: Decimal) -> Decimal {
140 value / self.base_factor
141 }
142}
143
144#[derive(Debug, Clone, PartialEq)]
145#[non_exhaustive]
146pub enum UnitError {
147 UnitNotFound(String),
148 IncompatibleDimensions { from: Dimension, to: Dimension },
149 ConversionNotDefined { from: String, to: String },
150 ZeroBaseFactor,
151 DuplicateUnit(String),
152}
153
154impl std::fmt::Display for UnitError {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 match self {
157 UnitError::UnitNotFound(symbol) => write!(f, "Unit not found: {}", symbol),
158 UnitError::IncompatibleDimensions { from, to } => {
159 write!(f, "Cannot convert between {:?} and {:?}", from, to)
160 }
161 UnitError::ConversionNotDefined { from, to } => {
162 write!(f, "Conversion not defined from {} to {}", from, to)
163 }
164 UnitError::ZeroBaseFactor => {
165 write!(f, "Unit base_factor cannot be zero")
166 }
167 UnitError::DuplicateUnit(symbol) => {
168 write!(f, "Unit already registered: {}", symbol)
169 }
170 }
171 }
172}
173
174impl std::error::Error for UnitError {}
175
176#[derive(Debug, Clone)]
177pub struct UnitRegistry {
178 units: HashMap<String, Unit>,
179 base_units: HashMap<Dimension, String>,
180}
181
182impl Default for UnitRegistry {
183 fn default() -> Self {
184 let mut registry = Self {
185 units: HashMap::new(),
186 base_units: HashMap::new(),
187 };
188
189 registry.register_base(Dimension::Mass, "kg");
191 registry.register_builtin(Unit::new(
192 "kg",
193 "kilogram",
194 Dimension::Mass,
195 Decimal::from(1),
196 "kg",
197 ));
198 registry.register_builtin(Unit::new(
199 "g",
200 "gram",
201 Dimension::Mass,
202 Decimal::new(1, 3),
203 "kg",
204 ));
205 registry.register_builtin(Unit::new(
206 "lb",
207 "pound",
208 Dimension::Mass,
209 Decimal::new(45359237, 8),
210 "kg",
211 ));
212
213 registry.register_base(Dimension::Length, "m");
215 registry.register_builtin(Unit::new(
216 "m",
217 "meter",
218 Dimension::Length,
219 Decimal::from(1),
220 "m",
221 ));
222 registry.register_builtin(Unit::new(
223 "cm",
224 "centimeter",
225 Dimension::Length,
226 Decimal::new(1, 2),
227 "m",
228 ));
229 registry.register_builtin(Unit::new(
230 "in",
231 "inch",
232 Dimension::Length,
233 Decimal::new(254, 4),
234 "m",
235 ));
236
237 registry.register_base(Dimension::Volume, "L");
239 registry.register_builtin(Unit::new(
240 "L",
241 "liter",
242 Dimension::Volume,
243 Decimal::from(1),
244 "L",
245 ));
246 registry.register_builtin(Unit::new(
247 "mL",
248 "milliliter",
249 Dimension::Volume,
250 Decimal::new(1, 3),
251 "L",
252 ));
253
254 registry.register_base(Dimension::Currency, "USD");
265 registry.register_builtin(Unit::new(
266 "USD",
267 "US Dollar",
268 Dimension::Currency,
269 Decimal::from(1),
270 "USD",
271 ));
272 registry.register_builtin(Unit::new(
273 "EUR",
274 "Euro",
275 Dimension::Currency,
276 Decimal::from(1),
277 "EUR",
278 ));
279 registry.register_builtin(Unit::new(
280 "GBP",
281 "British Pound",
282 Dimension::Currency,
283 Decimal::from(1),
284 "GBP",
285 ));
286
287 registry.register_base(Dimension::Time, "s");
289 registry.register_builtin(Unit::new(
290 "s",
291 "second",
292 Dimension::Time,
293 Decimal::from(1),
294 "s",
295 ));
296 registry.register_builtin(Unit::new(
297 "min",
298 "minute",
299 Dimension::Time,
300 Decimal::from(60),
301 "s",
302 ));
303 registry.register_builtin(Unit::new(
304 "h",
305 "hour",
306 Dimension::Time,
307 Decimal::from(3600),
308 "s",
309 ));
310 registry.register_builtin(Unit::new(
311 "ms",
312 "millisecond",
313 Dimension::Time,
314 Decimal::new(1, 3),
315 "s",
316 ));
317 registry.register_builtin(Unit::new(
318 "us",
319 "microsecond",
320 Dimension::Time,
321 Decimal::new(1, 6),
322 "s",
323 ));
324 registry.register_builtin(Unit::new(
325 "ns",
326 "nanosecond",
327 Dimension::Time,
328 Decimal::new(1, 9),
329 "s",
330 ));
331
332 registry.register_base(Dimension::Count, "units");
334 registry.register_builtin(Unit::new(
335 "units",
336 "units",
337 Dimension::Count,
338 Decimal::from(1),
339 "units",
340 ));
341 registry.register_builtin(Unit::new(
342 "items",
343 "items",
344 Dimension::Count,
345 Decimal::from(1),
346 "items",
347 ));
348 registry.register_builtin(Unit::new(
351 "percent",
352 "percent",
353 Dimension::Count,
354 Decimal::from(1),
355 "units",
356 ));
357
358 registry
359 }
360}
361
362impl UnitRegistry {
363 pub fn new() -> Self {
364 Self {
365 units: HashMap::new(),
366 base_units: HashMap::new(),
367 }
368 }
369
370 pub fn register(&mut self, unit: Unit) -> Result<(), UnitError> {
388 if self.units.contains_key(&unit.symbol) {
389 return Err(UnitError::DuplicateUnit(unit.symbol.clone()));
390 }
391 if unit.base_factor == Decimal::ZERO {
392 return Err(UnitError::ZeroBaseFactor);
393 }
394 if matches!(unit.dimension, Dimension::Temperature) {
395 return Err(UnitError::ConversionNotDefined {
396 from: unit.symbol.clone(),
397 to: "Temperature (needs affine/offset conversion, unsupported by this linear unit model)"
398 .to_string(),
399 });
400 }
401 if unit.base_unit != unit.symbol {
402 if let Some(base) = self.units.get(&unit.base_unit) {
403 if base.dimension != unit.dimension {
404 return Err(UnitError::IncompatibleDimensions {
405 from: unit.dimension.clone(),
406 to: base.dimension.clone(),
407 });
408 }
409 }
410 }
411 self.units.insert(unit.symbol.clone(), unit);
412 Ok(())
413 }
414
415 fn register_builtin(&mut self, unit: Unit) {
416 self.register(unit)
417 .expect("builtin unit registration must be valid");
418 }
419
420 pub fn register_dimension(&mut self, _dimension: Dimension) {}
428
429 pub fn register_base(&mut self, dimension: Dimension, base_unit: impl Into<String>) {
430 self.base_units.insert(dimension, base_unit.into());
431 }
432
433 pub fn get_unit(&self, symbol: &str) -> Result<&Unit, UnitError> {
434 self.units
435 .get(symbol)
436 .ok_or_else(|| UnitError::UnitNotFound(symbol.to_string()))
437 }
438
439 pub fn units(&self) -> &HashMap<String, Unit> {
440 &self.units
441 }
442
443 pub fn base_units(&self) -> &HashMap<Dimension, String> {
444 &self.base_units
445 }
446
447 pub fn convert(&self, value: Decimal, from: &Unit, to: &Unit) -> Result<Decimal, UnitError> {
448 if from.dimension != to.dimension {
449 return Err(UnitError::IncompatibleDimensions {
450 from: from.dimension.clone(),
451 to: to.dimension.clone(),
452 });
453 }
454
455 if matches!(from.dimension, Dimension::Currency) && from.symbol != to.symbol {
456 return Err(UnitError::ConversionNotDefined {
457 from: from.symbol.clone(),
458 to: to.symbol.clone(),
459 });
460 }
461
462 debug_assert_eq!(
469 from.base_unit, to.base_unit,
470 "same-dimension units '{}' and '{}' disagree on base_unit ('{}' vs '{}')",
471 from.symbol, to.symbol, from.base_unit, to.base_unit
472 );
473
474 let in_base = from.convert_to_base(value);
475 let in_target = to.convert_from_base(in_base);
476
477 Ok(in_target)
478 }
479
480 pub fn global() -> &'static RwLock<UnitRegistry> {
489 static GLOBAL_REGISTRY: OnceLock<RwLock<UnitRegistry>> = OnceLock::new();
490 GLOBAL_REGISTRY.get_or_init(|| RwLock::new(UnitRegistry::default()))
491 }
492
493 pub fn register_from_json(&mut self, json: &str) -> Result<(), UnitError> {
496 #[derive(Deserialize)]
497 struct UnitConfig {
498 symbol: String,
499 name: String,
500 dimension: String,
501 base_factor: f64,
502 base_unit: String,
503 }
504
505 let parsed: Vec<UnitConfig> =
506 serde_json::from_str(json).map_err(|e| UnitError::ConversionNotDefined {
507 from: "json".to_string(),
508 to: e.to_string(),
509 })?;
510 for cfg in parsed {
511 let dim = Dimension::parse(&cfg.dimension);
512 let factor = Decimal::from_f64(cfg.base_factor).ok_or(UnitError::ZeroBaseFactor)?;
513 if factor == Decimal::ZERO {
514 return Err(UnitError::ZeroBaseFactor);
515 }
516 let unit = Unit::new(cfg.symbol, cfg.name, dim, factor, cfg.base_unit);
517 self.register(unit)?;
518 }
519 Ok(())
520 }
521}
522
523pub fn get_default_registry() -> &'static RwLock<UnitRegistry> {
524 UnitRegistry::global()
525}
526
527pub fn try_unit_from_string(symbol: &str) -> Result<Unit, UnitError> {
532 let registry = get_default_registry();
533 let registry = registry.read().unwrap_or_else(|e| e.into_inner());
534 registry.get_unit(symbol).cloned()
535}
536
537pub fn unit_from_string(symbol: impl Into<String>) -> Unit {
552 let symbol = symbol.into();
553 try_unit_from_string(&symbol).unwrap_or_else(|_| {
554 Unit::new(
555 symbol.clone(),
556 symbol.clone(),
557 Dimension::Custom(symbol.clone()),
558 Decimal::from(1),
559 symbol.clone(),
560 )
561 })
562}