Skip to content

Commit

Permalink
Implement Queue.__hash__.
Browse files Browse the repository at this point in the history
Refs: #50
  • Loading branch information
Julian committed Jan 26, 2024
1 parent ee1bf7e commit 783e3ef
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use pyo3::exceptions::PyIndexError;
Expand Down Expand Up @@ -1129,6 +1130,16 @@ impl QueuePy {
.all(|r| r.unwrap_or(false))
}

fn __hash__(&self, py: Python<'_>) -> PyResult<u64> {
let hash = PyModule::import(py, "builtins")?.getattr("hash")?;
let mut hasher = DefaultHasher::new();
for each in &self.inner {
let n: i64 = hash.call1((each.into_py(py),))?.extract()?;
hasher.write_i64(n);
}
Ok(hasher.finish())
}

fn __ne__(&self, other: &Self, py: Python<'_>) -> bool {
(self.inner.len() != other.inner.len())
|| self
Expand Down
18 changes: 12 additions & 6 deletions tests/test_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,6 @@ def test_repr():
assert str(Queue([1, 2, 3])) in "Queue([1, 2, 3])"


@pytest.mark.xfail(reason=HASH_MSG)
def test_hashing():
assert hash(Queue([1, 2])) == hash(Queue([1, 2]))
assert hash(Queue([1, 2])) != hash(Queue([2, 1]))


def test_sequence():
m = Queue("asdf")
assert m == Queue(["a", "s", "d", "f"])
Expand Down Expand Up @@ -131,3 +125,15 @@ def test_more_eq():
assert not (Queue([o, o]) != Queue([o, o]))
assert not (Queue([o]) != Queue([o]))
assert not (Queue() != Queue([]))


def test_hashing():
assert hash(Queue([1, 2])) == hash(Queue([1, 2]))
assert hash(Queue([1, 2])) != hash(Queue([2, 1]))
assert len({Queue([1, 2]), Queue([1, 2])}) == 1


def test_unhashable_contents():
q = Queue([1, {1}])
with pytest.raises(TypeError):
hash(q)

0 comments on commit 783e3ef

Please sign in to comment.