Skip to content

Commit

Permalink
Implement FromPyObject for HashSet and BTreeSet
Browse files Browse the repository at this point in the history
  • Loading branch information
Árni Dagur committed Mar 30, 2020
1 parent 6bc5207 commit 97aca50
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## Unreleased

### Added
* `FromPyObject` implementations for `HashSet` and `BTreeSet`. [#842](https://github.com/PyO3/pyo3/pull/842)

## [0.9.1]

### Fixed
Expand Down
34 changes: 33 additions & 1 deletion src/types/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
use crate::err::{self, PyErr, PyResult};
use crate::internal_tricks::Unsendable;
use crate::{
ffi, AsPyPointer, PyAny, PyNativeType, PyObject, Python, ToBorrowedObject, ToPyObject,
ffi, AsPyPointer, FromPyObject, PyAny, PyNativeType, PyObject, PyTryFrom, Python,
ToBorrowedObject, ToPyObject,
};
use std::cmp;
use std::collections::{BTreeSet, HashSet};
use std::{collections, hash, ptr};

/// Represents a Python `set`
Expand Down Expand Up @@ -181,6 +184,35 @@ where
}
}

impl<'source, K, S> FromPyObject<'source> for HashSet<K, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
S: hash::BuildHasher + Default,
{
fn extract(ob: &'source PyAny) -> Result<Self, PyErr> {
let set = <PySet as PyTryFrom>::try_from(ob)?;
let mut ret = HashSet::default();
for k in set.iter() {
ret.insert(K::extract(k)?);
}
Ok(ret)
}
}

impl<'source, K> FromPyObject<'source> for BTreeSet<K>
where
K: FromPyObject<'source> + cmp::Ord,
{
fn extract(ob: &'source PyAny) -> Result<Self, PyErr> {
let set = <PySet as PyTryFrom>::try_from(ob)?;
let mut ret = BTreeSet::default();
for k in set.iter() {
ret.insert(K::extract(k)?);
}
Ok(ret)
}
}

impl PyFrozenSet {
/// Creates a new frozenset.
///
Expand Down

0 comments on commit 97aca50

Please sign in to comment.