Skip to content

Commit

Permalink
Merge pull request #3281 from davidhewitt/set-discard
Browse files Browse the repository at this point in the history
handle exceptions properly in `PySet::discard`
  • Loading branch information
adamreichold authored Jun 28, 2023
2 parents 1d56cfe + c0b9502 commit afc1d4c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
1 change: 1 addition & 0 deletions newsfragments/3281.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Change `PySet::discard` to return `PyResult<bool>` (previously returned nothing).
1 change: 1 addition & 0 deletions newsfragments/3281.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Handle exceptions properly in `PySet::discard`.
24 changes: 19 additions & 5 deletions src/types/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,23 @@ 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,
{
unsafe {
ffi::PySet_Discard(self.as_ptr(), key.to_object(self.py()).as_ptr());
fn inner(set: &PySet, key: PyObject) -> PyResult<bool> {
unsafe {
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.
Expand Down Expand Up @@ -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());
});
}

Expand Down

0 comments on commit afc1d4c

Please sign in to comment.