Skip to main content

Crate qtty

Crate qtty 

Source
Expand description

Strongly typed physical quantities and conversions.

qtty is the user-facing crate in this workspace. It re-exports the full API from qtty-core plus a curated set of predefined units (time, angles, lengths, …).

The core idea is: a value is always a Quantity<U, S>, where U is a zero-sized type describing the unit and S is the scalar type (defaults to f64). This keeps units at compile time with no runtime overhead beyond the scalar’s size.

§What this crate solves

  • Prevents mixing incompatible dimensions (you can’t add metres to seconds).
  • Makes unit conversion explicit and type-checked (to::<TargetUnit>()).
  • Provides a small set of astronomy-friendly units (AU, light-year, solar mass/luminosity, …).
  • Supports multiple scalar types (f64, f32, and optionally Rational64, etc.).

§What this crate does not try to solve

  • Arbitrary symbolic unit algebra (e.g. m^2 * s^-1) or automatic simplification of arbitrary expressions.
  • A full SI-prefix system; only the units defined in this crate are available out of the box.

§Quick start

Convert degrees to radians:

use qtty::{Degree, Radian};

let a = Degree::new(180.0);
let r = a.to::<qtty::unit::Radian>();
assert!((r.value() - core::f64::consts::PI).abs() < 1e-12);

Compose and use derived units (velocity = length / time):

use qtty::{Kilometer, Second};
use qtty::velocity::Velocity;

let d = Kilometer::new(1_000.0);
let t = Second::new(100.0);
let v: Velocity<qtty::unit::Kilometer, qtty::unit::Second> = d / t;
assert!((v.value() - 10.0).abs() < 1e-12);

Using f32 for memory efficiency:

use qtty::f32::{Degree, Meter};

let angle: Degree = Degree::new(45.0_f32);
let distance: Meter = Meter::new(100.0_f32);

§Incorrect usage (type error)

use qtty::{Kilometer, Second};

let d = Kilometer::new(1.0);
let t = Second::new(1.0);
let _ = d + t; // cannot add different unit types

§Scalar Types

The default scalar type is f64. You can use different scalar types:

  • f64 (default) - double precision floating point
  • f32 - single precision floating point (use qtty::f32::*)
  • i8, i16, i32, i64, i128 - signed integers (use qtty::i8::*, qtty::i16::*, qtty::i32::*, qtty::i64::*, qtty::i128::*)
  • Rational64 - exact rational (feature scalar-rational)

Integer quantities provide compile-time unit safety for discrete values. They support basic arithmetic and lossy unit conversion via to_lossy(), but not the full to() method (which requires floating-point semantics).

§Modules

Quantity aliases are exported at the crate root. Unit markers live under qtty::unit for generic APIs such as Quantity<U, S> and Velocity<N, D>:

  • qtty::velocity (Length / Time aliases)
  • qtty::angular_rate (Angular / Time aliases)
  • qtty::area, qtty::volume, qtty::force, qtty::energy
  • qtty::accel (Length / Time² aliases)
  • qtty::pressure (pressure units: Pa, hPa, kPa, bar)
  • qtty::temperature (thermodynamic temperature units: K)
  • qtty::unit (type-level unit markers)
  • qtty::f32 (all units with f32 scalar)
  • qtty::f64 (all units with f64 scalar - same as root)
  • qtty::i8 (all units with i8 scalar)
  • qtty::i16 (all units with i16 scalar)
  • qtty::i32 (all units with i32 scalar)
  • qtty::i64 (all units with i64 scalar)
  • qtty::i128 (all units with i128 scalar)

§Feature flags

  • std (default): enables std support in qtty-core.
  • cross-unit-ops (default): enables direct cross-unit comparison operators (==, <, etc.) for built-in units.
  • alloc: enables heap-backed helpers (like qtty_vec!(vec ...)) in no_std builds.
  • serde: enables serde support for Quantity<U, S>; serialization is the raw scalar value.
  • scalar-rational: enables num_rational::Rational64 as a scalar type.

§Custom Units

qtty re-exports the derive macro plus the arithmetic/conversion macros from qtty-core, so downstream crates can define units without depending on qtty-core directly:

