Refactor PairedQueue so that reference to data structure type is just in new

This commit is contained in:
Michael Bradley 2025-01-10 19:51:07 +13:00
parent 1a10720a06
commit e424dd42f5
Signed by: MichaelBradley
SSH key fingerprint: SHA256:cj/YZ5VT+QOKncqSkx+ibKTIn0Obg7OIzwzl9BL8EO8

View file

@ -25,7 +25,11 @@ impl PairedQueue {
#[pyo3(signature = (items=None))]
fn new(items: Option<Py<PyAny>>) -> PyResult<Self> {
if let Some(py_object) = items {
Python::with_gil(|py| Self::new_from_any(py_object.bind(py)))
Python::with_gil(|py| Self::from_any(py_object.bind(py))).and_then(|vec| {
Ok(Self {
backing: Box::new(BinaryHeap::from_iter(vec)),
})
})
} else {
Ok(Self {
backing: Box::new(BinaryHeap::new()),
@ -63,13 +67,13 @@ impl PairedQueue {
}
impl<'py> PairedQueue {
fn new_from_any(object: &Bound<'py, PyAny>) -> PyResult<Self> {
fn from_any(object: &Bound<'py, PyAny>) -> PyResult<Vec<Item<Py<PyAny>, f64>>> {
if let Ok(vec) = object.extract::<Vec<(Py<PyAny>, f64)>>() {
Ok(Self::new_from_vec(vec))
Ok(Self::from_vec(vec))
} else {
if object.is_instance_of::<PyDict>() {
if let Ok(dict) = object.downcast::<PyDict>() {
Self::new_from_map(dict)
Self::from_dict(dict)
} else {
Err(PyErr::new::<PyTypeError, _>(
"Argument claimed to be a dict but wasn't",
@ -83,16 +87,13 @@ impl<'py> PairedQueue {
}
}
fn new_from_vec(list: Vec<(Py<PyAny>, f64)>) -> Self {
Self {
backing: Box::new(BinaryHeap::from_iter(
list.into_iter()
.map(|(data, priority)| Item::new(data, priority)),
)),
}
fn from_vec(list: Vec<(Py<PyAny>, f64)>) -> Vec<Item<Py<PyAny>, f64>> {
list.into_iter()
.map(|(data, priority)| Item::new(data, priority))
.collect()
}
fn new_from_map(dict: &Bound<'py, PyDict>) -> PyResult<Self> {
fn from_dict(dict: &Bound<'py, PyDict>) -> PyResult<Vec<Item<Py<PyAny>, f64>>> {
if let Ok(items) = dict
.into_iter()
.map(|(data, priority)| match priority.extract::<f64>() {
@ -101,9 +102,7 @@ impl<'py> PairedQueue {
})
.collect::<Result<Vec<_>, _>>()
{
Ok(Self {
backing: Box::new(BinaryHeap::from_iter(items)),
})
Ok(items)
} else {
Err(PyErr::new::<PyTypeError, _>("Dict keys were not floats"))
}