-
Notifications
You must be signed in to change notification settings - Fork 198
/
datetime.rs
429 lines (382 loc) · 12.7 KB
/
datetime.rs
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::{PyDate, PyDateTime, PyDelta, PyDeltaAccess, PyTime, PyTzInfo};
use speedate::{Date, DateTime, Duration, Time};
use strum::EnumMessage;
use crate::errors::{ErrorKind, ValError, ValResult};
use super::Input;
#[cfg_attr(debug_assertions, derive(Debug))]
pub enum EitherDate<'a> {
Raw(Date),
Py(&'a PyDate),
}
impl<'a> From<Date> for EitherDate<'a> {
fn from(date: Date) -> Self {
Self::Raw(date)
}
}
impl<'a> From<&'a PyDate> for EitherDate<'a> {
fn from(date: &'a PyDate) -> Self {
Self::Py(date)
}
}
macro_rules! pydate_as_date {
($py_date:expr) => {
speedate::Date {
year: $py_date.getattr(pyo3::intern!($py_date.py(), "year"))?.extract()?,
month: $py_date.getattr(pyo3::intern!($py_date.py(), "month"))?.extract()?,
day: $py_date.getattr(pyo3::intern!($py_date.py(), "day"))?.extract()?,
}
};
}
pub(crate) use pydate_as_date;
impl<'a> EitherDate<'a> {
pub fn as_raw(&self) -> PyResult<Date> {
match self {
Self::Raw(date) => Ok(date.clone()),
Self::Py(py_date) => Ok(pydate_as_date!(py_date)),
}
}
pub fn try_into_py(self, py: Python<'_>) -> PyResult<PyObject> {
let date = match self {
Self::Py(date) => Ok(date),
Self::Raw(date) => PyDate::new(py, date.year as i32, date.month, date.day),
}?;
Ok(date.into_py(py))
}
}
#[cfg_attr(debug_assertions, derive(Debug))]
pub enum EitherTime<'a> {
Raw(Time),
Py(&'a PyTime),
}
impl<'a> From<Time> for EitherTime<'a> {
fn from(time: Time) -> Self {
Self::Raw(time)
}
}
impl<'a> From<&'a PyTime> for EitherTime<'a> {
fn from(time: &'a PyTime) -> Self {
Self::Py(time)
}
}
#[cfg_attr(debug_assertions, derive(Debug))]
pub enum EitherTimedelta<'a> {
Raw(Duration),
Py(&'a PyDelta),
}
impl<'a> From<Duration> for EitherTimedelta<'a> {
fn from(timedelta: Duration) -> Self {
Self::Raw(timedelta)
}
}
impl<'a> From<&'a PyDelta> for EitherTimedelta<'a> {
fn from(timedelta: &'a PyDelta) -> Self {
Self::Py(timedelta)
}
}
pub fn pytimedelta_as_timedelta(py_timedelta: &PyDelta) -> Duration {
// see https://docs.python.org/3/c-api/datetime.html#c.PyDateTime_DELTA_GET_DAYS
// days can be negative, but seconds and microseconds are always positive.
let mut days = py_timedelta.get_days(); // -999999999 to 999999999
let mut seconds = py_timedelta.get_seconds(); // 0 through 86399
let mut microseconds = py_timedelta.get_microseconds(); // 0 through 999999
let positive = days >= 0;
if !positive {
// negative timedelta, we need to adjust values to match duration logic
if microseconds != 0 {
seconds += 1;
microseconds = (microseconds - 1_000_000).abs();
}
if seconds != 0 {
days += 1;
seconds = (seconds - 86400).abs();
}
days = days.abs();
}
// we can safely "unwrap" since the methods above guarantee values are in the correct ranges.
Duration::new(positive, days as u32, seconds as u32, microseconds as u32).unwrap()
}
impl<'a> EitherTimedelta<'a> {
pub fn as_raw(&self) -> Duration {
match self {
Self::Raw(timedelta) => timedelta.clone(),
Self::Py(py_timedelta) => pytimedelta_as_timedelta(py_timedelta),
}
}
pub fn try_into_py(self, py: Python<'_>) -> PyResult<PyObject> {
let timedelta = match self {
Self::Py(timedelta) => Ok(timedelta),
Self::Raw(duration) => {
let sign = if duration.positive { 1 } else { -1 };
PyDelta::new(
py,
sign * duration.day as i32,
sign * duration.second as i32,
sign * duration.microsecond as i32,
true,
)
}
}?;
Ok(timedelta.into_py(py))
}
}
macro_rules! pytime_as_time {
($py_time:expr) => {
speedate::Time {
hour: $py_time.getattr(pyo3::intern!($py_time.py(), "hour"))?.extract()?,
minute: $py_time.getattr(pyo3::intern!($py_time.py(), "minute"))?.extract()?,
second: $py_time.getattr(pyo3::intern!($py_time.py(), "second"))?.extract()?,
microsecond: $py_time
.getattr(pyo3::intern!($py_time.py(), "microsecond"))?
.extract()?,
}
};
}
pub(crate) use pytime_as_time;
impl<'a> EitherTime<'a> {
pub fn as_raw(&self) -> PyResult<Time> {
match self {
Self::Raw(time) => Ok(time.clone()),
Self::Py(py_time) => Ok(pytime_as_time!(py_time)),
}
}
pub fn try_into_py(self, py: Python<'_>) -> PyResult<PyObject> {
let time = match self {
Self::Py(time) => Ok(time),
Self::Raw(time) => PyTime::new(py, time.hour, time.minute, time.second, time.microsecond, None),
}?;
Ok(time.into_py(py))
}
}
#[cfg_attr(debug_assertions, derive(Debug))]
pub enum EitherDateTime<'a> {
Raw(DateTime),
Py(&'a PyDateTime),
}
impl<'a> From<DateTime> for EitherDateTime<'a> {
fn from(dt: DateTime) -> Self {
Self::Raw(dt)
}
}
impl<'a> From<&'a PyDateTime> for EitherDateTime<'a> {
fn from(dt: &'a PyDateTime) -> Self {
Self::Py(dt)
}
}
pub fn pydatetime_as_datetime(py_dt: &PyDateTime) -> PyResult<DateTime> {
let py = py_dt.py();
let mut offset: Option<i32> = None;
let tzinfo = py_dt.getattr(intern!(py, "tzinfo"))?;
if !tzinfo.is_none() {
let offset_delta = tzinfo.getattr(intern!(py, "utcoffset"))?.call1((py_dt.as_ref(),))?;
// as per the docs, utcoffset() can return None
if !offset_delta.is_none() {
let offset_seconds: f64 = offset_delta.getattr(intern!(py, "total_seconds"))?.call0()?.extract()?;
offset = Some(offset_seconds.round() as i32);
}
}
Ok(DateTime {
date: pydate_as_date!(py_dt),
time: pytime_as_time!(py_dt),
offset,
})
}
impl<'a> EitherDateTime<'a> {
pub fn as_raw(&self) -> PyResult<DateTime> {
match self {
Self::Raw(dt) => Ok(dt.clone()),
Self::Py(py_dt) => pydatetime_as_datetime(py_dt),
}
}
pub fn try_into_py(self, py: Python<'a>) -> PyResult<PyObject> {
let dt = match self {
Self::Raw(datetime) => {
let tz: Option<PyTzInfo> = match datetime.offset {
Some(offset) => {
let tz_info = TzInfo::new(offset);
Some(tz_info)
}
None => None,
};
PyDateTime::new(
py,
datetime.date.year as i32,
datetime.date.month,
datetime.date.day,
datetime.time.hour,
datetime.time.minute,
datetime.time.second,
datetime.time.microsecond,
tz.as_ref(),
)?
}
Self::Py(dt) => dt,
};
Ok(dt.into_py(py))
}
}
pub fn bytes_as_date<'a>(input: &'a impl Input<'a>, bytes: &[u8]) -> ValResult<'a, EitherDate<'a>> {
match Date::parse_bytes(bytes) {
Ok(date) => Ok(date.into()),
Err(err) => Err(ValError::new(
ErrorKind::DateParsing {
error: err.get_documentation().unwrap_or_default(),
},
input,
)),
}
}
pub fn bytes_as_time<'a>(input: &'a impl Input<'a>, bytes: &[u8]) -> ValResult<'a, EitherTime<'a>> {
match Time::parse_bytes(bytes) {
Ok(date) => Ok(date.into()),
Err(err) => Err(ValError::new(
ErrorKind::TimeParsing {
error: err.get_documentation().unwrap_or_default(),
},
input,
)),
}
}
pub fn bytes_as_datetime<'a, 'b>(input: &'a impl Input<'a>, bytes: &'b [u8]) -> ValResult<'a, EitherDateTime<'a>> {
match DateTime::parse_bytes(bytes) {
Ok(dt) => Ok(dt.into()),
Err(err) => Err(ValError::new(
ErrorKind::DateTimeParsing {
error: err.get_documentation().unwrap_or_default(),
},
input,
)),
}
}
pub fn int_as_datetime<'a>(
input: &'a impl Input<'a>,
timestamp: i64,
timestamp_microseconds: u32,
) -> ValResult<EitherDateTime> {
match DateTime::from_timestamp(timestamp, timestamp_microseconds) {
Ok(dt) => Ok(dt.into()),
Err(err) => Err(ValError::new(
ErrorKind::DateTimeParsing {
error: err.get_documentation().unwrap_or_default(),
},
input,
)),
}
}
pub fn float_as_datetime<'a>(input: &'a impl Input<'a>, timestamp: f64) -> ValResult<EitherDateTime> {
let microseconds = timestamp.fract().abs() * 1_000_000.0;
// checking for extra digits in microseconds is unreliable with large floats,
// so we just round to the nearest microsecond
int_as_datetime(input, timestamp.floor() as i64, microseconds.round() as u32)
}
pub fn date_as_datetime(date: &PyDate) -> PyResult<EitherDateTime> {
let py = date.py();
let dt = PyDateTime::new(
py,
date.getattr(intern!(py, "year"))?.extract()?,
date.getattr(intern!(py, "month"))?.extract()?,
date.getattr(intern!(py, "day"))?.extract()?,
0,
0,
0,
0,
None,
)?;
Ok(dt.into())
}
const MAX_U32: i64 = u32::MAX as i64;
pub fn int_as_time<'a>(
input: &'a impl Input<'a>,
timestamp: i64,
timestamp_microseconds: u32,
) -> ValResult<EitherTime> {
let time_timestamp: u32 = match timestamp {
t if t < 0_i64 => {
return Err(ValError::new(
ErrorKind::TimeParsing {
error: "time in seconds should be positive",
},
input,
));
}
// continue and use the speedate error for >86400
t if t > MAX_U32 => u32::MAX,
// ok
t => t as u32,
};
match Time::from_timestamp(time_timestamp, timestamp_microseconds) {
Ok(dt) => Ok(dt.into()),
Err(err) => Err(ValError::new(
ErrorKind::TimeParsing {
error: err.get_documentation().unwrap_or_default(),
},
input,
)),
}
}
pub fn float_as_time<'a>(input: &'a impl Input<'a>, timestamp: f64) -> ValResult<EitherTime> {
let microseconds = timestamp.fract().abs() * 1_000_000.0;
// round for same reason as above
int_as_time(input, timestamp.floor() as i64, microseconds.round() as u32)
}
pub fn bytes_as_timedelta<'a, 'b>(input: &'a impl Input<'a>, bytes: &'b [u8]) -> ValResult<'a, EitherTimedelta<'a>> {
match Duration::parse_bytes(bytes) {
Ok(dt) => Ok(dt.into()),
Err(err) => Err(ValError::new(
ErrorKind::TimeDeltaParsing {
error: err.get_documentation().unwrap_or_default(),
},
input,
)),
}
}
pub fn int_as_duration(total_seconds: i64) -> Duration {
let positive = total_seconds >= 0;
let total_seconds = total_seconds.unsigned_abs();
// we can safely unwrap here since we've guaranteed seconds and microseconds can't cause overflow
let days = (total_seconds / 86400) as u32;
let seconds = (total_seconds % 86400) as u32;
Duration::new(positive, days, seconds, 0).unwrap()
}
pub fn float_as_duration(total_seconds: f64) -> Duration {
let positive = total_seconds >= 0_f64;
let total_seconds = total_seconds.abs();
let microsecond = total_seconds.fract() * 1_000_000.0;
let days = (total_seconds / 86400f64) as u32;
let seconds = total_seconds as u64 % 86400;
Duration::new(positive, days, seconds as u32, microsecond.round() as u32).unwrap()
}
#[pyclass(module = "pydantic_core._pydantic_core", extends = PyTzInfo)]
#[derive(Clone)]
#[cfg_attr(debug_assertions, derive(Debug))]
struct TzInfo {
seconds: i32,
}
#[pymethods]
impl TzInfo {
#[new]
fn new(seconds: i32) -> Self {
Self { seconds }
}
fn utcoffset<'p>(&self, py: Python<'p>, _dt: &PyDateTime) -> PyResult<&'p PyDelta> {
PyDelta::new(py, 0, self.seconds, 0, true)
}
fn tzname(&self, _dt: &PyDateTime) -> String {
self.__str__()
}
fn dst(&self, _dt: &PyDateTime) -> Option<&PyDelta> {
None
}
fn __repr__(&self) -> String {
format!("TzInfo({})", self.__str__())
}
fn __str__(&self) -> String {
if self.seconds == 0 {
"UTC".to_string()
} else {
let mins = self.seconds / 60;
format!("{:+03}:{:02}", mins / 60, (mins % 60).abs())
}
}
}