opentitanlib/util/
voltage.rs1use serde::{Deserialize, Serialize};
6use std::fmt::{Display, Formatter};
7use std::num::ParseFloatError;
8use std::str::FromStr;
9
10#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
11pub struct Voltage(pub f64);
12
13impl FromStr for Voltage {
14 type Err = ParseFloatError;
15
16 fn from_str(s: &str) -> Result<Self, Self::Err> {
17 let voltage = s.to_lowercase().replace('v', ".");
19 Ok(Voltage(f64::from_str(&voltage)?))
20 }
21}
22
23impl Display for Voltage {
24 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
25 self.0.fmt(f)
26 }
27}
28
29impl Voltage {
30 pub fn as_volts(&self) -> f64 {
31 self.0
32 }
33 pub fn as_millivolts(&self) -> u32 {
34 (self.0 * 1000.0) as u32
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41 use anyhow::Result;
42
43 #[test]
44 fn test_from_string() -> Result<()> {
45 assert_eq!(Voltage::from_str("3.3")?.as_volts(), 3.3);
46 assert_eq!(Voltage::from_str("3v3")?.as_volts(), 3.3);
47 assert_eq!(Voltage::from_str("1V8")?.as_volts(), 1.8);
48 assert!(Voltage::from_str("1k4").is_err());
49 Ok(())
50 }
51
52 #[test]
53 fn test_conversions() -> Result<()> {
54 assert_eq!(Voltage(2.5).as_volts(), 2.5);
55 assert_eq!(Voltage(2.5).as_millivolts(), 2500);
56 assert_eq!(Voltage(3.1173).as_millivolts(), 3117);
57 Ok(())
58 }
59}