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
#![cfg(feature = "num-rational")]
//! Conversions to and from [num-rational](https://docs.rs/num-rational) types.
//!
//! This is useful for converting between Python's [fractions.Fraction](https://docs.python.org/3/library/fractions.html) into and from a native Rust
//! type.
//!
//!
//! To use this feature, add to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"),  "\", features = [\"num-rational\"] }")]
//! num-rational = "0.4.1"
//! ```
//!
//! # Example
//!
//! Rust code to create a function that adds five to a fraction:
//!
//! ```rust
//! use num_rational::Ratio;
//! use pyo3::prelude::*;
//!
//! #[pyfunction]
//! fn add_five_to_fraction(fraction: Ratio<i32>) -> Ratio<i32> {
//!     fraction + Ratio::new(5, 1)
//! }
//!
//! #[pymodule]
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
//!     m.add_function(wrap_pyfunction!(add_five_to_fraction, m)?)?;
//!     Ok(())
//! }
//! ```
//!
//! Python code that validates the functionality:
//! ```python
//! from my_module import add_five_to_fraction
//! from fractions import Fraction
//!
//! fraction = Fraction(2,1)
//! fraction_plus_five = add_five_to_fraction(f)
//! assert fraction + 5 == fraction_plus_five
//! ```

use crate::conversion::IntoPyObject;
use crate::ffi;
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
use crate::types::PyType;
use crate::{
    Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject,
};

#[cfg(feature = "num-bigint")]
use num_bigint::BigInt;
use num_rational::Ratio;

static FRACTION_CLS: GILOnceCell<Py<PyType>> = GILOnceCell::new();

fn get_fraction_cls(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
    FRACTION_CLS.get_or_try_init_type_ref(py, "fractions", "Fraction")
}

