Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7bf36da

Browse files
Issue #27039: Fixed bytearray.remove() for values greater than 127.
Patch by Joe Jevnik.
1 parent dc953a5 commit 7bf36da

3 files changed

Lines changed: 14 additions & 7 deletions

File tree

Lib/test/test_bytes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,6 +1082,13 @@ def test_remove(self):
10821082
b.remove(Indexable(ord('e')))
10831083
self.assertEqual(b, b'')
10841084

1085+
# test values outside of the ascii range: (0, 127)
1086+
c = bytearray([126, 127, 128, 129])
1087+
c.remove(127)
1088+
self.assertEqual(c, bytes([126, 128, 129]))
1089+
c.remove(129)
1090+
self.assertEqual(c, bytes([126, 128]))
1091+
10851092
def test_pop(self):
10861093
b = bytearray(b'world')
10871094
self.assertEqual(b.pop(), ord('d'))

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ Release date: tba
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #27039: Fixed bytearray.remove() for values greater than 127. Patch by
14+
Joe Jevnik.
15+
1316
- Issue #23640: int.from_bytes() no longer bypasses constructors for subclasses.
1417

1518
- Issue #26811: gc.get_objects() no longer contains a broken tuple with NULL

Objects/bytearrayobject.c

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2565,21 +2565,18 @@ static PyObject *
25652565
bytearray_remove_impl(PyByteArrayObject *self, int value)
25662566
/*[clinic end generated code: output=d659e37866709c13 input=47560b11fd856c24]*/
25672567
{
2568-
Py_ssize_t where, n = Py_SIZE(self);
2568+
Py_ssize_t n = Py_SIZE(self);
25692569
char *buf = PyByteArray_AS_STRING(self);
2570+
char *where = memchr(buf, value, n);
25702571

2571-
for (where = 0; where < n; where++) {
2572-
if (buf[where] == value)
2573-
break;
2574-
}
2575-
if (where == n) {
2572+
if (!where) {
25762573
PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
25772574
return NULL;
25782575
}
25792576
if (!_canresize(self))
25802577
return NULL;
25812578

2582-
memmove(buf + where, buf + where + 1, n - where);
2579+
memmove(where, where + 1, buf + n - where);
25832580
if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)
25842581
return NULL;
25852582

0 commit comments

Comments
 (0)