proof_of_sql/base/posql_time/
timezone.rs

1use super::PoSQLTimestampError;
2use alloc::{string::ToString, sync::Arc};
3use core::fmt;
4use serde::{Deserialize, Serialize};
5
6/// Captures a timezone from a timestamp query
7#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize, PartialEq, Eq)]
8pub struct PoSQLTimeZone {
9    offset: i32,
10}
11
12impl PoSQLTimeZone {
13    /// Create a timezone from a count of seconds
14    #[must_use]
15    pub const fn new(offset: i32) -> Self {
16        PoSQLTimeZone { offset }
17    }
18    #[must_use]
19    /// The UTC timezone
20    pub const fn utc() -> Self {
21        PoSQLTimeZone::new(0)
22    }
23    /// Get the underlying offset in seconds
24    #[must_use]
25    pub const fn offset(self) -> i32 {
26        self.offset
27    }
28}
29
30impl From<proof_of_sql_parser::posql_time::PoSQLTimeZone> for PoSQLTimeZone {
31    fn from(value: proof_of_sql_parser::posql_time::PoSQLTimeZone) -> Self {
32        PoSQLTimeZone::new(value.offset())
33    }
34}
35
36impl TryFrom<&Option<Arc<str>>> for PoSQLTimeZone {
37    type Error = PoSQLTimestampError;
38
39    fn try_from(value: &Option<Arc<str>>) -> Result<Self, Self::Error> {
40        match value {
41            Some(tz_str) => {
42                let tz = Arc::as_ref(tz_str).to_uppercase();
43                match tz.as_str() {
44                    "Z" | "UTC" | "00:00" | "+00:00" | "0:00" | "+0:00" => Ok(PoSQLTimeZone::utc()),
45                    tz if tz.chars().count() == 6
46                        && (tz.starts_with('+') || tz.starts_with('-')) =>
47                    {
48                        let sign = if tz.starts_with('-') { -1 } else { 1 };
49                        let hours = tz[1..3]
50                            .parse::<i32>()
51                            .map_err(|_| PoSQLTimestampError::InvalidTimezoneOffset)?;
52                        let minutes = tz[4..6]
53                            .parse::<i32>()
54                            .map_err(|_| PoSQLTimestampError::InvalidTimezoneOffset)?;
55                        let total_seconds = sign * ((hours * 3600) + (minutes * 60));
56                        Ok(PoSQLTimeZone::new(total_seconds))
57                    }
58                    _ => Err(PoSQLTimestampError::InvalidTimezone {
59                        timezone: tz.to_string(),
60                    }),
61                }
62            }
63            None => Ok(PoSQLTimeZone::utc()),
64        }
65    }
66}
67
68impl fmt::Display for PoSQLTimeZone {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        let seconds = self.offset();
71        let hours = seconds / 3600;
72        let minutes = (seconds.abs() % 3600) / 60;
73        if seconds < 0 {
74            write!(f, "-{:02}:{:02}", hours.abs(), minutes)
75        } else {
76            write!(f, "+{hours:02}:{minutes:02}")
77        }
78    }
79}
80
81#[cfg(test)]
82mod timezone_parsing_tests {
83    use super::*;
84    use alloc::format;
85
86    #[test]
87    fn test_display_fixed_offset_positive() {
88        let timezone = PoSQLTimeZone::new(4500); // +01:15
89        assert_eq!(format!("{timezone}"), "+01:15");
90    }
91
92    #[test]
93    fn test_display_fixed_offset_negative() {
94        let timezone = PoSQLTimeZone::new(-3780); // -01:03
95        assert_eq!(format!("{timezone}"), "-01:03");
96    }
97
98    #[test]
99    fn test_display_utc() {
100        let timezone = PoSQLTimeZone::utc();
101        assert_eq!(format!("{timezone}"), "+00:00");
102    }
103}