forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplexobject.rs
More file actions
52 lines (45 loc) · 1.58 KB
/
Copy pathcomplexobject.rs
File metadata and controls
52 lines (45 loc) · 1.58 KB
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
use crate::object::define_py_check;
use crate::{PyObject, pystate::with_vm};
use core::ffi::c_double;
use num_complex::{Complex, Complex64};
use rustpython_vm::builtins::PyComplex;
use rustpython_vm::{PyResult, VirtualMachine};
define_py_check!(fn PyComplex_Check, types.complex_type);
define_py_check!(exact fn PyComplex_CheckExact, types.complex_type);
#[unsafe(no_mangle)]
pub extern "C" fn PyComplex_FromDoubles(real: c_double, imag: c_double) -> *mut PyObject {
with_vm(|vm| vm.ctx.new_complex(Complex::new(real, imag)))
}
fn try_to_complex(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Complex64> {
obj.try_downcast_ref::<PyComplex>(vm).map_or_else(
|type_err| {
if let Some((complex, _)) = obj.to_owned().try_complex(vm)? {
Ok(complex)
} else {
Err(type_err)
}
},
|complex| Ok(complex.to_complex()),
)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyComplex_RealAsDouble(obj: *mut PyObject) -> c_double {
with_vm(|vm| try_to_complex(vm, unsafe { &*obj }).map(|complex| complex.re))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyComplex_ImagAsDouble(obj: *mut PyObject) -> c_double {
with_vm(|vm| try_to_complex(vm, unsafe { &*obj }).map(|complex| complex.im))
}
#[cfg(false)]
mod tests {
use pyo3::prelude::*;
use pyo3::types::PyComplex;
#[test]
fn test_py_int() {
Python::attach(|py| {
let number = PyComplex::from_doubles(py, 1.0, 2.0);
assert_eq!(number.real(), 1.0);
assert_eq!(number.imag(), 2.0);
})
}
}