vcd/
timescale.rs

1use std::fmt::{self, Display};
2use std::str::FromStr;
3
4/// A unit of time for the `$timescale` command.
5#[derive(Debug, Copy, Clone, Eq, PartialEq)]
6pub enum TimescaleUnit {
7    /// Second
8    S,
9
10    /// Millisecond (10^-3)
11    MS,
12
13    /// Microsecond (10^-6)
14    US,
15
16    /// Nanosecond (10^-9)
17    NS,
18
19    /// Picosecond (10^-12)
20    PS,
21
22    /// Femtosecond (10^-15)
23    FS,
24}
25
26crate::unit_error_struct!(InvalidTimescaleUnit, "invalid timescale unit");
27
28impl FromStr for TimescaleUnit {
29    type Err = InvalidTimescaleUnit;
30    fn from_str(s: &str) -> Result<Self, Self::Err> {
31        use TimescaleUnit::*;
32        match s {
33            "s" => Ok(S),
34            "ms" => Ok(MS),
35            "us" => Ok(US),
36            "ns" => Ok(NS),
37            "ps" => Ok(PS),
38            "fs" => Ok(FS),
39            _ => Err(InvalidTimescaleUnit),
40        }
41    }
42}
43
44impl Display for TimescaleUnit {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        use TimescaleUnit::*;
47        write!(
48            f,
49            "{}",
50            match *self {
51                S => "s",
52                MS => "ms",
53                US => "us",
54                NS => "ns",
55                PS => "ps",
56                FS => "fs",
57            }
58        )
59    }
60}
61
62impl TimescaleUnit {
63    /// The number of timescale ticks per second.
64    pub fn divisor(&self) -> u64 {
65        use TimescaleUnit::*;
66        match *self {
67            S => 1,
68            MS => 1_000,
69            US => 1_000_000,
70            NS => 1_000_000_000,
71            PS => 1_000_000_000_000,
72            FS => 1_000_000_000_000_000,
73        }
74    }
75
76    /// The duration of a timescale tick in seconds.
77    pub fn fraction(&self) -> f64 {
78        1.0 / (self.divisor() as f64)
79    }
80}