#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, qtty::Unit)]
#[unit(crate = qtty, symbol = "smoot", dimension = qtty::Length, ratio = 1.7018)]
pub struct Smoot;

qtty::impl_unit_arithmetic_pairs_between!(qtty::unit::Meter, qtty::unit::Kilometer; Smoot);

§Limitations of downstream units

Custom units participate in arithmetic (*, /) and From-based conversion via the macro registrations shown above. However, due to Rust’s orphan rules, the derive macro cannot generate Display/LowerExp/UpperExp impls for Quantity<CustomUnit, S> from a downstream crate. Downstream units must implement formatting manually if needed.

Disable default features for no_std:

[dependencies]
qtty = { version = "0.7.0", default-features = false }

If you need qtty_vec!(vec ...) in no_std, enable alloc:

[dependencies]
qtty = { version = "0.7.0", default-features = false, features = ["alloc"] }

§Panics and errors

This crate does not define an error type and does not return Result from its core operations. For floating-point scalars (f64, f32), arithmetic follows IEEE-754 behavior (NaN and infinities propagate). For integer scalars, abs() uses saturating semantics at the minimum value (e.g. i32::MIN.abs() returns i32::MAX instead of panicking). Standard integer overflow rules still apply to addition, subtraction, and multiplication.

§SemVer and stability

This workspace is currently 0.x. Expect breaking changes between minor versions until 1.0.

The following items are explicitly excluded from the semver guarantee even though they appear in the compiled crate:

  • Dim, DimDiv, DimMul — typenum-driven dimension markers used internally by impl_unit_* macros. Their shape will change if the underlying numeric representation is ever replaced.
  • UnitDiv, UnitMul — arithmetic-layer traits whose associated-type signatures depend on the dimension representation above.

All five are marked #[doc(hidden)]. Do not depend on their concrete types in downstream code.

Re-exports§

pub use unit as units;

Modules§

accel
Acceleration quantities represented as Length / Time².
acceleration
Acceleration unit aliases and named units (Length / Time²).
angular
Angular quantities and utilities.
angular_rate
Angular-rate quantities represented as one unit divided by another (Angular / Time).
area
Area units.
dimensionless
Named dimensionless units for domain-specific ratios.
energy
Energy units.
f32
Re-exports of quantity types specialized to f32 scalar.
f64
Re-exports of quantity types specialized to f64 scalar (default).
force
Force units.
i8
Re-exports of quantity types specialized to i8 scalar.
i16
Re-exports of quantity types specialized to i16 scalar.
i32
Re-exports of quantity types specialized to i32 scalar.
i64
Re-exports of quantity types specialized to i64 scalar.
i128
Re-exports of quantity types specialized to i128 scalar.
length
Length units.
mass
Mass units.
power
Power units.
pressure
Pressure units.
solid_angle
Solid-angle units.
temperature
Thermodynamic temperature units.
time
Time units.
unit
Type-level unit markers used by Quantity.
velocity
Velocity quantities represented as one unit divided by another.
volume
Volume units.

Macros§

impl_unit_arithmetic_pairs
Convenience macro that generates both division and multiplication pair tables for a set of units.
impl_unit_arithmetic_pairs_between
Convenience macro that generates both division and multiplication impls between an existing base group and a new extra group.
impl_unit_cross_unit_ops
Generates cross-unit PartialEq and PartialOrd implementations for all pairs of units.
impl_unit_cross_unit_ops_between
Generates cross-unit PartialEq and PartialOrd implementations between every unit in the extra group and every unit in the base group, plus all intra-extra pairs.
impl_unit_division_pairs
Generates UnitDiv impls for all ordered pairs of distinct units.
impl_unit_division_pairs_between
Generates UnitDiv impls between every unit in the extra group and every unit in the base group, plus all intra-extra pairs.
impl_unit_from_conversions
Generates bidirectional From trait implementations for all pairs of units within a dimension.
impl_unit_from_conversions_between
Generates From implementations between every unit in the extra group and every unit in the base group, plus all intra-extra pairs.
impl_unit_multiplication_pairs
Generates UnitMul impls for all ordered pairs of units, including self-pairs (A * A).
impl_unit_multiplication_pairs_between
Generates UnitMul impls between every unit in the extra group and every unit in the base group, plus all intra-extra pairs.
qtty_vec
Build typed quantities from scalar literals without repeating Unit::new(...).

