Add PyItem container
Also reduce queue item trait bound from Ord to just PartialOrd
This commit is contained in:
parent
ee004bac19
commit
38a544db76
8 changed files with 91 additions and 32 deletions
|
@ -1,3 +1,5 @@
|
|||
mod pair;
|
||||
mod py_item;
|
||||
|
||||
pub use pair::Pair;
|
||||
pub use py_item::PyItem;
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
use std::cmp::Ordering;
|
||||
|
||||
/// Helper struct to associate an item with its priority
|
||||
/// Container to associate an item with a priority
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
// I mean I guess P should be Ord but I want to use f64 so whatever
|
||||
pub struct Pair<D: Clone, P: PartialOrd + Clone> {
|
||||
data: D,
|
||||
priority: P,
|
||||
|
@ -14,23 +13,13 @@ impl<D: Clone, P: PartialOrd + Clone> Pair<D, P> {
|
|||
Self { data, priority }
|
||||
}
|
||||
|
||||
/// Retrieve the internal data, it would be nicer to implement this using [`From`] or [`Into`], but I don't see a way to do that using generics
|
||||
/// Retrieves the internal data.
|
||||
/// It would be nicer to implement this using [`From`] or [`Into`], but I don't see a way to do that using generics.
|
||||
pub fn data(self) -> D {
|
||||
self.data
|
||||
}
|
||||
}
|
||||
|
||||
// The relevant Ord implementations are based just on the priority
|
||||
impl<D: Clone, P: PartialOrd + Clone> Ord for Pair<D, P> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
// Yeah this is bad design
|
||||
// My excuse is that i'm still learning Rust
|
||||
self.priority
|
||||
.partial_cmp(&other.priority)
|
||||
.unwrap_or(Ordering::Equal)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D: Clone, P: PartialOrd + Clone> PartialOrd for Pair<D, P> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
self.priority.partial_cmp(&other.priority)
|
||||
|
@ -42,5 +31,3 @@ impl<D: Clone, P: PartialOrd + Clone> PartialEq for Pair<D, P> {
|
|||
self.priority == other.priority
|
||||
}
|
||||
}
|
||||
|
||||
impl<D: Clone, P: PartialOrd + Clone> Eq for Pair<D, P> {}
|
||||
|
|
46
src/backing/containers/py_item.rs
Normal file
46
src/backing/containers/py_item.rs
Normal file
|
@ -0,0 +1,46 @@
|
|||
use std::cmp::Ordering;
|
||||
|
||||
use pyo3::prelude::*;
|
||||
|
||||
/// Container that provides PartialOrd based on the Python object it holds
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PyItem(Py<PyAny>);
|
||||
|
||||
impl PyItem {
|
||||
/// Creates a new instance
|
||||
fn new(item: Py<PyAny>) -> Self {
|
||||
PyItem(item)
|
||||
}
|
||||
|
||||
/// Retrieves the internal data
|
||||
fn item(self) -> Py<PyAny> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for PyItem {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Python::with_gil(|py| {
|
||||
// Bind objects for convenience
|
||||
let ours = self.0.bind(py);
|
||||
let theirs = other.0.bind(py);
|
||||
|
||||
// Compare based on Python comparison implementations
|
||||
match ours.lt(theirs) {
|
||||
Ok(true) => Some(Ordering::Less),
|
||||
Ok(false) => match ours.gt(theirs) {
|
||||
Ok(true) => Some(Ordering::Greater),
|
||||
Ok(false) => Some(Ordering::Equal), // If the python class is implemented strangely then this may be wrong
|
||||
Err(_) => None,
|
||||
},
|
||||
Err(_) => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for PyItem {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Python::with_gil(|py| self.0.bind(py).eq(other.0.bind(py)).unwrap_or(false))
|
||||
}
|
||||
}
|
|
@ -2,7 +2,7 @@
|
|||
use super::{containers::Pair, pure::PureBacking};
|
||||
|
||||
/// A data structure usable for backing an "indexed" queue
|
||||
pub trait IndexedBacking<D: Clone + Send + Sync, P: Ord + Clone + Send + Sync>:
|
||||
pub trait IndexedBacking<D: Clone + Send + Sync, P: PartialOrd + Clone + Send + Sync>:
|
||||
PureBacking<Pair<D, P>>
|
||||
{
|
||||
/// Update an item's priority
|
||||
|
|
|
@ -2,12 +2,6 @@ use std::fmt;
|
|||
|
||||
use super::PureBacking;
|
||||
|
||||
/// A binary min-heap backed by an array
|
||||
#[derive(Debug)]
|
||||
pub struct BinaryHeap<T: Ord + Clone + Send + Sync> {
|
||||
data: Vec<T>,
|
||||
}
|
||||
|
||||
/// Indicates why a sift failed
|
||||
#[derive(Debug, Clone)]
|
||||
struct SiftError {
|
||||
|
@ -33,7 +27,13 @@ impl fmt::Display for SiftError {
|
|||
/// Whether a sift operation succeeded
|
||||
type SiftResult = Result<(), SiftError>;
|
||||
|
||||
impl<T: Ord + Clone + Send + Sync> BinaryHeap<T> {
|
||||
/// A binary min-heap backed by an array
|
||||
#[derive(Debug)]
|
||||
pub struct BinaryHeap<T: PartialOrd + Clone + Send + Sync> {
|
||||
data: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T: PartialOrd + Clone + Send + Sync> BinaryHeap<T> {
|
||||
/// Instantiates a new (empty) binary heap
|
||||
pub fn new() -> Self {
|
||||
Self { data: vec![] }
|
||||
|
@ -108,7 +108,7 @@ impl<T: Ord + Clone + Send + Sync> BinaryHeap<T> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<T: Ord + Clone + Send + Sync> FromIterator<T> for BinaryHeap<T> {
|
||||
impl<T: PartialOrd + Clone + Send + Sync> FromIterator<T> for BinaryHeap<T> {
|
||||
fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Self {
|
||||
let mut this = Self {
|
||||
data: Vec::from_iter(iter),
|
||||
|
@ -120,7 +120,7 @@ impl<T: Ord + Clone + Send + Sync> FromIterator<T> for BinaryHeap<T> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<T: Ord + Clone + Send + Sync> PureBacking<T> for BinaryHeap<T> {
|
||||
impl<T: PartialOrd + Clone + Send + Sync> PureBacking<T> for BinaryHeap<T> {
|
||||
fn add(&mut self, item: T) {
|
||||
// Append item
|
||||
self.data.push(item);
|
||||
|
|
|
@ -3,7 +3,7 @@ mod binary_heap;
|
|||
pub use binary_heap::BinaryHeap;
|
||||
|
||||
/// A data structure usable for backing a "pure" queue
|
||||
pub trait PureBacking<T: Ord + Send + Sync>: Send + Sync {
|
||||
pub trait PureBacking<T: PartialOrd + Send + Sync>: Send + Sync {
|
||||
/// Places an item into the queue
|
||||
fn add(&mut self, item: T);
|
||||
/// Removes the item with minimum priority, if it exists
|
||||
|
|
|
@ -16,6 +16,7 @@ pub struct PairedQueue {
|
|||
|
||||
#[pymethods]
|
||||
impl PairedQueue {
|
||||
/// Enables generic typing
|
||||
#[classmethod]
|
||||
fn __class_getitem__(cls_: Bound<'_, PyType>, _key: Py<PyAny>) -> Bound<'_, PyType> {
|
||||
cls_
|
||||
|
@ -67,6 +68,7 @@ impl PairedQueue {
|
|||
}
|
||||
|
||||
impl<'py> PairedQueue {
|
||||
/// Tries to a Python object into a vector suitable for ingestion into the backing
|
||||
fn from_any(object: &Bound<'py, PyAny>) -> PyResult<Vec<Pair<Py<PyAny>, f64>>> {
|
||||
if let Ok(vec) = object.extract::<Vec<(Py<PyAny>, f64)>>() {
|
||||
Ok(Self::from_vec(vec))
|
||||
|
@ -87,12 +89,14 @@ impl<'py> PairedQueue {
|
|||
}
|
||||
}
|
||||
|
||||
/// Converts a vector of Python objects and priorities into a vector of items
|
||||
fn from_vec(list: Vec<(Py<PyAny>, f64)>) -> Vec<Pair<Py<PyAny>, f64>> {
|
||||
list.into_iter()
|
||||
.map(|(data, priority)| Pair::new(data, priority))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Converts a Python dictionary into a vector of items
|
||||
fn from_dict(dict: &Bound<'py, PyDict>) -> PyResult<Vec<Pair<Py<PyAny>, f64>>> {
|
||||
if let Ok(items) = dict
|
||||
.into_iter()
|
||||
|
@ -104,7 +108,7 @@ impl<'py> PairedQueue {
|
|||
{
|
||||
Ok(items)
|
||||
} else {
|
||||
Err(PyErr::new::<PyTypeError, _>("Dict keys were not floats"))
|
||||
Err(PyErr::new::<PyTypeError, _>("Dict keys were not numbers"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,12 +1,32 @@
|
|||
use pyo3::prelude::*;
|
||||
use pyo3::{prelude::*, types::PyType};
|
||||
|
||||
use crate::backing::{
|
||||
containers::PyItem,
|
||||
pure::{BinaryHeap, PureBacking},
|
||||
};
|
||||
|
||||
#[pyclass]
|
||||
pub struct PureQueue {}
|
||||
pub struct PureQueue {
|
||||
backing: Box<dyn PureBacking<PyItem>>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PureQueue {
|
||||
/// Enables generic typing
|
||||
#[classmethod]
|
||||
fn __class_getitem__(cls_: Bound<'_, PyType>, _key: Py<PyAny>) -> Bound<'_, PyType> {
|
||||
cls_
|
||||
}
|
||||
|
||||
#[new]
|
||||
fn new() -> Self {
|
||||
Self {}
|
||||
#[pyo3(signature = (items=None))]
|
||||
fn new(items: Option<Py<PyAny>>) -> PyResult<Self> {
|
||||
if let Some(py_object) = items {
|
||||
todo!()
|
||||
} else {
|
||||
Ok(Self {
|
||||
backing: Box::new(BinaryHeap::new()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue