1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use crate::{Date, OfDay, Span, Time};

#[derive(Copy, Clone)]
pub struct TzOffset {
    pub utc_offset: i32,
    pub dst_offset: i32,
}

#[derive(Clone)]
pub struct TzInfo {
    pub first: TzOffset,
    pub rest: &'static [(i64, TzOffset)],
}

impl TzOffset {
    pub const ZERO: TzOffset = TzOffset { utc_offset: 0, dst_offset: 0 };

    pub fn total_offset_sec(&self) -> i32 {
        self.utc_offset + self.dst_offset
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
pub enum TzError {
    NoTimeInThisTz,
    TwoTimesInThisTz(Time, Time),
}

impl std::fmt::Display for TzError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for TzError {}

impl TzInfo {
    pub fn find(&self, time: Time) -> &TzOffset {
        let sec = time.0.div_euclid(Span::SEC.to_int_ns());
        let index = self.rest.partition_point(|&(start_sec, _)| sec >= start_sec);
        if index == 0 {
            &self.first
        } else {
            &self.rest[index - 1].1
        }
    }

    pub fn offset(&self, time: Time) -> Span {
        let fixed_timespan = self.find(time);
        Span::of_int_sec(fixed_timespan.total_offset_sec() as i64)
    }

    pub const GMT: TzInfo = TzInfo { first: TzOffset::ZERO, rest: &[] };

    fn valid_time(&self, gmt_sec: i64, nanosecond: i64, next_i: usize) -> Option<Time> {
        let (min_sec, tz_info) = if next_i == 0 {
            (i64::MIN, self.first)
        } else if next_i > self.rest.len() {
            return None;
        } else {
            self.rest[next_i - 1]
        };
        let sec = gmt_sec - tz_info.total_offset_sec() as i64;
        if sec >= min_sec && (self.rest.len() == next_i || sec < self.rest[next_i].0) {
            Some(Time(sec * Span::SEC.to_int_ns() + nanosecond))
        } else {
            None
        }
    }

    pub fn date_ofday_to_time(&self, date: Date, ofday: OfDay) -> Result<Time, TzError> {
        let gmt_ns = (date - Date::UNIX_EPOCH) as i64 * Span::DAY.to_int_ns();
        let gmt_ns = gmt_ns + ofday.to_ns_since_midnight();
        let gmt_sec = gmt_ns.div_euclid(Span::SEC.to_int_ns());
        let nanosecond = gmt_ns.rem_euclid(Span::SEC.to_int_ns());
        let next_i = self.rest.partition_point(|&(start_sec, _)| gmt_sec >= start_sec);
        if next_i == 0 {
            let t1 = self.valid_time(gmt_sec, nanosecond, next_i);
            let t2 = self.valid_time(gmt_sec, nanosecond, next_i + 1);
            match (t1, t2) {
                (None, None) => Err(TzError::NoTimeInThisTz),
                (Some(v), None) | (None, Some(v)) => Ok(v),
                (Some(v1), Some(v2)) => Err(TzError::TwoTimesInThisTz(v1, v2)),
            }
        } else {
            let t0 = self.valid_time(gmt_sec, nanosecond, next_i - 1);
            let t1 = self.valid_time(gmt_sec, nanosecond, next_i);
            let t2 = self.valid_time(gmt_sec, nanosecond, next_i + 1);
            match (t0, t1, t2) {
                (None, None, None) => Err(TzError::NoTimeInThisTz),
                (Some(v), None, None) | (None, Some(v), None) | (None, None, Some(v)) => Ok(v),
                (Some(v1), Some(v2), _) | (Some(v1), _, Some(v2)) | (_, Some(v1), Some(v2)) => {
                    Err(TzError::TwoTimesInThisTz(v1, v2))
                }
            }
        }
    }
}