Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle exceptions properly in PySet::discard #3281

Merged
merged 1 commit into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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