Skip to content

Commit

Permalink
Merge pull request #215 from bheisler/iterate_units
Browse files Browse the repository at this point in the history
Generate an enum with one variant for each unit, use that for iteration.
  • Loading branch information
iliekturtles authored Nov 7, 2020
2 parents 6f5fbbc + f754470 commit a77ef61
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/quantity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,46 @@ macro_rules! quantity {
$description
}

/// Unit enum.
#[allow(non_camel_case_types)]
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum Units {
$(#[doc=$plural] $unit($unit),)+
}

impl Units {
/// Unit abbreviation.
pub fn abbreviation(&self) -> &'static str {
match self {
$(Units::$unit(_) => <$unit as super::Unit>::abbreviation(),)+
}
}

/// Unit singular description.
pub fn singular(&self) -> &'static str {
match self {
$(Units::$unit(_) => <$unit as super::Unit>::singular(),)+
}
}

/// Unit plural description.
pub fn plural(&self) -> &'static str {
match self {
$(Units::$unit(_) => <$unit as super::Unit>::plural(),)+
}
}
}

static ALL_UNITS: &[Units] = &[
$(Units::$unit($unit),)+
];

/// Iterate over all defined units for this quantity.
pub fn units() -> impl Iterator<Item = Units> {
ALL_UNITS.iter().copied()
}

impl<U, V> $quantity<U, V>
where
U: super::Units<V> + ?Sized,
Expand Down
13 changes: 13 additions & 0 deletions src/tests/quantity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,19 @@ storage_types! {
a == b && a == c
}
}

#[test]
fn test_units_iterator() {
let mut units_iter = crate::si::volume::units();

// Specifically check the first few units. Doubles as a test of abbreviation() and others
assert_eq!("Ym³", units_iter.next().unwrap().abbreviation());
assert_eq!("cubic zettameter", units_iter.next().unwrap().singular());
assert_eq!("cubic exameters", units_iter.next().unwrap().plural());

// And there should be 63 remaining units.
assert_eq!(63, units_iter.count());
}
}

#[cfg(feature = "std")]
Expand Down

0 comments on commit a77ef61

Please sign in to comment.