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