Debian Codegraph @

rust/src/python/helpers.rs

raw
1 #![allow(clippy::useless_conversion)]
2 use std::cmp::Ordering;
3
4 use pyo3::{
5 prelude::*,
6 types::{PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyString, PyTimeAccess},
7 PyTypeInfo,
8 };
9
10 use crate::{
11 constants::{DAYS_PER_MONTHS, SECS_PER_DAY, SECS_PER_HOUR, SECS_PER_MIN},
12 helpers,
13 };
14
15 use crate::python::types::PreciseDiff;
16
17 struct DateTimeInfo<'py> {
18 pub year: i32,
19 pub month: i32,
20 pub day: i32,
21 pub hour: i32,
22 pub minute: i32,
23 pub second: i32,
24 pub microsecond: i32,
25 pub total_seconds: i32,
26 pub offset: i32,
27 pub tz: &'py str,
28 pub is_datetime: bool,
29 }
30
31 impl PartialEq for DateTimeInfo<'_> {
32 fn eq(&self, other: &Self) -> bool {
33 (
34 self.year,
35 self.month,
36 self.day,
37 self.hour,
38 self.minute,
39 self.second,
40 self.microsecond,
41 )
42 .eq(&(
43 other.year,
44 other.month,
45 other.day,
46 other.hour,
47 other.minute,
48 other.second,
49 other.microsecond,
50 ))
51 }
52 }
53
54 impl PartialOrd for DateTimeInfo<'_> {
55 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
56 (
57 self.year,
58 self.month,
59 self.day,
60 self.hour,
61 self.minute,
62 self.second,
63 self.microsecond,
64 )
65 .partial_cmp(&(
66 other.year,
67 other.month,
68 other.day,
69 other.hour,
70 other.minute,
71 other.second,
72 other.microsecond,
73 ))
74 }
75 }
76
77 pub fn get_tz_name<'py>(dt: &Bound<'py, PyAny>) -> PyResult<String> {
78 // let tz: &str = "";
79
80 if !PyDateTime::is_type_of(dt) {
81 return Ok(String::new());
82 }
83
84 let tzinfo: Bound<'py, PyAny> = dt.getattr("tzinfo")?;
85
86 if tzinfo.is_none() {
87 return Ok(String::new());
88 }
89
90 let tzname_attr: Option<Bound<'py, PyAny>>;
91
92 if tzinfo.hasattr("key")? {
93 tzname_attr = Some(tzinfo.getattr("key")?);
94 } else if tzinfo.hasattr("name")? {
95 tzname_attr = Some(tzinfo.getattr("name")?);
96 } else if tzinfo.hasattr("zone")? {
97 tzname_attr = Some(tzinfo.getattr("zone")?);
98 } else {
99 tzname_attr = None;
100 }
101
102 if let Some(tzname_attr) = tzname_attr {
103 let tzname: &Bound<PyString> = tzname_attr.cast()?;
104 tzname.extract()
105 } else {
106 Ok(String::new())
107 }
108 }
109
110 pub fn get_offset(dt: &Bound<PyAny>) -> PyResult<i32> {
111 if !PyDateTime::is_type_of(dt) {
112 return Ok(0);
113 }
114
115 let tzinfo = dt.getattr("tzinfo")?;
116
117 if tzinfo.is_none() {
118 return Ok(0);
119 }
120 let binding = tzinfo.call_method1("utcoffset", (dt,))?;
121 let offset: &Bound<PyDelta> = binding.cast()?;
122
123 Ok(offset.get_days() * SECS_PER_DAY as i32 + offset.get_seconds())
124 }
125
126 #[pyfunction]
127 pub fn is_leap(year: i32) -> bool {
128 helpers::is_leap(year)
129 }
130
131 #[pyfunction]
132 pub fn is_long_year(year: i32) -> bool {
133 helpers::is_long_year(year)
134 }
135
136 #[pyfunction]
137 pub fn week_day(year: i32, month: u32, day: u32) -> u32 {
138 helpers::week_day(year, month, day)
139 }
140
141 #[pyfunction]
142 pub fn days_in_year(year: i32) -> u32 {
143 helpers::days_in_year(year)
144 }
145
146 #[pyfunction]
147 pub fn local_time(
148 unix_time: f64,
149 utc_offset: isize,
150 microsecond: usize,
151 ) -> (usize, usize, usize, usize, usize, usize, usize) {
152 helpers::local_time(unix_time, utc_offset, microsecond)
153 }
154
155 #[pyfunction]
156 pub fn precise_diff<'py>(
157 dt1: &Bound<'py, PyAny>,
158 dt2: &Bound<'py, PyAny>,
159 ) -> PyResult<PreciseDiff> {
160 let mut sign = 1;
161 let dt1_tz = get_tz_name(dt1)?;
162 let dt2_tz = get_tz_name(dt2)?;
163 let mut dtinfo1 = DateTimeInfo {
164 year: dt1.cast::<PyDate>()?.get_year(),
165 month: i32::from(dt1.cast::<PyDate>()?.get_month()),
166 day: i32::from(dt1.cast::<PyDate>()?.get_day()),
167 hour: 0,
168 minute: 0,
169 second: 0,
170 microsecond: 0,
171 total_seconds: 0,
172 tz: dt1_tz.as_str(),
173 offset: get_offset(dt1)?,
174 is_datetime: PyDateTime::is_type_of(dt1),
175 };
176 let mut dtinfo2 = DateTimeInfo {
177 year: dt2.cast::<PyDate>()?.get_year(),
178 month: i32::from(dt2.cast::<PyDate>()?.get_month()),
179 day: i32::from(dt2.cast::<PyDate>()?.get_day()),
180 hour: 0,
181 minute: 0,
182 second: 0,
183 microsecond: 0,
184 total_seconds: 0,
185 tz: dt2_tz.as_str(),
186 offset: get_offset(dt2)?,
187 is_datetime: PyDateTime::is_exact_type_of(dt2),
188 };
189 let in_same_tz: bool = dtinfo1.tz == dtinfo2.tz && !dtinfo1.tz.is_empty();
190 let mut total_days = helpers::day_number(dtinfo2.year, dtinfo2.month as u8, dtinfo2.day as u8)
191 - helpers::day_number(dtinfo1.year, dtinfo1.month as u8, dtinfo1.day as u8);
192
193 if dtinfo1.is_datetime {
194 let dt1dt: &Bound<PyDateTime> = dt1.cast()?;
195
196 dtinfo1.hour = i32::from(dt1dt.get_hour());
197 dtinfo1.minute = i32::from(dt1dt.get_minute());
198 dtinfo1.second = i32::from(dt1dt.get_second());
199 dtinfo1.microsecond = dt1dt.get_microsecond() as i32;
200
201 if !in_same_tz && dtinfo1.offset != 0 || total_days == 0 {
202 dtinfo1.hour -= dtinfo1.offset / SECS_PER_HOUR as i32;
203 dtinfo1.offset %= SECS_PER_HOUR as i32;
204 dtinfo1.minute -= dtinfo1.offset / SECS_PER_MIN as i32;
205 dtinfo1.offset %= SECS_PER_MIN as i32;
206 dtinfo1.second -= dtinfo1.offset;
207
208 if dtinfo1.second < 0 {
209 dtinfo1.second += 60;
210 dtinfo1.minute -= 1;
211 } else if dtinfo1.second > 60 {
212 dtinfo1.second -= 60;
213 dtinfo1.minute += 1;
214 }
215
216 if dtinfo1.minute < 0 {
217 dtinfo1.minute += 60;
218 dtinfo1.hour -= 1;
219 } else if dtinfo1.minute > 60 {
220 dtinfo1.minute -= 60;
221 dtinfo1.hour += 1;
222 }
223
224 if dtinfo1.hour < 0 {
225 dtinfo1.hour += 24;
226 dtinfo1.day -= 1;
227 } else if dtinfo1.hour > 24 {
228 dtinfo1.hour -= 24;
229 dtinfo1.day += 1;
230 }
231 }
232
233 dtinfo1.total_seconds = dtinfo1.hour * SECS_PER_HOUR as i32
234 + dtinfo1.minute * SECS_PER_MIN as i32
235 + dtinfo1.second;
236 }
237
238 if dtinfo2.is_datetime {
239 let dt2dt: &Bound<PyDateTime> = dt2.cast()?;
240
241 dtinfo2.hour = i32::from(dt2dt.get_hour());
242 dtinfo2.minute = i32::from(dt2dt.get_minute());
243 dtinfo2.second = i32::from(dt2dt.get_second());
244 dtinfo2.microsecond = dt2dt.get_microsecond() as i32;
245
246 if !in_same_tz && dtinfo2.offset != 0 || total_days == 0 {
247 dtinfo2.hour -= dtinfo2.offset / SECS_PER_HOUR as i32;
248 dtinfo2.offset %= SECS_PER_HOUR as i32;
249 dtinfo2.minute -= dtinfo2.offset / SECS_PER_MIN as i32;
250 dtinfo2.offset %= SECS_PER_MIN as i32;
251 dtinfo2.second -= dtinfo2.offset;
252
253 if dtinfo2.second < 0 {
254 dtinfo2.second += 60;
255 dtinfo2.minute -= 1;
256 } else if dtinfo2.second > 60 {
257 dtinfo2.second -= 60;
258 dtinfo2.minute += 1;
259 }
260
261 if dtinfo2.minute < 0 {
262 dtinfo2.minute += 60;
263 dtinfo2.hour -= 1;
264 } else if dtinfo2.minute > 60 {
265 dtinfo2.minute -= 60;
266 dtinfo2.hour += 1;
267 }
268
269 if dtinfo2.hour < 0 {
270 dtinfo2.hour += 24;
271 dtinfo2.day -= 1;
272 } else if dtinfo2.hour > 24 {
273 dtinfo2.hour -= 24;
274 dtinfo2.day += 1;
275 }
276 }
277
278 dtinfo2.total_seconds = dtinfo2.hour * SECS_PER_HOUR as i32
279 + dtinfo2.minute * SECS_PER_MIN as i32
280 + dtinfo2.second;
281 }
282
283 if dtinfo1 > dtinfo2 {
284 sign = -1;
285 (dtinfo1, dtinfo2) = (dtinfo2, dtinfo1);
286
287 total_days = -total_days;
288 }
289
290 let mut year_diff = dtinfo2.year - dtinfo1.year;
291 let mut month_diff = dtinfo2.month - dtinfo1.month;
292 let mut day_diff = dtinfo2.day - dtinfo1.day;
293 let mut hour_diff = dtinfo2.hour - dtinfo1.hour;
294 let mut minute_diff = dtinfo2.minute - dtinfo1.minute;
295 let mut second_diff = dtinfo2.second - dtinfo1.second;
296 let mut microsecond_diff = dtinfo2.microsecond - dtinfo1.microsecond;
297
298 if microsecond_diff < 0 {
299 microsecond_diff += 1_000_000;
300 second_diff -= 1;
301 }
302
303 if second_diff < 0 {
304 second_diff += 60;
305 minute_diff -= 1;
306 }
307
308 if minute_diff < 0 {
309 minute_diff += 60;
310 hour_diff -= 1;
311 }
312
313 if hour_diff < 0 {
314 hour_diff += 24;
315 day_diff -= 1;
316 }
317
318 if day_diff < 0 {
319 // If we have a difference in days,
320 // we have to check if they represent months
321 let mut year = dtinfo2.year;
322 let mut month = dtinfo2.month;
323
324 if month == 1 {
325 month = 12;
326 year -= 1;
327 } else {
328 month -= 1;
329 }
330
331 let leap = helpers::is_leap(year);
332
333 let days_in_last_month = DAYS_PER_MONTHS[usize::from(leap)][month as usize];
334 let days_in_month =
335 DAYS_PER_MONTHS[usize::from(helpers::is_leap(dtinfo2.year))][dtinfo2.month as usize];
336
337 match day_diff.cmp(&(days_in_month - days_in_last_month)) {
338 Ordering::Less => {
339 // We don't have a full month, we calculate days
340 if days_in_last_month < dtinfo1.day {
341 day_diff += dtinfo1.day;
342 } else {
343 day_diff += days_in_last_month;
344 }
345 }
346 Ordering::Equal => {
347 // We have exactly a full month
348 // We remove the days difference
349 // and add one to the months difference
350 day_diff = 0;
351 month_diff += 1;
352 }
353 Ordering::Greater => {
354 // We have a full month
355 day_diff += days_in_last_month;
356 }
357 }
358
359 month_diff -= 1;
360 }
361
362 if month_diff < 0 {
363 month_diff += 12;
364 year_diff -= 1;
365 }
366
367 Ok(PreciseDiff {
368 years: year_diff * sign,
369 months: month_diff * sign,
370 days: day_diff * sign,
371 hours: hour_diff * sign,
372 minutes: minute_diff * sign,
373 seconds: second_diff * sign,
374 microseconds: microsecond_diff * sign,
375 total_days: total_days * sign,
376 })
377 }