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
#![allow(incomplete_features)]
#![cfg_attr(feature = "const", feature(generic_const_exprs))]
#![cfg_attr(feature = "const", feature(adt_const_params))]
#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
/*!
A library that lets you validate the dimensions of your quantities at compile time and at runtime.
<div class="warning">WARNING: Uses the experimental features `generic_const_exprs` and `adt_const_params` which are known to cause bugs. Disable the `const` feature if you're only interested in runtime checking.</div>
## Compile time example
Okay
```rust
use const_units::si; // Parses units at compile time
use const_units::Quantity; // Represents a number with a dimension
// Input attometers, return square attometers
fn square_dist(
x: Quantity<f64, { si("am") }>,
y: Quantity<f64, { si("am") }>,
) -> Quantity<f64, { si("am^2") }> {
x.powi::<2>() + y.powi::<2>()
}
// Input attometers, return meters
fn distance(
x: Quantity<f64, { si("am") }>,
y: Quantity<f64, { si("am") }>,
) -> Quantity<f64, { si("m") }> {
square_dist(x, y)
.powf::<{ (1, 2) }>() // `(1, 2)` represents 1/2
.convert_to::<{ si("m") }>()
}
assert_eq!(
distance(Quantity(3.), Quantity(4.)),
Quantity(0.000_000_000_000_000_005)
);
```
Broken
```compile_fail
# use const_units::{Quantity, units::{meter, second, DIMENSIONLESS}};
fn sum(
x: Quantity<f64, { meter }>,
y: Quantity<f64, { second }>,
) -> Quantity<f64, DIMENSIONLESS> {
x + y // You can't add meters and seconds
}
```
## Run time example
Requires the `dyn` feature
```rust
use const_units::si;
use const_units::DynQuantity; // A quantity with dynamic units stored at runtime alongside the number
use const_units::InconsistentUnits; // The error returned when inconsistent units are used together
fn distance(
x: DynQuantity<f64>,
y: DynQuantity<f64>,
) -> DynQuantity<f64> {
// The addition operator will panic if the units are inconsistent
(x.powi(2) + y.powi(2))
.powf((1, 2))
.convert_to(si("m"))
.unwrap()
}
fn distance_checked(
x: DynQuantity<f64>,
y: DynQuantity<f64>,
) -> Result<DynQuantity<f64>, InconsistentUnits> {
// You can use checked operators to avoid panicking
x.powi(2)
.checked_add(y.powi(2))?
.powf((1, 2))
.convert_to(si("m"))
}
assert_eq!(
distance_checked(DynQuantity(3., si("am")), DynQuantity(4., si("am"))),
Ok(DynQuantity(0.000_000_000_000_000_005, si("m"))),
);
assert_eq!(
distance_checked(DynQuantity(3., si("m")), DynQuantity(4., si("m"))),
Ok(DynQuantity(5., si("m"))),
);
assert!(distance_checked(DynQuantity(3., si("m")), DynQuantity(4., si("s"))).is_err());
```
## no-std
The `std` feature can be disabled to allow the crate to function in no-std environments. Doing so will remove methods to convert quantities directly to strings and prevent errors from implementing `std::error::Error`.
*/
use core::fmt::Display;
use units::DIMENSIONLESS;
mod parsing;
pub mod prefixes;
pub mod units;
pub use parsing::*;
#[cfg(feature = "const")]
mod quantity;
#[cfg(feature = "const")]
pub use quantity::*;
#[cfg(feature = "dyn")]
mod dyn_quantity;
#[cfg(feature = "dyn")]
pub use dyn_quantity::*;
// https://stackoverflow.com/questions/7407752/integer-nth-root
const fn try_root(v: u128, n: u32) -> Option<u128> {
// (2..128).map(|v| (u128::MAX as f64).powf(1. / v as f64).ceil() as u128).collect::<Vec<_>>()
#[rustfmt::skip]
const MAX_VALS: [u128; 126] = [18446744073709551616, 6981463658332, 4294967296, 50859009, 2642246, 319558, 65536, 19113, 7132, 3184, 1626, 921, 566, 371, 256, 185, 139, 107, 85, 69, 57, 48, 41, 35, 31, 27, 24, 22, 20, 18, 16, 15, 14, 13, 12, 12, 11, 10, 10, 9, 9, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3];
if n == 1 {
return Some(v);
}
if n == 0 {
return Some(1);
}
if v == 0 || v == 1 {
return Some(v);
}
if n > (MAX_VALS.len() + 1) as u32 {
return None;
}
// Can't shadow constant `min`
let mut minimum = 2;
let mut max = MAX_VALS[n as usize - 2];
loop {
let mid = (minimum + max) >> 1;
let res = mid.pow(n);
if res > v {
max = mid;
} else if res < v {
minimum = mid + 1;
} else {
return Some(mid);
}
if minimum == max {
return None;
}
}
}
const fn add(lhs: (i32, u32), rhs: (i32, u32)) -> (i32, u32) {
simplify((
lhs.0 * (rhs.1 as i32) + rhs.0 * (lhs.1 as i32),
lhs.1 * rhs.1,
))
}
const fn sub(lhs: (i32, u32), mut rhs: (i32, u32)) -> (i32, u32) {
rhs.0 = -rhs.0;
add(lhs, rhs)
}
const fn recip(f: (i128, u128)) -> (i128, u128) {
simplify_big((f.1 as i128 * f.0.signum(), f.0.unsigned_abs()))
}
const fn mul(lhs: (i128, u128), rhs: (i128, u128)) -> (i128, u128) {
simplify_big((lhs.0 * rhs.0, lhs.1 * rhs.1))
}
const fn div(lhs: (i128, u128), rhs: (i128, u128)) -> (i128, u128) {
mul(lhs, recip(rhs))
}
const fn gcd(a: u32, b: u32) -> u32 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
const fn gcd_big(a: u128, b: u128) -> u128 {
if b == 0 {
a
} else {
gcd_big(b, a % b)
}
}
/// Simplify a fraction that uses 32 bit numbers
pub const fn simplify(v: (i32, u32)) -> (i32, u32) {
let scale_down = gcd(v.0.unsigned_abs(), v.1);
(v.0 / (scale_down as i32), v.1 / scale_down)
}
/// Simplify a fraction that uses 128 bit numbers
pub const fn simplify_big(v: (i128, u128)) -> (i128, u128) {
let scale_down = gcd_big(v.0.unsigned_abs(), v.1);
(v.0 / (scale_down as i128), v.1 / scale_down)
}
/// Represents SI units
///
/// Each field contains the exponent of the corresponding dimension. Exponents are fractions where the first element of the tuple is the numerator and the second is the denominator. Ensure the fractions are fully simplified if you're creating an instance directly.
#[allow(non_snake_case)]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub struct SI {
/// A scale factor - used for units that are constant multiples of other units; ie. minutes or kilometers
pub scale: (i128, u128),
/// Seconds
pub s: (i32, u32),
/// Meters
pub m: (i32, u32),
/// Kilograms
pub kg: (i32, u32),
/// Amperes
pub A: (i32, u32),
/// Kelvin
pub K: (i32, u32),
/// Moles
pub mol: (i32, u32),
/// Candelas
pub cd: (i32, u32),
}
impl Display for SI {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut not_first = false;
if self.scale.0 != 1
|| self.scale.1 != 1
|| (*self).scale_by(recip(self.scale)) == DIMENSIONLESS
{
f.write_str("(")?;
self.scale.0.fmt(f)?;
if self.scale.1 != 1 {
f.write_str("/")?;
self.scale.1.fmt(f)?;
}
f.write_str(")")?;
not_first = true;
}
macro_rules! unit {
($name: tt, $signum: expr) => {
#[allow(unused_assignments)]
// Implicitly checks for zero too
if self.$name.0.signum() == $signum {
if not_first {
f.write_str("⋅")?;
}
f.write_str(stringify!($name))?;
if self.$name.0 != 1 || self.$name.1 != 1 {
f.write_str("^")?;
self.$name.0.fmt(f)?;
if self.$name.1 != 1 {
f.write_str("/")?;
self.$name.1.fmt(f)?;
}
}
not_first = true;
}
};
}
// Ensure negative powers come after positive ones
unit!(s, 1);
unit!(m, 1);
unit!(kg, 1);
unit!(A, 1);
unit!(K, 1);
unit!(mol, 1);
unit!(cd, 1);
unit!(s, -1);
unit!(m, -1);
unit!(kg, -1);
unit!(A, -1);
unit!(K, -1);
unit!(mol, -1);
unit!(cd, -1);
Ok(())
}
}
impl SI {
/// Multiply the scale factor by a given constant
///
/// ```
/// # use const_units::units::{second, minute};
/// assert_eq!(second.scale_by((60, 1)), minute)
/// ```
pub const fn scale_by(mut self, scale: (i128, u128)) -> Self {
self.scale = mul(scale, self.scale);
self
}
/// Multiply SI units
///
/// ```
/// # use const_units::units::{newton, meter, joule};
/// assert_eq!(newton.mul(meter), joule)
/// ```
pub const fn mul(self, rhs: Self) -> Self {
SI {
scale: mul(self.scale, rhs.scale),
s: add(self.s, rhs.s),
m: add(self.m, rhs.m),
kg: add(self.kg, rhs.kg),
A: add(self.A, rhs.A),
K: add(self.K, rhs.K),
mol: add(self.mol, rhs.mol),
cd: add(self.cd, rhs.cd),
}
}
/// Divide SI units
///
/// ```
/// # use const_units::units::{joule, second, watt};
/// assert_eq!(joule.div(second), watt);
/// ```
pub const fn div(self, rhs: Self) -> Self {
SI {
scale: div(self.scale, rhs.scale),
s: sub(self.s, rhs.s),
m: sub(self.m, rhs.m),
kg: sub(self.kg, rhs.kg),
A: sub(self.A, rhs.A),
K: sub(self.K, rhs.K),
mol: sub(self.mol, rhs.mol),
cd: sub(self.cd, rhs.cd),
}
}
/// Raise SI units to an integer power
///
/// ```
/// # use const_units::units::{second, hertz};
/// assert_eq!(second.powi(-1), hertz);
/// ```
pub const fn powi(self, v: i32) -> Self {
self.powf((v, 1))
}
/// Raise SI units to a fractional power
///
/// ```
/// # use const_units::units::{meter};
/// assert_eq!(meter.powi(2).powf((1, 2)), meter);
/// ```
///
/// # Panics
/// Panics if `scale` can't be raised to the given power without losing precision
///
/// ```should_panic
/// # use const_units::units::{meter};
/// meter.scale_by((2, 1)).powf((1, 2)); // `2` isn't a square number
/// ```
pub const fn powf(self, v: (i32, u32)) -> Self {
match self.checked_powf(v) {
Some(v) => v,
None => panic!("Scale can't be raised to the given power without losing precision"),
}
}
/// A checked version of `pow`
///
/// ```
/// # use const_units::units::{meter};
/// assert_eq!(meter.powi(2).checked_powf((1, 2)), Some(meter));
/// assert_eq!(meter.scale_by((2, 1)).checked_powf((1, 2)), None);
/// ```
pub const fn checked_powf(self, mut v: (i32, u32)) -> Option<Self> {
v = simplify(v);
let mut scale = self.scale;
// `Try` isn't allowed in const
scale.0 = match try_root(scale.0.unsigned_abs(), v.1) {
Some(v) => v as i128 * scale.0.signum(),
None => return None,
};
scale.1 = match try_root(scale.1, v.1) {
Some(v) => v,
None => return None,
};
if v.0.signum() == -1 {
scale = recip(scale);
}
scale.0 = scale.0.pow(v.0.unsigned_abs());
scale.1 = scale.1.pow(v.0.unsigned_abs());
Some(SI {
scale,
s: simplify((self.s.0 * v.0, self.s.1 * v.1)),
m: simplify((self.m.0 * v.0, self.m.1 * v.1)),
kg: simplify((self.kg.0 * v.0, self.kg.1 * v.1)),
A: simplify((self.A.0 * v.0, self.A.1 * v.1)),
K: simplify((self.K.0 * v.0, self.K.1 * v.1)),
mol: simplify((self.mol.0 * v.0, self.mol.1 * v.1)),
cd: simplify((self.cd.0 * v.0, self.cd.1 * v.1)),
})
}
/// Compare units in constant functions
pub const fn const_eq(self, other: SI) -> bool {
self.scale.0 == other.scale.0 && self.scale.1 == other.scale.1 && self.same_dimension(other)
}
/// Determine whether two units measure the same dimension
///
/// ```
/// use const_units::si;
/// assert!(si("min").same_dimension(si("s")));
/// assert!(!si("cd").same_dimension(si("s")));
/// ```
pub const fn same_dimension(self, other: SI) -> bool {
self.s.0 == other.s.0
&& self.s.1 == other.s.1
&& self.m.0 == other.m.0
&& self.m.1 == other.m.1
&& self.kg.0 == other.kg.0
&& self.kg.1 == other.kg.1
&& self.A.0 == other.A.0
&& self.A.1 == other.A.1
&& self.K.0 == other.K.0
&& self.K.1 == other.K.1
&& self.mol.0 == other.mol.0
&& self.mol.1 == other.mol.1
&& self.cd.0 == other.cd.0
&& self.cd.1 == other.cd.1
}
}
#[cfg(test)]
mod tests {
use crate::{add, gcd, mul, recip, simplify, sub, try_root};
#[test]
fn fractional_add() {
assert_eq!(add((1, 2), (1, 3)), (5, 6));
assert_eq!(add((1, 2), (-1, 3)), (1, 6));
assert_eq!(add((-1, 2), (-1, 3)), (-5, 6));
assert_eq!(add((-2, 2), (-1, 3)), (-4, 3));
assert_eq!(add((2, 2), (3, 3)), (2, 1));
}
#[test]
fn fractional_sub() {
assert_eq!(sub((1, 2), (1, 3)), (1, 6));
assert_eq!(sub((1, 2), (-1, 3)), (5, 6));
assert_eq!(sub((-1, 2), (-1, 3)), (-1, 6));
assert_eq!(sub((-2, 2), (-1, 3)), (-2, 3));
assert_eq!(sub((2, 2), (3, 3)), (0, 1));
}
#[test]
fn fractional_mul() {
assert_eq!(mul((1, 2), (1, 3)), (1, 6));
assert_eq!(mul((1, 2), (-1, 3)), (-1, 6));
assert_eq!(mul((-1, 2), (-1, 3)), (1, 6));
assert_eq!(mul((-2, 2), (-1, 3)), (1, 3));
assert_eq!(mul((2, 2), (3, 3)), (1, 1));
assert_eq!(mul((60, 1), (1, 60)), (1, 1));
}
#[test]
fn test_gcd() {
assert_eq!(gcd(2, 2), 2);
assert_eq!(gcd(2, 3), 1);
assert_eq!(gcd(2, 4), 2);
assert_eq!(gcd(4, 3), 1);
assert_eq!(gcd(4, 2), 2);
}
#[test]
fn test_recip() {
assert_eq!(recip((1, 2)), (2, 1));
assert_eq!(recip((2, 2)), (1, 1));
assert_eq!(recip((-1, 2)), (-2, 1));
assert_eq!(recip((-2, 1)), (-1, 2));
}
#[test]
fn test_simplify() {
assert_eq!(simplify((5, 6)), (5, 6));
assert_eq!(simplify((-5, 6)), (-5, 6));
assert_eq!(simplify((-4, 6)), (-2, 3));
assert_eq!(simplify((-2, 1)), (-2, 1));
assert_eq!(simplify((4, 6)), (2, 3));
}
#[test]
fn test_root() {
assert_eq!(try_root(9, 2), Some(3));
assert_eq!(try_root(27, 3), Some(3));
assert_eq!(try_root(28, 3), None);
assert_eq!(try_root(28, 39), None);
assert_eq!(try_root(1, 39), Some(1));
assert_eq!(try_root(28, 0), Some(1));
assert_eq!(try_root(0, 1), Some(0));
}
}