units.rs
This file
Path
src/util/units.rs
45 lines · 1.1 KiB · Rust
Last changed by
Move a few modules to utilDavid Peterbefore adoption5c634c9
History of this fileTake it
Move a few modules to utilDavid Peterbefore adoption5c634c9
lines 1–45why, one step back1//! This module contains common units.23pub type Scalar = f64;45/// Type alias for unit of time6pub type Second = Scalar;78/// Supported time units9#[derive(Debug, Clone, Copy, PartialEq)]10pub enum Unit {11 Second,12 MilliSecond,13}1415impl Unit {16 /// The abbreviation of the Unit.17 pub fn short_name(self) -> String {18 match self {19 Unit::Second => String::from("s"),20 Unit::MilliSecond => String::from("ms"),21 }22 }2324 /// Returns the Second value formatted for the Unit.25 pub fn format(self, value: Second) -> String {26 match self {27 Unit::Second => format!("{:.3}", value),28 Unit::MilliSecond => format!("{:.1}", value * 1e3),29 }30 }31}3233#[test]34fn test_unit_short_name() {35 assert_eq!("s", Unit::Second.short_name());36 assert_eq!("ms", Unit::MilliSecond.short_name());37}3839// Note - the values are rounded when formatted.40#[test]41fn test_unit_format() {42 let value: Second = 123.456789;43 assert_eq!("123.457", Unit::Second.format(value));44 assert_eq!("123456.8", Unit::MilliSecond.format(value));45}