pub struct Unit { /* private fields */ }Expand description
Unit wraps a GNU units unittype for safe use from Rust.
A Unit represents a dimensional quantity: a numeric factor paired with
zero or more base dimensions (length, time, mass, …). Instances are
constructed via Unit::new (dimensionless, factor 1) or Unit::parse
(from a GNU units expression string). All arithmetic operations mutate
self in place and return Result<()>.
Unit owns the memory allocated by the C library; it is freed
automatically when the value is dropped.
§Examples
use gnu_units::Unit;
let mut area = Unit::parse("3 m")?;
area.multiply(Unit::parse("4 m")?)?;
println!("factor: {}", area.factor()); // 12.0Implementations§
Source§impl Unit
impl Unit
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a freshly initialized unit with factor 1.0 and no dimensions.
The underlying C function initializeunit zeroes all fields of the
unittype struct, producing the multiplicative identity, equivalent
to the dimensionless number 1.
Prefer Unit::parse when you want a unit with a specific value or
dimensions.
§Examples
use gnu_units::Unit;
let unit = Unit::new();
assert_eq!(unit.factor(), 1.0);Sourcepub fn parse(input: &str) -> Result<Self>
pub fn parse(input: &str) -> Result<Self>
Parses a GNU units expression string and returns the resulting Unit.
input is passed to the underlying C function parseunit. The string
is first converted to a null-terminated C string; a null byte anywhere
in input causes an immediate E_PARSE error without reaching the C
layer.
§Errors
Returns Err(UnitsError) with code == E_PARSE when:
inputcontains a null byte (\0).inputis not a valid GNU units expression (e.g. unbalanced parentheses, unknown unit name).
§Examples
use gnu_units::Unit;
let km = Unit::parse("km")?;
println!("factor: {}", km.factor());
assert!(Unit::parse(")").is_err());Sourcepub fn multiply(&mut self, rhs: Unit) -> Result<()>
pub fn multiply(&mut self, rhs: Unit) -> Result<()>
Multiplies self by rhs in place, consuming rhs.
Delegates to the C function multunit. Ownership of rhs is
transferred to the C layer, which merges its dimension arrays into
self. rhs is dropped after the call; the underlying C allocation
is freed safely because multunit leaves the rhs struct in a
defined (empty) state.
§Errors
Returns Err(UnitsError) if the multiplication cannot be represented
(e.g. a dimensional overflow reported by the C library).
§Examples
use gnu_units::Unit;
let mut lhs = Unit::parse("3")?;
lhs.multiply(Unit::parse("4")?)?;
assert_eq!(lhs.factor(), 12.0);Sourcepub fn divide(&mut self, rhs: Unit) -> Result<()>
pub fn divide(&mut self, rhs: Unit) -> Result<()>
Divides self by rhs in place, consuming rhs.
Delegates to the C function divunit. Ownership of rhs is
transferred to the C layer, which inverts rhs and merges its
dimension arrays into self. rhs is dropped after the call; the
underlying C allocation is freed safely because divunit leaves the
rhs struct in a defined (empty) state.
§Errors
Returns Err(UnitsError) if the division cannot be represented (e.g.
a dimensional inconsistency reported by the C library).
§Examples
use gnu_units::Unit;
let mut lhs = Unit::parse("10")?;
lhs.divide(Unit::parse("2")?)?;
assert_eq!(lhs.factor(), 5.0);Sourcepub fn add(&mut self, rhs: Unit) -> Result<()>
pub fn add(&mut self, rhs: Unit) -> Result<()>
Adds rhs to self in place, consuming rhs.
Delegates to the C function addunit. Both units must be
dimensionally compatible (same base dimensions). Ownership of rhs
is transferred to the C layer; rhs is dropped after the call.
§Errors
Returns Err(UnitsError) when the two units have incompatible
dimensions (e.g. adding a length to a mass).
§Examples
use gnu_units::Unit;
let mut lhs = Unit::parse("3")?;
lhs.add(Unit::parse("7")?)?;
assert_eq!(lhs.factor(), 10.0);Sourcepub fn invert(&mut self)
pub fn invert(&mut self)
Swaps the numerator and denominator of self in place.
Delegates to the C function invertunit, which negates the exponent
of every base dimension and takes the reciprocal of the numeric
factor. The operation is always well-defined and cannot fail.
§Examples
use gnu_units::Unit;
let mut unit = Unit::parse("5")?;
unit.invert();
assert_eq!(unit.factor(), 0.2);Sourcepub fn pow(&mut self, power: c_int) -> Result<()>
pub fn pow(&mut self, power: c_int) -> Result<()>
Raises self to a non-negative integer power in place.
Delegates to the C function expunit, which multiplies the exponent
of every base dimension by power and raises the numeric factor to
power.
§Errors
Returns Err(UnitsError) when:
poweris negative (negative exponents are not supported).- The resulting dimensions cannot be represented (e.g. an exponent overflow reported by the C library).
§Examples
use gnu_units::Unit;
let mut unit = Unit::parse("3")?;
unit.pow(2)?;
assert_eq!(unit.factor(), 9.0);Sourcepub fn root(&mut self, n: c_int) -> Result<()>
pub fn root(&mut self, n: c_int) -> Result<()>
Takes the nth root of self in place.
Delegates to the C function rootunit. The root must be exact: every
base-dimension exponent in self must be divisible by n. If it is
not, the C library returns an error rather than producing a fractional
exponent.
§Errors
Returns Err(UnitsError) when n is not positive (greater than zero),
when the root is not exact (i.e. a dimension exponent is not divisible
by n), or when the C library signals another failure.
§Examples
use gnu_units::Unit;
let mut unit = Unit::parse("9")?;
unit.root(2)?;
assert_eq!(unit.factor(), 3.0);Sourcepub fn to_number(&self) -> Result<f64>
pub fn to_number(&self) -> Result<f64>
Converts a dimensionless unit to its numeric value.
Internally clones self and calls the C function unit2num on the
clone, so the original unit is not mutated. The returned f64 is
the numeric factor of the dimensionless quantity.
§Errors
Returns Err(UnitsError) when self carries non-zero base
dimensions (e.g. metres, kilograms). Use Unit::factor to read
the numeric factor unconditionally regardless of dimensions.
§Examples
use gnu_units::Unit;
let unit = Unit::parse("42")?;
assert_eq!(unit.to_number()?, 42.0);Sourcepub fn factor(&self) -> f64
pub fn factor(&self) -> f64
Returns the numeric factor of the unit.
The factor is the double factor field of the underlying unittype
struct. For a dimensionless unit it is the plain numeric value; for
a dimensional unit it is the SI conversion factor (e.g. 1000.0
for km when the base unit is metres).
This accessor is always infallible. For a strict dimensionless
check, use Unit::to_number instead.
§Examples
use gnu_units::Unit;
let unit = Unit::parse("5")?;
assert_eq!(unit.factor(), 5.0);Sourcepub fn convert_to(self, to: Unit) -> Result<f64>
pub fn convert_to(self, to: Unit) -> Result<f64>
Converts self into the unit expressed by to, returning the numeric
conversion factor.
Both self and to are consumed by this call. Internally, to is
divided out of self using Unit::divide, and the dimensionless
result is extracted with Unit::to_number.
§Errors
Returns Err(UnitsError) when:
selfandtohave incompatible dimensions (e.g. converting kilometres to kilograms), in which caseUnit::to_numberreports a dimensional mismatch.- The division itself fails (e.g. a dimensional overflow reported by the C library).
§Examples
use gnu_units::Unit;
let factor = Unit::parse("5 km")?.convert_to(Unit::parse("miles")?)?;
println!("{factor}"); // ≈ 3.1069Sourcepub fn base_units(&self) -> String
pub fn base_units(&self) -> String
Returns the base dimensions of the unit as a human-readable string.
Each non-empty, non-sentinel slot in the numerator and denominator
arrays of the underlying unittype is read and the corresponding C
string is collected. The terms are primitive base units as resolved by
the parser, but they are not sorted or canceled, redundant terms
(e.g. from "m/s * s") may appear in both numerator and denominator.
Result formats:
"m", numerator only"kg m / s s", numerator and denominator"1 / s", denominator only (numerator is empty)"", dimensionless (both arrays are empty)
Sourcepub fn is_conformable(&self, other: &Unit) -> bool
pub fn is_conformable(&self, other: &Unit) -> bool
Returns true when self and other have the same base dimensions.
Two units are conformable when they describe the same physical quantity
(e.g. km and miles are both lengths). The check divides a clone of
self by a clone of other and attempts to reduce the result to a
dimensionless number: success means the units are conformable.
Neither self nor other is consumed or mutated.
Trait Implementations§
Source§impl Clone for Unit
impl Clone for Unit
Source§fn clone(&self) -> Self
fn clone(&self) -> Self
Returns a deep copy of self.
Delegates to the C function unitcopy, which duplicates all heap
allocations owned by the unittype struct. The cloned Unit is
fully independent: dropping either value does not affect the other.
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Drop for Unit
impl Drop for Unit
Source§fn drop(&mut self)
fn drop(&mut self)
Releases the C heap memory owned by this unit.
Delegates to the C function freeunit, which frees the dimension
arrays allocated by parseunit or unitcopy. After drop, all
pointer fields inside the unittype struct are invalid; the struct
itself is on the Rust stack and is reclaimed by Rust after this
function returns.