Typesafe, compile-time checked units library for Rust.
Go to file
elfeiin 599b8ceb25
qol touches
2024-05-05 19:39:24 -07:00
examples small error fixes 2024-05-05 19:27:23 -07:00
src qol touches 2024-05-05 19:39:24 -07:00
.gitignore v0.4.0 2024-03-01 16:54:05 -08:00
Cargo.toml small API change: Measurement no longer takes a unit in new 2024-05-05 19:23:11 -07:00
README.md small fixes, bump minor 2024-05-04 00:59:32 -07:00

README.md

units

Type-safe units handling library. Do arithmetic on measurements. Convert between different units.

example

#![feature(generic_const_exprs)]

use std::f64::consts::TAU;
use unidades::{
    dimensions::{
        Energy,
        Frequency,
        Length,
        Mass,
        MassMoment,
    },
    units::{
        Gram,
        Joule,
        Meter,
        Rpm,
        Watthour,
    },
    Unit,
    prefixes::Kilo,
};

#[derive(Debug)]
pub struct Flywheel {
    mass: Mass,
    radius: Length,
    inertial_constant: f64,
}

impl Flywheel {
    pub fn new_cylinder(mass: Mass, radius: Length) -> Self {
        Self {
            mass,
            radius,
            // Cylinder
            inertial_constant: 0.606,
        }
    }

    pub fn new_good(mass: Mass, radius: Length) -> Self {
        Self {
            mass,
            radius,
            // Mass concentrated around rim
            inertial_constant: 1.0,
        }
    }

    pub fn inertial_moment(&self) -> MassMoment {
        self.mass * self.inertial_constant * (self.radius * self.radius)
    }

    pub fn energy(&self, spin_rate: Frequency) -> Energy {
        let angular_velocity = spin_rate * TAU;
        self.inertial_moment() * (angular_velocity * angular_velocity) / 2.0
    }
}

fn main() {
    let flywheel = Flywheel::new_good(Kilo::<Gram>::new(300.0), Meter::new(0.5));
    let frequency = Rpm::new(60000.0);
    let energy = flywheel.energy(frequency);
    println!["{flywheel:?}"];
    println![
        "Energy at {} rpm: {} joules or {} kilowatthours",
        frequency.to_units::<Rpm>(),
        energy.to_units::<Joule>(),
        energy.to_units::<Watthour>() / 1000.0
    ];
}