Structs§

Per
Unit representing the division of two other units.
Prod
Unit representing the product of two other units.
Quantity
A quantity with a specific unit and scalar type.

Constants§

DAY
A constant representing one day.
DEG
One degree.
KM
One kilometre.
M
One metre.
RAD
One radian.
SEC
A constant representing one second.

Traits§

Dimension
Marker trait for dimensions.
Exact
Trait for exact numeric types that avoid floating-point rounding.
IntegerScalar
Marker trait for integer scalar types.
Real
Trait for scalar types that support real-number operations.
Scalar
The base trait for all scalar types usable in Quantity.
Transcendental
Trait for scalar types that support transcendental (trigonometric) functions.
Unit
Trait implemented by every unit type.

Type Aliases§

Accel
An acceleration quantity parameterized by length and time units.
Acceleration
Acceleration (L¹ · T⁻²).
Airmass
Airmass quantity.
Albedo
Albedo quantity.
AmountOfSubstance
Amount of substance (N¹).
Angular
Plane angle (A¹) — treated as an independent dimension for type safety.
AngularRate
Angular rate (A¹ · T⁻¹) — angular displacement per unit time.
Area
Area (L²).
Attogram
Attogram.
Attometer
Attometer.
Attosecond
Attosecond.
Attowatt
Attowatt.
Bar
Bar.
Capacitance
Electrical capacitance (M⁻¹ · L⁻² · T⁴ · I²) — SI unit: farad (F).
Centigram
Centigram.
Centiliter
Centiliter.
Centimeter
Centimeter.
Centisecond
Centisecond.
Century
Century.
Charge
Electric charge (I¹ · T¹) — SI unit: coulomb (C = A·s).
CubicCentimeter
CubicCentimeter.
CubicKilometer
CubicKilometer.
CubicMeter
CubicMeter.
CubicMillimeter
CubicMillimeter.
Current
Electric current (I¹).
Day
Day.
Decade
Decade.
Decagram
Decagram.
Decameter
Decameter.
Decasecond
Decasecond.
Decawatt
Decawatt.
Decigram
Decigram.
Deciliter
Deciliter.
Decimeter
Decimeter.
Decisecond
Decisecond.
Deciwatt
Deciwatt.
Degree
Degree.
Density
Mass density (M¹ · L⁻³) — SI unit: kg·m⁻³.
Dimensionless
Dimensionless (all exponents zero).
Energy
Energy (M¹ · L² · T⁻²).
Exagram
Exagram.
Exameter
Exameter.
Exawatt
Exawatt.
Femtogram
Femtogram.
Femtometer
Femtometer.
Femtosecond
Femtosecond.
Femtowatt
Femtowatt.
Force
Force (M¹ · L¹ · T⁻²).
Fortnight
Fortnight.
Frequency
Frequency (T⁻¹) — reciprocal time, SI unit: hertz (Hz = s⁻¹).
Gigagram
Gigagram.
Gigajoule
Gigajoule.
Gigameter
Gigameter.
Giganewton
Giganewton.
Gigapascal
Gigapascal.
Gigasecond
Gigasecond.
Gigawatt
Gigawatt.
Gram
Gram.
Hectogram
Hectogram.
Hectometer
Hectometer.
Hectopascal
Hectopascal.
Hectosecond
Hectosecond.
Hectowatt
Hectowatt.
Hour
Hour.
Illuminance
Illuminance (J¹ · A² · L⁻²) — luminous flux per unit area; SI unit: lux (lx = lm·m⁻²).
IlluminationFraction
Illuminated fraction quantity.
Inductance
Electrical inductance (M¹ · L² · T⁻² · I⁻²) — SI unit: henry (H).
Joule
Joule.
Kelvin
Kelvin.
Kilogram
Kilogram.
Kilojoule
Kilojoule.
Kilometer
Kilometer.
Kilonewton
Kilonewton.
Kilopascal
Kilopascal.
Kilosecond
Kilosecond.
Kilowatt
Kilowatt.
KilowattHour
KilowattHour.
Length
Length (L¹).
Liter
Liter.
LuminousFlux
Luminous flux (J¹ · A²) — radiant power weighted by the luminosity function; SI unit: lumen (lm = cd·sr).
LuminousIntensity
Luminous intensity (J¹).
MagneticFlux
Magnetic flux (M¹ · L² · T⁻² · I⁻¹) — SI unit: weber (Wb).
MagneticFluxDensity
Magnetic flux density / magnetic field (M¹ · T⁻² · I⁻¹) — SI unit: tesla (T).
Mass
Mass (M¹).
Megagram
Megagram.
Megajoule
Megajoule.
Megameter
Megameter.
Meganewton
Meganewton.
Megapascal
Megapascal.
Megasecond
Megasecond.
Megawatt
Megawatt.
Meter
Meter.
MeterPerSecondSquared
MeterPerSecondSquared.
Microgram
Microgram.
Microjoule
Microjoule.
Microliter
Microliter.
Micrometer
Micrometer.
Micronewton
Micronewton.
Microsecond
Microsecond.
Microwatt
Microwatt.
Millennium
Millennium.
Milligram
Milligram.
Millijoule
Millijoule.
Milliliter
Milliliter.
Millimeter
Millimeter.
Millinewton
Millinewton.
Millipascal
Millipascal.
Milliradian
Milliradian.
Millisecond
Millisecond.
Milliwatt
Milliwatt.
Minute
Minute.
Nanogram
Nanogram.
Nanojoule
Nanojoule.
Nanometer
Nanometer.
Nanosecond
Nanosecond.
Nanowatt
Nanowatt.
Newton
Newton.
OpticalDepth
Optical depth quantity.
Pascal
Pascal.
Petagram
Petagram.
Petameter
Petameter.
Petawatt
Petawatt.
Picogram
Picogram.
Picojoule
Picojoule.
Picometer
Picometer.
Picosecond
Picosecond.
Picowatt
Picowatt.
Power
Power (M¹ · L² · T⁻³).
Pressure
Pressure (M¹ · L⁻¹ · T⁻²) — equivalently, force per unit area (N/m²).
Quantity32
A quantity backed by f32.
Quantity64
A quantity backed by f64 (the default).
QuantityI8
A quantity backed by i8.
QuantityI16
A quantity backed by i16.
QuantityI32
A quantity backed by i32.
QuantityI64
A quantity backed by i64.
QuantityI128
A quantity backed by i128.
Radian
Radian.
Rankine
Rankine.
Refractivity
Refractivity quantity.
Resistance
Electrical resistance (M¹ · L² · T⁻³ · I⁻²) — SI unit: ohm (Ω).
Second
Second.
SquareCentimeter
SquareCentimeter.
SquareDegree
SquareDegree.
SquareKilometer
SquareKilometer.
SquareMeter
SquareMeter.
SquareMillimeter
SquareMillimeter.
SquareMilliradian
SquareMilliradian.
StandardGravity
StandardGravity.
Steradian
Steradian.
Temperature
Thermodynamic temperature (Θ¹).
Teragram
Teragram.
Terajoule
Terajoule.
Terameter
Terameter.
Terasecond
Terasecond.
Terawatt
Terawatt.
Time
Time (T¹).
Tonne
Tonne.
Transmittance
Transmittance quantity.
Turn
Turn.
Velocity
Velocity (L¹ · T⁻¹).
Voltage
Voltage / electromotive force (M¹ · L² · T⁻³ · I⁻¹) — SI unit: volt (V).
Volume
Volume (L³).
Watt
Watt.
WattHour
WattHour.
Week
Week.
Year
Year.
Yoctogram
Yoctogram.
Yoctometer
Yoctometer.
Yoctowatt
Yoctowatt.
Yottagram
Yottagram.
Yottameter
Yottameter.
Yottawatt
Yottawatt.
Zeptogram
Zeptogram.
Zeptometer
Zeptometer.
Zeptowatt
Zeptowatt.
Zettagram
Zettagram.
Zettameter
Zettameter.
Zettawatt
Zettawatt.

Derive Macros§

Unit
Derive macro used to define unit marker types.