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 d5c6ab4
Showing 1 changed file with 33 additions and 1 deletion.
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 d5c6ab4

Please sign in to comment.