Implement Python bindings for IndexedQueue

This commit is contained in:
Michael Bradley 2025-01-12 21:01:11 +13:00
parent fec9ccffc6
commit 2cb2e97d7b
Signed by: MichaelBradley
SSH key fingerprint: SHA256:cj/YZ5VT+QOKncqSkx+ibKTIn0Obg7OIzwzl9BL8EO8
4 changed files with 104 additions and 15 deletions

View file

@ -1,4 +1,7 @@
use std::cmp::Ordering; use std::{
cmp::Ordering,
hash::{Hash, Hasher},
};
use pyo3::prelude::*; use pyo3::prelude::*;
@ -44,3 +47,10 @@ impl PartialEq for PyItem {
Python::with_gil(|py| self.0.bind(py).eq(other.0.bind(py)).unwrap_or(false)) Python::with_gil(|py| self.0.bind(py).eq(other.0.bind(py)).unwrap_or(false))
} }
} }
impl Hash for PyItem {
fn hash<H: Hasher>(&self, state: &mut H) {
// TODO: Should warn or fail instead of defaulting to 0
Python::with_gil(|py| self.0.bind(py).hash().unwrap_or(0).hash(state))
}
}

View file

@ -50,4 +50,8 @@ impl<D: Hash + Clone + Send + Sync, P: PartialOrd + Clone + Send + Sync> Indexed
fn remove(&mut self, data: D) -> bool { fn remove(&mut self, data: D) -> bool {
todo!() todo!()
} }
fn contains(&self, data: &D) -> bool {
todo!()
}
} }

View file

@ -13,4 +13,6 @@ pub trait IndexedBacking<D: Clone + Send + Sync, P: PartialOrd + Clone + Send +
fn update(&mut self, data: D, priority: P) -> bool; fn update(&mut self, data: D, priority: P) -> bool;
/// Remove an item from the queue /// Remove an item from the queue
fn remove(&mut self, data: D) -> bool; fn remove(&mut self, data: D) -> bool;
/// Check if an item is already in the queue
fn contains(&self, data: &D) -> bool;
} }

View file

@ -1,38 +1,65 @@
use pyo3::{ use pyo3::{
exceptions::{PyIndexError, PyStopIteration}, exceptions::{PyIndexError, PyKeyError, PyRuntimeError, PyStopIteration, PyTypeError},
prelude::*, prelude::*,
types::PyType, types::{PyDict, PyType},
}; };
use crate::backing::indexed::IndexedBacking; use crate::backing::{
containers::{Pair, PyItem},
indexed::{IndexedBacking, IndexedBinaryHeap},
};
#[pyclass] #[pyclass]
pub struct IndexedQueue { pub struct IndexedQueue {
backing: Box<dyn IndexedBacking<Py<PyAny>, f64>>, backing: Box<dyn IndexedBacking<PyItem, f64>>,
} }
// TODO: Too much of this is just too similar to the other queues
// Normally I'd solve this with inheritance, but I'm not so familiar with rust trait default implementations yet
// In my limited understanding they don't seem to play nice with the Pyo3 bindings
#[pymethods] #[pymethods]
impl IndexedQueue { impl IndexedQueue {
#[new] #[new]
#[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 {
todo!() Python::with_gil(|py| Self::from_any(py_object.bind(py))).and_then(|vec| {
Ok(Self {
backing: Box::new(IndexedBinaryHeap::from_iter(vec)),
})
})
} else { } else {
todo!() // TBD: Determine best way to make Python object hashable from Rust Ok(Self {
backing: Box::new(IndexedBinaryHeap::new()),
})
} }
} }
fn __setitem__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>, value: Py<PyAny>) { fn __setitem__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>, value: f64) -> PyResult<()> {
todo!() let data = PyItem::new(key);
if self_.backing.contains(&data) {
if self_.backing.update(data, value) {
Ok(())
} else {
Err(PyErr::new::<PyRuntimeError, _>("Key could not be updated"))
}
} else {
Ok(self_.backing.add(Pair::new(data, value)))
}
} }
fn __delitem__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>) { fn __delitem__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>) -> PyResult<()> {
todo!() if self_.backing.remove(PyItem::new(key)) {
Ok(())
} else {
Err(PyErr::new::<PyKeyError, _>(
"Key was not contained in queue",
))
}
} }
fn __contains__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>) { fn __contains__(self_: PyRef<'_, Self>, key: Py<PyAny>) -> bool {
todo!() self_.backing.contains(&PyItem::new(key))
} }
/// Enables generic typing /// Enables generic typing
@ -51,7 +78,7 @@ impl IndexedQueue {
fn __next__(mut self_: PyRefMut<'_, Self>) -> PyResult<Py<PyAny>> { fn __next__(mut self_: PyRefMut<'_, Self>) -> PyResult<Py<PyAny>> {
if let Some(item) = self_.backing.pop() { if let Some(item) = self_.backing.pop() {
Ok(item.data()) Ok(item.data().data())
} else { } else {
Err(PyErr::new::<PyStopIteration, _>(())) Err(PyErr::new::<PyStopIteration, _>(()))
} }
@ -59,9 +86,55 @@ impl IndexedQueue {
fn pop(mut self_: PyRefMut<'_, Self>) -> PyResult<Py<PyAny>> { fn pop(mut self_: PyRefMut<'_, Self>) -> PyResult<Py<PyAny>> {
if let Some(item) = self_.backing.pop() { if let Some(item) = self_.backing.pop() {
Ok(item.data()) Ok(item.data().data())
} else { } else {
Err(PyErr::new::<PyIndexError, _>(())) Err(PyErr::new::<PyIndexError, _>(()))
} }
} }
} }
impl<'py> IndexedQueue {
/// Tries to a Python object into a vector suitable for ingestion into the backing
fn from_any(object: &Bound<'py, PyAny>) -> PyResult<Vec<Pair<PyItem, f64>>> {
if let Ok(vec) = object.extract::<Vec<(Py<PyAny>, f64)>>() {
Ok(Self::from_vec(vec))
} else {
if object.is_instance_of::<PyDict>() {
if let Ok(dict) = object.downcast::<PyDict>() {
Self::from_dict(dict)
} else {
Err(PyErr::new::<PyTypeError, _>(
"Argument claimed to be a dict but wasn't",
))
}
} else {
Err(PyErr::new::<PyTypeError, _>(
"Argument was not a properly-formed dict, list, or tuple",
))
}
}
}
/// Converts a vector of Python objects and priorities into a vector of items
fn from_vec(list: Vec<(Py<PyAny>, f64)>) -> Vec<Pair<PyItem, f64>> {
list.into_iter()
.map(|(data, priority)| Pair::new(PyItem::new(data), priority))
.collect()
}
/// Converts a Python dictionary into a vector of items
fn from_dict(dict: &Bound<'py, PyDict>) -> PyResult<Vec<Pair<PyItem, f64>>> {
if let Ok(items) = dict
.into_iter()
.map(|(data, priority)| match priority.extract::<f64>() {
Ok(value) => Ok(Pair::new(PyItem::new(data.unbind()), value)),
Err(err) => Err(err),
})
.collect::<Result<Vec<_>, _>>()
{
Ok(items)
} else {
Err(PyErr::new::<PyTypeError, _>("Dict keys were not numbers"))
}
}
}