Skip to main content

Unit

Struct Unit 

Source
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.0

Implementations§

Source§

impl Unit

Source

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);
Source

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:

  • input contains a null byte (\0).
  • input is 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());
Source

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);
Source

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);
Source

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);
Source

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);
Source

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:

  • power is 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);
Source

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);
Source

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);
Source

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);
Source

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:

  • self and to have incompatible dimensions (e.g. converting kilometres to kilograms), in which case Unit::to_number reports 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.1069
Source

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)
Source

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

Source§

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)

Performs copy-assignment from source. Read more
Source§

impl Default for Unit

Source§

fn default() -> Self

Returns a freshly initialized unit with factor 1.0 and no dimensions.

Equivalent to Unit::new.

Source§

impl Drop for Unit

Source§

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.

Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Send for Unit

Source§

impl Sync for Unit

Auto Trait Implementations§

§

impl Freeze for Unit

§

impl RefUnwindSafe for Unit

§

impl Unpin for Unit

§

impl UnsafeUnpin for Unit

§

impl UnwindSafe for Unit

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.