Skip to content
Draft
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
16 changes: 11 additions & 5 deletions include/pybind11/stl_bind.h
Original file line number Diff line number Diff line change
Expand Up @@ -286,18 +286,24 @@ void vector_modifiers(
cl.def(
"__delitem__",
[](Vector &v, const slice &slice) {
size_t start = 0, stop = 0, step = 0, slicelength = 0;
ssize_t start = 0, stop = 0, step = 0, slicelength = 0;

if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
if (!slice.compute((ssize_t) v.size(), &start, &stop, &step, &slicelength)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use Cpp style static cast?

throw error_already_set();
}

if (step == 1 && false) {
if (step == 1) {
v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
} else {
for (size_t i = 0; i < slicelength; ++i) {
// For a positive step, erasing an element shifts the remaining
// (later) elements down by one, so the next index to erase is
// ``start + step - 1``. For a negative step the visited indices
// are strictly decreasing, so erasing never shifts them and the
// next index is simply ``start + step``.
ssize_t offset = step > 0 ? step - 1 : step;
for (ssize_t i = 0; i < slicelength; ++i) {
v.erase(v.begin() + DiffType(start));
start += step - 1;
start += offset;
}
}
},
Expand Down
23 changes: 23 additions & 0 deletions tests/test_stl_binders.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,29 @@ def test_vector_int():
assert len(v_int2) == 0


def test_vector_delitem_slice():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not invert the for loop and just pytest parameterize?

slice_cases = [
slice(1, 4),
slice(None, None, 2),
slice(1, None, 2),
slice(None, None, -1),
slice(None, None, -2),
slice(3, 1, -1),
slice(2, 2),
slice(None),
slice(5, 0, -2),
slice(-3, -1),
slice(None, None, -3),
]
for n in range(8):
for s in slice_cases:
ref = list(range(n))
got = m.VectorInt(range(n))
del ref[s]
del got[s]
assert list(got) == ref, f"n={n} slice={s}"


# Older PyPy's failed here, related to the PyPy's buffer protocol.
def test_vector_buffer():
b = bytearray([1, 2, 3, 4])
Expand Down
Loading