1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use crate::err::{PyErr, PyResult};
use crate::ffi;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::types::any::PyAnyMethods;
use crate::{Bound, PyAny, PyNativeType, PyObject, Python, ToPyObject};

/// Represents a Python `slice`.
///
/// Only `isize` indices supported at the moment by the `PySlice` object.
#[repr(transparent)]
pub struct PySlice(PyAny);

pyobject_native_type!(
    PySlice,
    ffi::PySliceObject,
    pyobject_native_static_type_object!(ffi::PySlice_Type),
    #checkfunction=ffi::PySlice_Check
);

/// Return value from [`PySlice::indices`].
#[derive(Debug, Eq, PartialEq)]
pub struct PySliceIndices {
    /// Start of the slice
    ///
    /// It can be -1 when the step is negative, otherwise it's non-negative.
    pub start: isize,
    /// End of the slice
    ///
    /// It can be -1 when the step is negative, otherwise it's non-negative.
    pub stop: isize,
    /// Increment to use when iterating the slice from `start` to `stop`.
    pub step: isize,
    /// The length of the slice calculated from the original input sequence.
    pub slicelength: usize,
}

impl PySliceIndices {
    /// Creates a new `PySliceIndices`.
    pub fn new(start: isize, stop: isize, step: isize) -> PySliceIndices {
        PySliceIndices {
            start,
            stop,
            step,
            slicelength: 0,
        }
    }
}

impl PySlice {
    /// Deprecated form of `PySlice::new_bound`.
    #[cfg_attr(
        not(feature = "gil-refs"),
        deprecated(
            since = "0.21.0",
            note = "`PySlice::new` will be replaced by `PySlice::new_bound` in a future PyO3 version"
        )
    )]
    pub fn new(py: Python<'_>, start: isize, stop: isize, step: isize) -> &PySlice {
        Self::new_bound(py, start, stop, step).into_gil_ref()
    }

    /// Constructs a new slice with the given elements.
    pub fn new_bound(py: Python<'_>, start: isize, stop: isize, step: isize) -> Bound<'_, PySlice> {
        unsafe {
            ffi::PySlice_New(
                ffi::PyLong_FromSsize_t(start),
                ffi::PyLong_FromSsize_t(stop),
                ffi::PyLong_FromSsize_t(step),
            )
            .assume_owned(py)
            .downcast_into_unchecked()
        }
    }

    /// Deprecated form of `PySlice::full_bound`.
    #[cfg_attr(
        not(feature = "gil-refs"),
        deprecated(
            since = "0.21.0",
            note = "`PySlice::full` will be replaced by `PySlice::full_bound` in a future PyO3 version"
        )
    )]
    pub fn full(py: Python<'_>) -> &PySlice {
        PySlice::full_bound(py).into_gil_ref()
    }

    /// Constructs a new full slice that is equivalent to `::`.
    pub fn full_bound(py: Python<'_>) -> Bound<'_, PySlice> {
        unsafe {
            ffi::PySlice_New(ffi::Py_None(), ffi::Py_None(), ffi::Py_None())
                .assume_owned(py)
                .downcast_into_unchecked()
        }
    }

    /// 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.
    #[inline]
    pub fn indices(&self, length: isize) -> PyResult<PySliceIndices> {
        self.as_borrowed().indices(length)
    }
}

/// Implementation of functionality for [`PySlice`].
///
/// These methods are defined for the `Bound<'py, PyTuple>` smart pointer, so to use method call
/// syntax these methods are separated into a trait, because stable Rust does not yet support
/// `arbitrary_self_types`.
#[doc(alias = "PySlice")]
pub trait PySliceMethods<'py>: crate::sealed::Sealed {
    /// 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.
    fn indices(&self, length: isize) -> PyResult<PySliceIndices>;
}

impl<'py> PySliceMethods<'py> for Bound<'py, PySlice> {
    fn indices(&self, length: isize) -> PyResult<PySliceIndices> {
        unsafe {
            let mut slicelength: isize = 0;
            let mut start: isize = 0;
            let mut stop: isize = 0;
            let mut step: isize = 0;
            let r = ffi::PySlice_GetIndicesEx(
                self.as_ptr(),
                length,
                &mut start,
                &mut stop,
                &mut step,
                &mut slicelength,
            );
            if r == 0 {
                Ok(PySliceIndices {
                    start,
                    stop,
                    step,
                    // non-negative isize should always fit into usize
                    slicelength: slicelength as _,
                })
            } else {
                Err(PyErr::fetch(self.py()))
            }
        }
    }
}

impl ToPyObject for PySliceIndices {
    fn to_object(&self, py: Python<'_>) -> PyObject {
        PySlice::new_bound(py, self.start, self.stop, self.step).into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_py_slice_new() {
        Python::with_gil(|py| {
            let slice = PySlice::new_bound(py, isize::MIN, isize::MAX, 1);
            assert_eq!(
                slice.getattr("start").unwrap().extract::<isize>().unwrap(),
                isize::MIN
            );
            assert_eq!(
                slice.getattr("stop").unwrap().extract::<isize>().unwrap(),
                isize::MAX
            );
            assert_eq!(
                slice.getattr("step").unwrap().extract::<isize>().unwrap(),
                1
            );
        });
    }

    #[test]
    fn test_py_slice_full() {
        Python::with_gil(|py| {
            let slice = PySlice::full_bound(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;
        let stop = 0;
        let step = 0;
        assert_eq!(
            PySliceIndices::new(start, stop, step),
            PySliceIndices {
                start,
                stop,
                step,
                slicelength: 0
            }
        );

        let start = 0;
        let stop = 100;
        let step = 10;
        assert_eq!(
            PySliceIndices::new(start, stop, step),
            PySliceIndices {
                start,
                stop,
                step,
                slicelength: 0
            }
        );

        let start = 0;
        let stop = -10;
        let step = -1;
        assert_eq!(
            PySliceIndices::new(start, stop, step),
            PySliceIndices {
                start,
                stop,
                step,
                slicelength: 0
            }
        );

        let start = 0;
        let stop = -10;
        let step = 20;
        assert_eq!(
            PySliceIndices::new(start, stop, step),
            PySliceIndices {
                start,
                stop,
                step,
                slicelength: 0
            }
        );
    }
}