1use std::fmt;
18
19#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
24#[repr(usize)]
25pub enum BaseDim {
26 Length = 0,
27 Mass,
28 Time,
29 Current,
30 Temperature,
31 Amount,
32 Luminous,
33 Angle,
34 SolidAngle,
35 Information,
36}
37
38impl BaseDim {
39 pub const COUNT: usize = 10;
41
42 pub const ALL: [BaseDim; BaseDim::COUNT] = [
44 BaseDim::Length,
45 BaseDim::Mass,
46 BaseDim::Time,
47 BaseDim::Current,
48 BaseDim::Temperature,
49 BaseDim::Amount,
50 BaseDim::Luminous,
51 BaseDim::Angle,
52 BaseDim::SolidAngle,
53 BaseDim::Information,
54 ];
55
56 #[inline]
58 pub const fn index(self) -> usize {
59 self as usize
60 }
61
62 pub const fn symbol(self) -> &'static str {
64 match self {
65 BaseDim::Length => "L",
66 BaseDim::Mass => "M",
67 BaseDim::Time => "T",
68 BaseDim::Current => "I",
69 BaseDim::Temperature => "Θ",
70 BaseDim::Amount => "N",
71 BaseDim::Luminous => "J",
72 BaseDim::Angle => "rad",
73 BaseDim::SolidAngle => "sr",
74 BaseDim::Information => "bit",
75 }
76 }
77}
78
79const fn igcd(mut a: i32, mut b: i32) -> i32 {
81 a = a.abs();
82 b = b.abs();
83 while b != 0 {
84 let t = b;
85 b = a % b;
86 a = t;
87 }
88 a
89}
90
91#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
95pub struct Exp {
96 num: i32,
97 den: i32,
98}
99
100impl Exp {
101 pub const ZERO: Exp = Exp { num: 0, den: 1 };
103 pub const ONE: Exp = Exp { num: 1, den: 1 };
105
106 pub fn new(num: i32, den: i32) -> Exp {
108 assert!(den != 0, "exponent denominator must be nonzero");
109 let (mut num, mut den) = (num, den);
110 if den < 0 {
111 num = -num;
112 den = -den;
113 }
114 if num == 0 {
115 return Exp::ZERO;
116 }
117 let g = igcd(num, den);
118 Exp {
119 num: num / g,
120 den: den / g,
121 }
122 }
123
124 #[inline]
126 pub const fn int(n: i32) -> Exp {
127 Exp { num: n, den: 1 }
128 }
129
130 pub const fn numerator(self) -> i32 {
131 self.num
132 }
133
134 pub const fn denominator(self) -> i32 {
135 self.den
136 }
137
138 #[inline]
139 pub const fn is_zero(self) -> bool {
140 self.num == 0
141 }
142
143 pub fn add(self, other: Exp) -> Exp {
145 Exp::new(
146 self.num * other.den + other.num * self.den,
147 self.den * other.den,
148 )
149 }
150
151 pub fn sub(self, other: Exp) -> Exp {
153 Exp::new(
154 self.num * other.den - other.num * self.den,
155 self.den * other.den,
156 )
157 }
158
159 pub fn neg(self) -> Exp {
161 Exp {
162 num: -self.num,
163 den: self.den,
164 }
165 }
166
167 pub fn scale(self, k: i32) -> Exp {
169 Exp::new(self.num * k, self.den)
170 }
171
172 pub fn div_int(self, k: i32) -> Exp {
174 Exp::new(self.num, self.den * k)
175 }
176}
177
178impl fmt::Display for Exp {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 if self.den == 1 {
181 write!(f, "{}", self.num)
182 } else {
183 write!(f, "{}/{}", self.num, self.den)
184 }
185 }
186}
187
188#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
192pub struct Dimension {
193 e: [Exp; BaseDim::COUNT],
194}
195
196impl Dimension {
197 pub const DIMENSIONLESS: Dimension = Dimension {
199 e: [Exp::ZERO; BaseDim::COUNT],
200 };
201
202 pub fn base(d: BaseDim) -> Dimension {
204 let mut e = [Exp::ZERO; BaseDim::COUNT];
205 e[d.index()] = Exp::ONE;
206 Dimension { e }
207 }
208
209 pub fn from_exps(e: [Exp; BaseDim::COUNT]) -> Dimension {
213 Dimension { e }
214 }
215
216 #[inline]
218 pub fn exponent(self, d: BaseDim) -> Exp {
219 self.e[d.index()]
220 }
221
222 pub fn is_dimensionless(self) -> bool {
224 self.e.iter().all(|x| x.is_zero())
225 }
226
227 pub fn mul(self, other: Dimension) -> Dimension {
229 let mut e = self.e;
230 for (i, slot) in e.iter_mut().enumerate() {
231 *slot = slot.add(other.e[i]);
232 }
233 Dimension { e }
234 }
235
236 pub fn div(self, other: Dimension) -> Dimension {
238 let mut e = self.e;
239 for (i, slot) in e.iter_mut().enumerate() {
240 *slot = slot.sub(other.e[i]);
241 }
242 Dimension { e }
243 }
244
245 pub fn recip(self) -> Dimension {
247 let mut e = self.e;
248 for slot in e.iter_mut() {
249 *slot = slot.neg();
250 }
251 Dimension { e }
252 }
253
254 pub fn powi(self, k: i32) -> Dimension {
256 let mut e = self.e;
257 for slot in e.iter_mut() {
258 *slot = slot.scale(k);
259 }
260 Dimension { e }
261 }
262
263 pub fn nth_root(self, k: i32) -> Dimension {
265 let mut e = self.e;
266 for slot in e.iter_mut() {
267 *slot = slot.div_int(k);
268 }
269 Dimension { e }
270 }
271
272 pub fn length() -> Dimension {
274 Dimension::base(BaseDim::Length)
275 }
276 pub fn mass() -> Dimension {
277 Dimension::base(BaseDim::Mass)
278 }
279 pub fn time() -> Dimension {
280 Dimension::base(BaseDim::Time)
281 }
282 pub fn current() -> Dimension {
283 Dimension::base(BaseDim::Current)
284 }
285 pub fn temperature() -> Dimension {
286 Dimension::base(BaseDim::Temperature)
287 }
288 pub fn amount() -> Dimension {
289 Dimension::base(BaseDim::Amount)
290 }
291 pub fn luminous() -> Dimension {
292 Dimension::base(BaseDim::Luminous)
293 }
294 pub fn angle() -> Dimension {
295 Dimension::base(BaseDim::Angle)
296 }
297 pub fn solid_angle() -> Dimension {
298 Dimension::base(BaseDim::SolidAngle)
299 }
300 pub fn information() -> Dimension {
301 Dimension::base(BaseDim::Information)
302 }
303
304 pub fn area() -> Dimension {
306 Self::length().powi(2)
307 }
308 pub fn volume() -> Dimension {
309 Self::length().powi(3)
310 }
311 pub fn speed() -> Dimension {
312 Self::length().div(Self::time())
313 }
314 pub fn acceleration() -> Dimension {
315 Self::speed().div(Self::time())
316 }
317 pub fn frequency() -> Dimension {
318 Self::time().recip()
319 }
320 pub fn force() -> Dimension {
321 Self::mass().mul(Self::acceleration())
322 }
323 pub fn energy() -> Dimension {
324 Self::force().mul(Self::length())
325 }
326 pub fn power() -> Dimension {
327 Self::energy().div(Self::time())
328 }
329 pub fn pressure() -> Dimension {
330 Self::force().div(Self::area())
331 }
332 pub fn charge() -> Dimension {
333 Self::current().mul(Self::time())
334 }
335 pub fn voltage() -> Dimension {
336 Self::power().div(Self::current())
337 }
338 pub fn resistance() -> Dimension {
339 Self::voltage().div(Self::current())
340 }
341 pub fn conductance() -> Dimension {
342 Self::resistance().recip()
343 } pub fn capacitance() -> Dimension {
345 Self::charge().div(Self::voltage())
346 } pub fn magnetic_flux() -> Dimension {
348 Self::voltage().mul(Self::time())
349 } pub fn inductance() -> Dimension {
351 Self::magnetic_flux().div(Self::current())
352 } pub fn magnetic_flux_density() -> Dimension {
354 Self::magnetic_flux().div(Self::area())
355 } pub fn surface_tension() -> Dimension {
357 Self::force().div(Self::length())
358 } pub fn density() -> Dimension {
360 Self::mass().div(Self::volume())
361 }
362 pub fn absorbed_dose() -> Dimension {
364 Self::energy().div(Self::mass())
365 } pub fn radioactivity() -> Dimension {
367 Self::frequency()
368 } pub fn exposure() -> Dimension {
370 Self::charge().div(Self::mass())
371 } pub fn catalytic_activity() -> Dimension {
373 Self::amount().div(Self::time())
374 } pub fn luminous_flux() -> Dimension {
377 Self::luminous().mul(Self::solid_angle())
378 } pub fn illuminance() -> Dimension {
380 Self::luminous_flux().div(Self::area())
381 } pub fn luminance() -> Dimension {
383 Self::luminous().div(Self::area())
384 } pub fn data_rate() -> Dimension {
387 Self::information().div(Self::time())
388 } pub fn volumetric_flow() -> Dimension {
390 Self::volume().div(Self::time())
391 } pub fn molar_concentration() -> Dimension {
393 Self::amount().div(Self::volume())
394 } pub fn molality() -> Dimension {
396 Self::amount().div(Self::mass())
397 } pub fn dynamic_viscosity() -> Dimension {
399 Self::pressure().mul(Self::time())
400 } pub fn kinematic_viscosity() -> Dimension {
402 Self::area().div(Self::time())
403 } pub fn fuel_economy() -> Dimension {
405 Self::length().div(Self::volume())
406 } pub fn by_name(name: &str) -> Option<Dimension> {
412 let n = name.trim().to_ascii_lowercase();
413 Some(match n.as_str() {
414 "dimensionless" | "scalar" | "number" => Dimension::DIMENSIONLESS,
415 "length" | "distance" => Self::length(),
417 "mass" => Self::mass(),
418 "time" | "duration" => Self::time(),
419 "current" | "electriccurrent" | "electric current" => Self::current(),
420 "temperature" => Self::temperature(),
421 "amount" | "amountofsubstance" => Self::amount(),
422 "luminous" | "luminousintensity" => Self::luminous(),
423 "angle" | "planeangle" => Self::angle(),
424 "solidangle" | "solid angle" => Self::solid_angle(),
425 "information" | "data" => Self::information(),
426 "area" => Self::area(),
428 "volume" => Self::volume(),
429 "speed" | "velocity" => Self::speed(),
430 "acceleration" => Self::acceleration(),
431 "frequency" => Self::frequency(),
432 "force" | "weight" => Self::force(),
433 "energy" | "work" | "heat" => Self::energy(),
434 "power" => Self::power(),
435 "pressure" | "stress" => Self::pressure(),
436 "charge" | "electriccharge" => Self::charge(),
437 "voltage" | "potential" | "emf" => Self::voltage(),
438 "resistance" => Self::resistance(),
439 "conductance" => Self::conductance(),
440 "capacitance" => Self::capacitance(),
441 "inductance" => Self::inductance(),
442 "magneticflux" | "magnetic flux" => Self::magnetic_flux(),
443 "magneticfluxdensity" | "fluxdensity" => Self::magnetic_flux_density(),
444 "density" => Self::density(),
445 "surfacetension" | "surface tension" => Self::surface_tension(),
446 "datarate" | "data rate" | "bandwidth" => Self::data_rate(),
447 "flow" | "volumetricflow" | "volumetric flow" => Self::volumetric_flow(),
448 "concentration" | "molarconcentration" | "molarity" => Self::molar_concentration(),
449 "molality" => Self::molality(),
450 "absorbeddose" | "dose" => Self::absorbed_dose(),
451 "radioactivity" | "activity" => Self::radioactivity(),
452 "exposure" => Self::exposure(),
453 "catalyticactivity" | "catalysis" => Self::catalytic_activity(),
454 "luminousflux" => Self::luminous_flux(),
455 "illuminance" => Self::illuminance(),
456 "luminance" => Self::luminance(),
457 "fueleconomy" | "fuel economy" => Self::fuel_economy(),
458 _ => return None,
459 })
460 }
461}
462
463impl fmt::Display for Dimension {
464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465 if self.is_dimensionless() {
466 return write!(f, "1");
467 }
468 let mut first = true;
469 for d in BaseDim::ALL {
470 let x = self.exponent(d);
471 if x.is_zero() {
472 continue;
473 }
474 if !first {
475 write!(f, "·")?;
476 }
477 first = false;
478 if x == Exp::ONE {
479 write!(f, "{}", d.symbol())?;
480 } else {
481 write!(f, "{}^{}", d.symbol(), x)?;
482 }
483 }
484 Ok(())
485 }
486}
487
488#[cfg(test)]
489#[path = "../../logicaffeine_tests/unit/logicaffeine_base/dimension/tests.rs"]
490mod tests;