diff --git a/newsfragments/3353.added.md b/newsfragments/3353.added.md new file mode 100644 index 00000000000..2db4834e660 --- /dev/null +++ b/newsfragments/3353.added.md @@ -0,0 +1 @@ +Add `PySlice::full()` to construct a full slice (`::`). diff --git a/src/types/slice.rs b/src/types/slice.rs index 2f1e796c9eb..c0bcc5555ce 100644 --- a/src/types/slice.rs +++ b/src/types/slice.rs @@ -54,6 +54,14 @@ impl PySlice { } } + /// Constructs a new full slice that is equivalent to `::`. + pub fn full(py: Python<'_>) -> &PySlice { + unsafe { + let ptr = ffi::PySlice_New(ffi::Py_None(), ffi::Py_None(), ffi::Py_None()); + py.from_owned_ptr(ptr) + } + } + /// Retrieves the start, stop, and step indices from the slice object, /// assuming a sequence of length `length`, and stores the length of the /// slice in its `slicelength` member. @@ -116,6 +124,34 @@ mod tests { }); } + #[test] + fn test_py_slice_full() { + Python::with_gil(|py| { + let slice = PySlice::full(py); + assert!(slice.getattr("start").unwrap().is_none(),); + assert!(slice.getattr("stop").unwrap().is_none(),); + assert!(slice.getattr("step").unwrap().is_none(),); + assert_eq!( + slice.indices(0).unwrap(), + PySliceIndices { + start: 0, + stop: 0, + step: 1, + slicelength: 0, + }, + ); + assert_eq!( + slice.indices(42).unwrap(), + PySliceIndices { + start: 0, + stop: 42, + step: 1, + slicelength: 42, + }, + ); + }); + } + #[test] fn test_py_slice_indices_new() { let start = 0;