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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use std::convert::TryFrom;
use std::fmt;
use std::ops::Sub;
use anyhow::anyhow;
use chrono::NaiveDate;
use mz_proto::{RustType, TryFromProtoError};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use thiserror::Error;
include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.date.rs"));
#[derive(Debug, Error)]
pub enum DateError {
#[error("data out of range")]
OutOfRange,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Hash, Deserialize)]
pub struct Date {
days: i32,
}
impl RustType<ProtoDate> for Date {
fn into_proto(&self) -> ProtoDate {
ProtoDate { days: self.days }
}
fn from_proto(proto: ProtoDate) -> Result<Self, TryFromProtoError> {
Ok(Date { days: proto.days })
}
}
impl std::str::FromStr for Date {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
crate::strconv::parse_date(s).map_err(|e| anyhow!(e))
}
}
static PG_EPOCH: Lazy<NaiveDate> = Lazy::new(|| NaiveDate::from_ymd_opt(2000, 1, 1).unwrap());
impl Date {
pub const UNIX_EPOCH_TO_PG_EPOCH: i32 = 10957; const CE_EPOCH_TO_PG_EPOCH: i32 = 730120; pub const LOW_DAYS: i32 = -2451545; pub const HIGH_DAYS: i32 = 95_015_644;
pub fn from_pg_epoch(days: i32) -> Result<Date, DateError> {
if days < Self::LOW_DAYS || days > Self::HIGH_DAYS {
Err(DateError::OutOfRange)
} else {
Ok(Date { days })
}
}
pub fn from_unix_epoch(unix_days: i32) -> Result<Date, DateError> {
let pg_days = unix_days.saturating_sub(Self::UNIX_EPOCH_TO_PG_EPOCH);
if pg_days == i32::MIN {
return Err(DateError::OutOfRange);
}
Self::from_pg_epoch(pg_days)
}
pub fn pg_epoch_days(&self) -> i32 {
self.days
}
pub fn is_finite(&self) -> bool {
self.days != i32::MAX && self.days != i32::MIN
}
pub fn unix_epoch_days(&self) -> i32 {
assert!(self.is_finite());
self.days + Self::UNIX_EPOCH_TO_PG_EPOCH
}
pub fn checked_add(self, days: i32) -> Result<Date, DateError> {
let days = if let Some(days) = self.days.checked_add(days) {
days
} else {
return Err(DateError::OutOfRange);
};
Self::from_pg_epoch(days)
}
}
impl Sub for Date {
type Output = i32;
fn sub(self, rhs: Self) -> Self::Output {
assert!(self.is_finite());
self.days - rhs.days
}
}
impl From<Date> for NaiveDate {
fn from(date: Date) -> Self {
Self::from(&date)
}
}
impl From<&Date> for NaiveDate {
fn from(date: &Date) -> Self {
let days = date
.pg_epoch_days()
.checked_add(Date::CE_EPOCH_TO_PG_EPOCH)
.expect("out of range date are prevented");
NaiveDate::from_num_days_from_ce_opt(days).unwrap()
}
}
impl TryFrom<NaiveDate> for Date {
type Error = DateError;
fn try_from(value: NaiveDate) -> Result<Self, Self::Error> {
let d = value.signed_duration_since(*PG_EPOCH);
let days: i32 = d.num_days().try_into().map_err(|_| DateError::OutOfRange)?;
Self::from_pg_epoch(days)
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let d: NaiveDate = (*self).into();
d.format("%Y-%m-%d").fmt(f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_date() {
let pgepoch = Date::from_pg_epoch(0).unwrap();
let unixepoch = Date::from_unix_epoch(0).unwrap();
assert_eq!(pgepoch.pg_epoch_days(), 0);
assert_eq!(pgepoch.unix_epoch_days(), 10957);
assert_eq!(unixepoch.pg_epoch_days(), -10957);
assert_eq!(unixepoch.unix_epoch_days(), 0);
assert_eq!(
NaiveDate::from(pgepoch),
NaiveDate::from_ymd_opt(2000, 1, 1).unwrap()
);
assert_eq!(
pgepoch,
Date::try_from(NaiveDate::from_ymd_opt(2000, 1, 1).unwrap()).unwrap()
);
assert_eq!(
unixepoch,
Date::try_from(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()).unwrap()
);
assert_eq!(
unixepoch,
Date::try_from(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()).unwrap()
);
assert!(pgepoch > unixepoch);
}
}