macro_rules! rational_conversion {
    ($int: ty) => {
        impl<'py> FromPyObject<'py> for Ratio<$int> {
            fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
                let py = obj.py();
                let py_numerator_obj = obj.getattr(crate::intern!(py, "numerator"))?;
                let py_denominator_obj = obj.getattr(crate::intern!(py, "denominator"))?;
                let numerator_owned = unsafe {
                    Bound::from_owned_ptr_or_err(py, ffi::PyNumber_Long(py_numerator_obj.as_ptr()))?
                };
                let denominator_owned = unsafe {
                    Bound::from_owned_ptr_or_err(
                        py,
                        ffi::PyNumber_Long(py_denominator_obj.as_ptr()),
                    )?
                };
                let rs_numerator: $int = numerator_owned.extract()?;
                let rs_denominator: $int = denominator_owned.extract()?;
                Ok(Ratio::new(rs_numerator, rs_denominator))
            }
        }

        impl ToPyObject for Ratio<$int> {
            #[inline]
            fn to_object(&self, py: Python<'_>) -> PyObject {
                self.into_pyobject(py).unwrap().into_any().unbind()
            }
        }
        impl IntoPy<PyObject> for Ratio<$int> {
            #[inline]
            fn into_py(self, py: Python<'_>) -> PyObject {
                self.into_pyobject(py).unwrap().into_any().unbind()
            }
        }

        impl<'py> IntoPyObject<'py> for Ratio<$int> {
            type Target = PyAny;
            type Output = Bound<'py, Self::Target>;
            type Error = PyErr;

            #[inline]
            fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
                (&self).into_pyobject(py)
            }
        }

        impl<'py> IntoPyObject<'py> for &Ratio<$int> {
            type Target = PyAny;
            type Output = Bound<'py, Self::Target>;
            type Error = PyErr;

            fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
                get_fraction_cls(py)?.call1((self.numer().clone(), self.denom().clone()))
            }
        }
    };
}
rational_conversion!(i8);
rational_conversion!(i16);
rational_conversion!(i32);
rational_conversion!(isize);
rational_conversion!(i64);
#[cfg(feature = "num-bigint")]
rational_conversion!(BigInt);
#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::dict::PyDictMethods;
    use crate::types::PyDict;

    #[cfg(not(target_arch = "wasm32"))]
    use proptest::prelude::*;
    #[test]
    fn test_negative_fraction() {
        Python::with_gil(|py| {
            let locals = PyDict::new(py);
            py.run(
                ffi::c_str!("import fractions\npy_frac = fractions.Fraction(-0.125)"),
                None,
                Some(&locals),
            )
            .unwrap();
            let py_frac = locals.get_item("py_frac").unwrap().unwrap();
            let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
            let rs_frac = Ratio::new(-1, 8);
            assert_eq!(roundtripped, rs_frac);
        })
    }
    #[test]
    fn test_obj_with_incorrect_atts() {
        Python::with_gil(|py| {
            let locals = PyDict::new(py);
            py.run(
                ffi::c_str!("not_fraction = \"contains_incorrect_atts\""),
                None,
                Some(&locals),
            )
            .unwrap();
            let py_frac = locals.get_item("not_fraction").unwrap().unwrap();
            assert!(py_frac.extract::<Ratio<i32>>().is_err());
        })
    }

    #[test]
    fn test_fraction_with_fraction_type() {
        Python::with_gil(|py| {
            let locals = PyDict::new(py);
            py.run(
                ffi::c_str!(
                    "import fractions\npy_frac = fractions.Fraction(fractions.Fraction(10))"
                ),
                None,
                Some(&locals),
            )
            .unwrap();
            let py_frac = locals.get_item("py_frac").unwrap().unwrap();
            let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
            let rs_frac = Ratio::new(10, 1);
            assert_eq!(roundtripped, rs_frac);
        })
    }

    #[test]
    fn test_fraction_with_decimal() {
        Python::with_gil(|py| {
            let locals = PyDict::new(py);
            py.run(
                ffi::c_str!("import fractions\n\nfrom decimal import Decimal\npy_frac = fractions.Fraction(Decimal(\"1.1\"))"),
                None,
                Some(&locals),
            )
            .unwrap();
            let py_frac = locals.get_item("py_frac").unwrap().unwrap();
            let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
            let rs_frac = Ratio::new(11, 10);
            assert_eq!(roundtripped, rs_frac);
        })
    }

    #[test]
    fn test_fraction_with_num_den() {
        Python::with_gil(|py| {
            let locals = PyDict::new(py);
            py.run(
                ffi::c_str!("import fractions\npy_frac = fractions.Fraction(10,5)"),
                None,
                Some(&locals),
            )
            .unwrap();
            let py_frac = locals.get_item("py_frac").unwrap().unwrap();
            let roundtripped: Ratio<i32> = py_frac.extract().unwrap();
            let rs_frac = Ratio::new(10, 5);
            assert_eq!(roundtripped, rs_frac);
        })
    }

    #[cfg(target_arch = "wasm32")]
    #[test]
    fn test_int_roundtrip() {
        Python::with_gil(|py| {
            let rs_frac = Ratio::new(1, 2);
            let py_frac: PyObject = rs_frac.into_py(py);
            let roundtripped: Ratio<i32> = py_frac.extract(py).unwrap();
            assert_eq!(rs_frac, roundtripped);
            // float conversion
        })
    }

    #[cfg(target_arch = "wasm32")]
    #[test]
    fn test_big_int_roundtrip() {
        Python::with_gil(|py| {
            let rs_frac = Ratio::from_float(5.5).unwrap();
            let py_frac: PyObject = rs_frac.clone().into_py(py);
            let roundtripped: Ratio<BigInt> = py_frac.extract(py).unwrap();
            assert_eq!(rs_frac, roundtripped);
        })
    }

    #[cfg(not(target_arch = "wasm32"))]
    proptest! {
        #[test]
        fn test_int_roundtrip(num in any::<i32>(), den in any::<i32>()) {
            Python::with_gil(|py| {
                let rs_frac = Ratio::new(num, den);
                let py_frac = rs_frac.into_py(py);
                let roundtripped: Ratio<i32> = py_frac.extract(py).unwrap();
                assert_eq!(rs_frac, roundtripped);
            })
        }

        #[test]
        #[cfg(feature = "num-bigint")]
        fn test_big_int_roundtrip(num in any::<f32>()) {
            Python::with_gil(|py| {
                let rs_frac = Ratio::from_float(num).unwrap();
                let py_frac = rs_frac.clone().into_py(py);
                let roundtripped: Ratio<BigInt> = py_frac.extract(py).unwrap();
                assert_eq!(roundtripped, rs_frac);
            })
        }

    }

    #[test]
    fn test_infinity() {
        Python::with_gil(|py| {
            let locals = PyDict::new(py);
            let py_bound = py.run(
                ffi::c_str!("import fractions\npy_frac = fractions.Fraction(\"Infinity\")"),
                None,
                Some(&locals),
            );
            assert!(py_bound.is_err());
        })
    }
}