Implement Python bindings for IndexedQueue
This commit is contained in:
parent
fec9ccffc6
commit
2cb2e97d7b
4 changed files with 104 additions and 15 deletions
|
@ -1,4 +1,7 @@
|
|||
use std::cmp::Ordering;
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
hash::{Hash, Hasher},
|
||||
};
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -50,4 +50,8 @@ impl<D: Hash + Clone + Send + Sync, P: PartialOrd + Clone + Send + Sync> Indexed
|
|||
fn remove(&mut self, data: D) -> bool {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn contains(&self, data: &D) -> bool {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,4 +13,6 @@ pub trait IndexedBacking<D: Clone + Send + Sync, P: PartialOrd + Clone + Send +
|
|||
fn update(&mut self, data: D, priority: P) -> bool;
|
||||
/// Remove an item from the queue
|
||||
fn remove(&mut self, data: D) -> bool;
|
||||
/// Check if an item is already in the queue
|
||||
fn contains(&self, data: &D) -> bool;
|
||||
}
|
||||
|
|
|
@ -1,38 +1,65 @@
|
|||
use pyo3::{
|
||||
exceptions::{PyIndexError, PyStopIteration},
|
||||
exceptions::{PyIndexError, PyKeyError, PyRuntimeError, PyStopIteration, PyTypeError},
|
||||
prelude::*,
|
||||
types::PyType,
|
||||
types::{PyDict, PyType},
|
||||
};
|
||||
|
||||
use crate::backing::indexed::IndexedBacking;
|
||||
use crate::backing::{
|
||||
containers::{Pair, PyItem},
|
||||
indexed::{IndexedBacking, IndexedBinaryHeap},
|
||||
};
|
||||
|
||||
#[pyclass]
|
||||
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]
|
||||
impl IndexedQueue {
|
||||
#[new]
|
||||
#[pyo3(signature = (items=None))]
|
||||
fn new(items: Option<Py<PyAny>>) -> PyResult<Self> {
|
||||
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 {
|
||||
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>) {
|
||||
todo!()
|
||||
fn __setitem__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>, value: f64) -> PyResult<()> {
|
||||
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>) {
|
||||
todo!()
|
||||
fn __delitem__(mut self_: PyRefMut<'_, Self>, key: Py<PyAny>) -> PyResult<()> {
|
||||
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>) {
|
||||
todo!()
|
||||
fn __contains__(self_: PyRef<'_, Self>, key: Py<PyAny>) -> bool {
|
||||
self_.backing.contains(&PyItem::new(key))
|
||||
}
|
||||
|
||||
/// Enables generic typing
|
||||
|
@ -51,7 +78,7 @@ impl IndexedQueue {
|
|||
|
||||
fn __next__(mut self_: PyRefMut<'_, Self>) -> PyResult<Py<PyAny>> {
|
||||
if let Some(item) = self_.backing.pop() {
|
||||
Ok(item.data())
|
||||
Ok(item.data().data())
|
||||
} else {
|
||||
Err(PyErr::new::<PyStopIteration, _>(()))
|
||||
}
|
||||
|
@ -59,9 +86,55 @@ impl IndexedQueue {
|
|||
|
||||
fn pop(mut self_: PyRefMut<'_, Self>) -> PyResult<Py<PyAny>> {
|
||||
if let Some(item) = self_.backing.pop() {
|
||||
Ok(item.data())
|
||||
Ok(item.data().data())
|
||||
} else {
|
||||
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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue