Debian Codegraph @

rust/src/python/parsing.rs

raw
1 #![allow(clippy::useless_conversion)]
2 use pyo3::exceptions;
3 use pyo3::prelude::*;
4 use pyo3::types::PyDate;
5 use pyo3::types::PyDateTime;
6 use pyo3::types::PyTime;
7 use pyo3::IntoPyObjectExt;
8
9 use crate::parsing::Parser;
10 use crate::python::types::{Duration, FixedTimezone};
11
12 #[pyfunction]
13 pub fn parse_iso8601(py: Python, input: &str) -> PyResult<Py<PyAny>> {
14 let parsed = Parser::new(input).parse();
15
16 match parsed {
17 Ok(parsed) => match (parsed.datetime, parsed.duration, parsed.second_datetime) {
18 (Some(datetime), None, None) => match (datetime.has_date, datetime.has_time) {
19 (true, true) => match datetime.offset {
20 Some(offset) => {
21 let dt = PyDateTime::new(
22 py,
23 datetime.year as i32,
24 datetime.month as u8,
25 datetime.day as u8,
26 datetime.hour as u8,
27 datetime.minute as u8,
28 datetime.second as u8,
29 datetime.microsecond,
30 Some(
31 Py::new(py, FixedTimezone::new(offset, datetime.tzname))?
32 .into_any()
33 .cast_bound(py)?,
34 ),
35 )?;
36
37 Ok(dt.into_any().unbind())
38 }
39 None => {
40 let dt = PyDateTime::new(
41 py,
42 datetime.year as i32,
43 datetime.month as u8,
44 datetime.day as u8,
45 datetime.hour as u8,
46 datetime.minute as u8,
47 datetime.second as u8,
48 datetime.microsecond,
49 None,
50 )?;
51
52 Ok(dt.into_any().unbind())
53 }
54 },
55 (true, false) => {
56 let dt = PyDate::new(
57 py,
58 datetime.year as i32,
59 datetime.month as u8,
60 datetime.day as u8,
61 )?;
62
63 Ok(dt.into_any().unbind())
64 }
65 (false, true) => match datetime.offset {
66 Some(offset) => {
67 let dt = PyTime::new(
68 py,
69 datetime.hour as u8,
70 datetime.minute as u8,
71 datetime.second as u8,
72 datetime.microsecond,
73 Some(
74 Py::new(py, FixedTimezone::new(offset, datetime.tzname))?
75 .into_any()
76 .cast_bound(py)?,
77 ),
78 )?;
79
80 Ok(dt.into_any().unbind())
81 }
82 None => {
83 let dt = PyTime::new(
84 py,
85 datetime.hour as u8,
86 datetime.minute as u8,
87 datetime.second as u8,
88 datetime.microsecond,
89 None,
90 )?;
91
92 Ok(dt.into_any().unbind())
93 }
94 },
95 (_, _) => Err(exceptions::PyValueError::new_err(
96 "Parsing error".to_string(),
97 )),
98 },
99 (None, Some(duration), None) => Ok(Py::new(
100 py,
101 Duration::new(
102 Some(duration.years),
103 Some(duration.months),
104 Some(duration.weeks),
105 Some(duration.days),
106 Some(duration.hours),
107 Some(duration.minutes),
108 Some(duration.seconds),
109 Some(duration.microseconds),
110 ),
111 )?
112 .into_py_any(py)?),
113 (_, _, _) => Err(exceptions::PyValueError::new_err(
114 "Not yet implemented".to_string(),
115 )),
116 },
117 Err(error) => Err(exceptions::PyValueError::new_err(error.to_string())),
118 }
119 }