rateslib/scheduling/py/
rollday.rs1use crate::json::{DeserializedObj, JSON};
2use crate::scheduling::RollDay;
3use pyo3::exceptions::PyValueError;
4use pyo3::prelude::*;
5use pyo3::types::PyTuple;
6
7enum RollDayNewArgs {
8 U32(u32),
9 NoArgs(),
10}
11
12impl<'py> IntoPyObject<'py> for RollDayNewArgs {
13 type Target = PyTuple;
14 type Output = Bound<'py, Self::Target>;
15 type Error = std::convert::Infallible;
16
17 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
18 match self {
19 RollDayNewArgs::U32(a) => Ok((a,).into_pyobject(py).unwrap()),
20 RollDayNewArgs::NoArgs() => Ok(PyTuple::empty(py)),
21 }
22 }
23}
24
25impl<'py> FromPyObject<'py> for RollDayNewArgs {
26 fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
27 let ext: PyResult<(u32,)> = ob.extract();
28 match ext {
29 Ok(v) => Ok(RollDayNewArgs::U32(v.0)),
30 Err(_) => Ok(RollDayNewArgs::NoArgs()),
31 }
32 }
33}
34
35#[pymethods]
36impl RollDay {
37 pub(crate) fn __str__(&self) -> String {
38 match self {
39 RollDay::Day(n) => format!("{n}"),
40 RollDay::IMM() => "IMM".to_string(),
41 }
42 }
43
44 fn __getnewargs__(&self) -> RollDayNewArgs {
45 match self {
46 RollDay::Day(n) => RollDayNewArgs::U32(*n),
47 RollDay::IMM() => RollDayNewArgs::NoArgs(),
48 }
49 }
50
51 #[new]
52 fn new_py(args: RollDayNewArgs) -> RollDay {
53 match args {
54 RollDayNewArgs::U32(n) => RollDay::Day(n),
55 RollDayNewArgs::NoArgs() => RollDay::IMM(),
56 }
57 }
58
59 #[pyo3(name = "to_json")]
65 fn to_json_py(&self) -> PyResult<String> {
66 match DeserializedObj::RollDay(self.clone()).to_json() {
67 Ok(v) => Ok(v),
68 Err(_) => Err(PyValueError::new_err(
69 "Failed to serialize `RollDay` to JSON.",
70 )),
71 }
72 }
73
74 fn __repr__(&self) -> String {
75 format!("<rl.RollDay.{:?} at {:p}>", self, self)
76 }
77}