Merge pull request #3281 from davidhewitt/set-discard

handle exceptions properly in `PySet::discard`
This commit is contained in:
Adam Reichold 2023-06-28 17:09:01 +00:00 committed by GitHub
commit afc1d4cc42
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 5 deletions

View File

@ -0,0 +1 @@
Change `PySet::discard` to return `PyResult<bool>` (previously returned nothing).

View File

@ -0,0 +1 @@
Handle exceptions properly in `PySet::discard`.

View File

@ -81,14 +81,24 @@ impl PySet {
}
/// Removes the element from the set if it is present.
pub fn discard<K>(&self, key: K)
///
/// Returns `true` if the element was present in the set.
pub fn discard<K>(&self, key: K) -> PyResult<bool>
where
K: ToPyObject,
{
fn inner(set: &PySet, key: PyObject) -> PyResult<bool> {
unsafe {
ffi::PySet_Discard(self.as_ptr(), key.to_object(self.py()).as_ptr());
match ffi::PySet_Discard(set.as_ptr(), key.as_ptr()) {
1 => Ok(true),
0 => Ok(false),
_ => Err(PyErr::fetch(set.py())),
}
}
}
inner(self, key.to_object(self.py()))
}
/// Adds an element to the set.
pub fn add<K>(&self, key: K) -> PyResult<()>
@ -322,10 +332,14 @@ mod tests {
fn test_set_discard() {
Python::with_gil(|py| {
let set = PySet::new(py, &[1]).unwrap();
set.discard(2);
assert!(!set.discard(2).unwrap());
assert_eq!(1, set.len());
set.discard(1);
assert!(set.discard(1).unwrap());
assert_eq!(0, set.len());
assert!(!set.discard(1).unwrap());
assert!(set.discard(vec![1, 2]).is_err());
});
}