Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/capi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ license.workspace = true
crate-type = ["cdylib", "rlib"]

[dependencies]
num-complex = { workspace = true }
rustpython-vm = { workspace = true, features = ["threading", "compiler"] }
rustpython-stdlib = {workspace = true, features = ["threading"] }

Expand Down
52 changes: 52 additions & 0 deletions crates/capi/src/complexobject.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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);
})
}
}
1 change: 1 addition & 0 deletions crates/capi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod abstract_;
pub mod boolobject;
pub mod bytesobject;
pub mod ceval;
pub mod complexobject;
pub mod dictobject;
pub mod import;
pub mod longobject;
Expand Down
Loading