From 182b2fc6150b90542371a1824afec691d2f83051 Mon Sep 17 00:00:00 2001 From: Omer Katz Date: Fri, 19 Jul 2019 10:07:22 +0300 Subject: [PATCH] Add empty() to PySet and PyFrozenSet. --- src/types/set.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/types/set.rs b/src/types/set.rs index 43d9b39d..eaa4311c 100644 --- a/src/types/set.rs +++ b/src/types/set.rs @@ -8,6 +8,7 @@ use crate::object::PyObject; use crate::AsPyPointer; use crate::Python; use crate::{ToBorrowedObject, ToPyObject}; +use std::ptr; use std::{collections, hash}; /// Represents a Python `set` @@ -28,6 +29,11 @@ impl PySet { unsafe { py.from_owned_ptr_or_err(ffi::PySet_New(list.as_ptr())) } } + /// Creates a new empty set + pub fn empty<'p>(py: Python<'p>) -> PyResult<&'p PySet> { + unsafe { py.from_owned_ptr_or_err(ffi::PySet_New(ptr::null_mut())) } + } + /// Remove all elements from the set. #[inline] pub fn clear(&self) { @@ -128,6 +134,11 @@ impl PyFrozenSet { unsafe { py.from_owned_ptr_or_err(ffi::PyFrozenSet_New(list.as_ptr())) } } + /// Creates a new empty frozen set + pub fn empty<'p>(py: Python<'p>) -> PyResult<&'p PySet> { + unsafe { py.from_owned_ptr_or_err(ffi::PyFrozenSet_New(ptr::null_mut())) } + } + /// Return the number of items in the set. /// This is equivalent to len(p) on a set. #[inline] @@ -177,6 +188,14 @@ mod test { assert!(PySet::new(py, &[v]).is_err()); } + #[test] + fn test_set_empty() { + let gil = Python::acquire_gil(); + let py = gil.python(); + let set = PySet::empty(py).unwrap(); + assert_eq!(0, set.len()); + } + #[test] fn test_set_len() { let gil = Python::acquire_gil(); @@ -264,6 +283,14 @@ mod test { assert!(PyFrozenSet::new(py, &[v]).is_err()); } + #[test] + fn test_frozenset_empty() { + let gil = Python::acquire_gil(); + let py = gil.python(); + let set = PyFrozenSet::empty(py).unwrap(); + assert_eq!(0, set.len()); + } + #[test] fn test_frozenset_contains() { let gil = Python::acquire_gil();