routee_compass_core/model/unit/
volume_unit.rs1use serde::{Deserialize, Serialize};
2use std::str::FromStr;
3
4#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Default)]
5#[serde(rename_all = "snake_case", try_from = "String")]
6pub enum VolumeUnit {
7 #[default]
8 GallonsUs,
9 GallonsUk,
10 Liters,
11}
12
13impl std::fmt::Display for VolumeUnit {
14 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15 let s = serde_json::to_string(self)
16 .map_err(|_| std::fmt::Error)?
17 .replace('\"', "");
18 write!(f, "{s}")
19 }
20}
21
22impl FromStr for VolumeUnit {
23 type Err = String;
24
25 fn from_str(s: &str) -> Result<Self, Self::Err> {
26 use VolumeUnit as V;
27 match s.trim().to_lowercase().as_str() {
28 "gal" | "usgal" | "usgals" => Ok(V::GallonsUs),
29 "ukgal" | "ukgals" => Ok(V::GallonsUk),
30 "liter" | "liters" | "l" => Ok(V::Liters),
31 _ => Err(format!("unknown volume unit '{s}'")),
32 }
33 }
34}
35
36impl TryFrom<String> for VolumeUnit {
37 type Error = String;
38 fn try_from(value: String) -> Result<Self, Self::Error> {
39 Self::from_str(&value)
40 }
41}