proof_of_sql/base/posql_time/
unit.rs1use super::PoSQLTimestampError;
2use core::fmt;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize, PartialEq, Eq)]
7pub enum PoSQLTimeUnit {
8 Second,
10 Millisecond,
12 Microsecond,
14 Nanosecond,
16}
17
18impl From<PoSQLTimeUnit> for u64 {
19 fn from(value: PoSQLTimeUnit) -> u64 {
20 match value {
21 PoSQLTimeUnit::Second => 0,
22 PoSQLTimeUnit::Millisecond => 3,
23 PoSQLTimeUnit::Microsecond => 6,
24 PoSQLTimeUnit::Nanosecond => 9,
25 }
26 }
27}
28
29impl TryFrom<&str> for PoSQLTimeUnit {
30 type Error = PoSQLTimestampError;
31 fn try_from(value: &str) -> Result<Self, PoSQLTimestampError> {
32 match value {
33 "0" => Ok(PoSQLTimeUnit::Second),
34 "3" => Ok(PoSQLTimeUnit::Millisecond),
35 "6" => Ok(PoSQLTimeUnit::Microsecond),
36 "9" => Ok(PoSQLTimeUnit::Nanosecond),
37 _ => Err(PoSQLTimestampError::UnsupportedPrecision {
38 error: value.into(),
39 }),
40 }
41 }
42}
43
44impl fmt::Display for PoSQLTimeUnit {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 match self {
47 PoSQLTimeUnit::Second => write!(f, "seconds (precision: 0)"),
48 PoSQLTimeUnit::Millisecond => write!(f, "milliseconds (precision: 3)"),
49 PoSQLTimeUnit::Microsecond => write!(f, "microseconds (precision: 6)"),
50 PoSQLTimeUnit::Nanosecond => write!(f, "nanoseconds (precision: 9)"),
51 }
52 }
53}
54
55#[cfg(test)]
58#[expect(clippy::missing_panics_doc)]
59mod time_unit_tests {
60 use super::*;
61 use crate::base::posql_time::PoSQLTimestampError;
62
63 #[test]
64 fn test_valid_precisions() {
65 assert_eq!(PoSQLTimeUnit::try_from("0"), Ok(PoSQLTimeUnit::Second));
66 assert_eq!(PoSQLTimeUnit::try_from("3"), Ok(PoSQLTimeUnit::Millisecond));
67 assert_eq!(PoSQLTimeUnit::try_from("6"), Ok(PoSQLTimeUnit::Microsecond));
68 assert_eq!(PoSQLTimeUnit::try_from("9"), Ok(PoSQLTimeUnit::Nanosecond));
69 }
70
71 #[test]
72 fn test_invalid_precision() {
73 let invalid_precisions = [
74 "1", "2", "4", "5", "7", "8", "10", "zero", "three", "cat", "-1", "-2",
75 ]; for &value in &invalid_precisions {
77 let result = PoSQLTimeUnit::try_from(value);
78 assert!(matches!(
79 result,
80 Err(PoSQLTimestampError::UnsupportedPrecision { .. })
81 ));
82 }
83 }
84}