From 347569dc9b7af36cafed4a569ba577fe92eaa9a2 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 12:16:26 +0500 Subject: [PATCH 1/3] [mypyc] Add primitives for bytearray len, indexing, item assignment and slicing Add fast paths for len(b), b[i], b[i] = x and b[i:j] when b is a bytearray. The C implementations live in bytearray_extra_ops.c. Indexing, item assignment and slicing only use the fast path for exact bytearray objects with short int arguments, and otherwise fall back to the generic implementation, so subclass overrides and error messages for very large indexes are preserved. On free-threaded builds the item array is accessed while holding the object's lock, since a bytearray can be resized concurrently. Part of mypyc/mypyc#644. --- mypyc/doc/bytearray_operations.rst | 18 +++++ mypyc/irbuild/expression.py | 3 + mypyc/irbuild/ll_builder.py | 8 +- mypyc/lib-rt/bytearray_extra_ops.c | 121 +++++++++++++++++++++++++++++ mypyc/lib-rt/bytearray_extra_ops.h | 9 +++ mypyc/primitives/bytearray_ops.py | 34 +++++++- mypyc/primitives/bytes_ops.py | 1 - mypyc/test-data/irbuild-bytes.test | 63 +++++++++++++++ mypyc/test-data/run-bytes.test | 119 ++++++++++++++++++++++++++++ 9 files changed, 372 insertions(+), 4 deletions(-) diff --git a/mypyc/doc/bytearray_operations.rst b/mypyc/doc/bytearray_operations.rst index 3ee242b5648bf..3947aaf56759a 100644 --- a/mypyc/doc/bytearray_operations.rst +++ b/mypyc/doc/bytearray_operations.rst @@ -11,3 +11,21 @@ Construction * ``bytearray()`` * ``bytearray(x)`` + +Operators +--------- + +* Indexing (``b[n]``) +* Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``) + +Statements +---------- + +Set item by integer index: + +* ``b[n] = x`` + +Functions +--------- + +* ``len(b: bytearray)`` diff --git a/mypyc/irbuild/expression.py b/mypyc/irbuild/expression.py index e2ae96e6f161f..e99a9e6dca6bb 100644 --- a/mypyc/irbuild/expression.py +++ b/mypyc/irbuild/expression.py @@ -146,6 +146,7 @@ vec_item_type, vec_slice, ) +from mypyc.primitives.bytearray_ops import bytearray_slice_op from mypyc.primitives.bytes_ops import bytes_slice_op from mypyc.primitives.dict_ops import dict_get_item_op, dict_new_op, exact_dict_set_item_op from mypyc.primitives.float_ops import ( @@ -1084,6 +1085,8 @@ def try_gen_slice_op(builder: IRBuilder, base: Value, index: SliceExpr) -> Value end = builder.load_int(MAX_SHORT_INT) if isinstance(base.type, RVec): return vec_slice(builder.builder, base, begin, end, index.line) + if is_bytearray_rprimitive(base.type): + return builder.primitive_op(bytearray_slice_op, [base, begin, end], index.line) candidates = [list_slice_op, tuple_slice_op, str_slice_op, bytes_slice_op] return builder.builder.matching_call_c(candidates, [base, begin, end], index.line) diff --git a/mypyc/irbuild/ll_builder.py b/mypyc/irbuild/ll_builder.py index 01ee6dc6442d9..23b376a3190a6 100644 --- a/mypyc/irbuild/ll_builder.py +++ b/mypyc/irbuild/ll_builder.py @@ -102,6 +102,7 @@ int64_rprimitive, int_rprimitive, is_bool_or_bit_rprimitive, + is_bytearray_rprimitive, is_bytes_rprimitive, is_c_py_ssize_t_rprimitive, is_dict_rprimitive, @@ -2893,7 +2894,12 @@ def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Val """ typ = val.type size_value = None - if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ): + if ( + is_list_rprimitive(typ) + or is_tuple_rprimitive(typ) + or is_bytes_rprimitive(typ) + or is_bytearray_rprimitive(typ) + ): size_value = self.primitive_op(var_object_size, [val], line) elif is_set_rprimitive(typ) or is_frozenset_rprimitive(typ): elem_address = self.add(GetElementPtr(val, PySetObject, "used")) diff --git a/mypyc/lib-rt/bytearray_extra_ops.c b/mypyc/lib-rt/bytearray_extra_ops.c index fe734ed73159f..61d11aaca8dba 100644 --- a/mypyc/lib-rt/bytearray_extra_ops.c +++ b/mypyc/lib-rt/bytearray_extra_ops.c @@ -31,3 +31,124 @@ PyObject *CPyByteArray_FromBytesSlice(PyObject *obj, CPyTagged start, CPyTagged Py_DECREF(slice); return result; } + +// On free-threaded builds, the item array of a bytearray may be resized or freed +// concurrently, so it must only be accessed while holding the object's lock. +#ifdef Py_GIL_DISABLED +#define CPY_BYTEARRAY_LOCK(obj) Py_BEGIN_CRITICAL_SECTION(obj) +#define CPY_BYTEARRAY_UNLOCK() Py_END_CRITICAL_SECTION() +#else +#define CPY_BYTEARRAY_LOCK(obj) { +#define CPY_BYTEARRAY_UNLOCK() } +#endif + +CPyTagged CPyByteArray_GetItem(PyObject *obj, CPyTagged index) { + if (likely(PyByteArray_CheckExact(obj) && CPyTagged_CheckShort(index))) { + Py_ssize_t n = CPyTagged_ShortAsSsize_t(index); + CPyTagged result = CPY_INT_TAG; + CPY_BYTEARRAY_LOCK(obj); + Py_ssize_t size = PyByteArray_GET_SIZE(obj); + if (n < 0) { + n += size; + } + if (n < 0 || n >= size) { + PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); + } else { + result = (CPyTagged)(unsigned char)PyByteArray_AS_STRING(obj)[n] << 1; + } + CPY_BYTEARRAY_UNLOCK(); + return result; + } + + // Generic path for subclasses and large indexes + PyObject *index_obj = CPyTagged_AsObject(index); + if (index_obj == NULL) { + return CPY_INT_TAG; + } + PyObject *item = PyObject_GetItem(obj, index_obj); + Py_DECREF(index_obj); + if (item == NULL) { + return CPY_INT_TAG; + } + if (unlikely(!PyLong_Check(item))) { + CPy_TypeError("int", item); + Py_DECREF(item); + return CPY_INT_TAG; + } + return CPyTagged_StealFromObject(item); +} + +bool CPyByteArray_SetItem(PyObject *obj, CPyTagged index, CPyTagged value) { + if (likely(PyByteArray_CheckExact(obj) && CPyTagged_CheckShort(index))) { + Py_ssize_t n = CPyTagged_ShortAsSsize_t(index); + // Like CPython, check the value before the index + Py_ssize_t v = CPyTagged_CheckShort(value) ? CPyTagged_ShortAsSsize_t(value) : -1; + if (v < 0 || v > 255) { + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return false; + } + bool ok = false; + CPY_BYTEARRAY_LOCK(obj); + Py_ssize_t size = PyByteArray_GET_SIZE(obj); + if (n < 0) { + n += size; + } + if (n < 0 || n >= size) { + PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); + } else { + PyByteArray_AS_STRING(obj)[n] = (char)v; + ok = true; + } + CPY_BYTEARRAY_UNLOCK(); + return ok; + } + + // Generic path for subclasses and large indexes + PyObject *index_obj = CPyTagged_AsObject(index); + if (index_obj == NULL) { + return false; + } + PyObject *value_obj = CPyTagged_AsObject(value); + if (value_obj == NULL) { + Py_DECREF(index_obj); + return false; + } + int res = PyObject_SetItem(obj, index_obj, value_obj); + Py_DECREF(index_obj); + Py_DECREF(value_obj); + return res >= 0; +} + +PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { + if (likely(PyByteArray_CheckExact(obj) + && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) { + Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start); + Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end); + PyObject *result; + CPY_BYTEARRAY_LOCK(obj); + Py_ssize_t size = PyByteArray_GET_SIZE(obj); + if (startn < 0) { + startn += size; + if (startn < 0) { + startn = 0; + } + } else if (startn > size) { + startn = size; + } + if (endn < 0) { + endn += size; + if (endn < 0) { + endn = 0; + } + } else if (endn > size) { + endn = size; + } + Py_ssize_t len = endn > startn ? endn - startn : 0; + result = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(obj) + startn, len); + CPY_BYTEARRAY_UNLOCK(); + return result; + } + + // Generic path for subclasses and large indexes + return CPyObject_GetSlice(obj, start, end); +} diff --git a/mypyc/lib-rt/bytearray_extra_ops.h b/mypyc/lib-rt/bytearray_extra_ops.h index 3fe973d230118..05e7eb96e38de 100644 --- a/mypyc/lib-rt/bytearray_extra_ops.h +++ b/mypyc/lib-rt/bytearray_extra_ops.h @@ -11,4 +11,13 @@ PyObject *CPyByteArray_New(void); // An omitted bound is represented by CPY_INT_TAG. PyObject *CPyByteArray_FromBytesSlice(PyObject *obj, CPyTagged start, CPyTagged end); +// bytearray[index] +CPyTagged CPyByteArray_GetItem(PyObject *obj, CPyTagged index); + +// bytearray[index] = value +bool CPyByteArray_SetItem(PyObject *obj, CPyTagged index, CPyTagged value); + +// bytearray[start:end] +PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end); + #endif diff --git a/mypyc/primitives/bytearray_ops.py b/mypyc/primitives/bytearray_ops.py index c02b3ee1c2a7a..f8ea3db584b2d 100644 --- a/mypyc/primitives/bytearray_ops.py +++ b/mypyc/primitives/bytearray_ops.py @@ -8,7 +8,7 @@ from __future__ import annotations from mypyc.ir.deps import BYTEARRAY_EXTRA_OPS -from mypyc.ir.ops import ERR_MAGIC, ERR_NEVER +from mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER from mypyc.ir.rtypes import ( bit_rprimitive, bytearray_rprimitive, @@ -16,7 +16,7 @@ int_rprimitive, object_rprimitive, ) -from mypyc.primitives.registry import custom_primitive_op, function_op, load_address_op +from mypyc.primitives.registry import custom_primitive_op, function_op, load_address_op, method_op # Get the 'bytearray' type object. load_address_op(name="builtins.bytearray", type=object_rprimitive, src="PyByteArray_Type") @@ -59,3 +59,33 @@ c_function_name="PyByteArray_Check", error_kind=ERR_NEVER, ) + +# bytearray[index] +method_op( + name="__getitem__", + arg_types=[bytearray_rprimitive, int_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyByteArray_GetItem", + error_kind=ERR_MAGIC, + dependencies=[BYTEARRAY_EXTRA_OPS], +) + +# bytearray[index] = value +method_op( + name="__setitem__", + arg_types=[bytearray_rprimitive, int_rprimitive, int_rprimitive], + return_type=bit_rprimitive, + c_function_name="CPyByteArray_SetItem", + error_kind=ERR_FALSE, + dependencies=[BYTEARRAY_EXTRA_OPS], +) + +# bytearray[begin:end] +bytearray_slice_op = custom_primitive_op( + name="bytearray_slice", + arg_types=[bytearray_rprimitive, int_rprimitive, int_rprimitive], + return_type=bytearray_rprimitive, + c_function_name="CPyByteArray_GetSlice", + error_kind=ERR_MAGIC, + dependencies=[BYTEARRAY_EXTRA_OPS], +) diff --git a/mypyc/primitives/bytes_ops.py b/mypyc/primitives/bytes_ops.py index 96e8069f317ed..0c51aa1ad8c94 100644 --- a/mypyc/primitives/bytes_ops.py +++ b/mypyc/primitives/bytes_ops.py @@ -94,7 +94,6 @@ ) # bytes[index] -# bytearray[index] method_op( name="__getitem__", arg_types=[bytes_rprimitive, int_rprimitive], diff --git a/mypyc/test-data/irbuild-bytes.test b/mypyc/test-data/irbuild-bytes.test index 9f9d14c291b15..e0d7cdeb6b4d3 100644 --- a/mypyc/test-data/irbuild-bytes.test +++ b/mypyc/test-data/irbuild-bytes.test @@ -257,6 +257,69 @@ L0: r1 = r0 << 1 return r1 +[case testBytearrayLen] +def f(b: bytearray) -> int: + return len(b) +[out] +def f(b): + b :: bytearray + r0 :: native_int + r1 :: short_int +L0: + r0 = var_object_size b + r1 = r0 << 1 + return r1 + +[case testBytearrayGetItem] +def f(b: bytearray, i: int) -> int: + return b[i] +[out] +def f(b, i): + b :: bytearray + i, r0 :: int +L0: + r0 = CPyByteArray_GetItem(b, i) + return r0 + +[case testBytearraySetItem] +def f(b: bytearray, i: int, x: int) -> None: + b[i] = x +[out] +def f(b, i, x): + b :: bytearray + i, x :: int + r0 :: bit +L0: + r0 = CPyByteArray_SetItem(b, i, x) + return 1 + +[case testBytearraySlice] +def f(b: bytearray, i: int, j: int) -> bytearray: + return b[i:j] +def g(b: bytearray, i: int, j: int, k: int) -> bytearray: + return b[i:j:k] +[out] +def f(b, i, j): + b :: bytearray + i, j :: int + r0 :: bytearray +L0: + r0 = CPyByteArray_GetSlice(b, i, j) + return r0 +def g(b, i, j, k): + b :: bytearray + i, j, k :: int + r0, r1, r2, r3, r4 :: object + r5 :: bytearray +L0: + r0 = box(int, i) + r1 = box(int, j) + r2 = box(int, k) + r3 = PySlice_New(r0, r1, r2) + r4 = PyObject_GetItem(b, r3) + r5 = cast(bytearray, r4) + return r5 + [case testBytesFormatting] def f(var: bytes, num: int) -> None: b1 = b'aaaa%bbbbb%s' % (var, var) diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index c26ae9142bd0d..00ba0b3f58bb8 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -567,6 +567,125 @@ def test_bytearray_indexing() -> None: with assertRaises(ValueError, "byte must be in range(0, 256)"): b2[0] = 256 +[case testBytearrayPrimitivesMatchGeneric] +from typing import Any, Callable + +from testutil import assertRaises + +from basubclass import ByteArraySubclass, ByteArrayOverrides + +BIG_INTS = [2**31, 2**62 - 1, 2**62, 2**63, 2**70] + +def outcome(f: Callable[[], object]) -> object: + try: + return f() + except Exception as e: + return (type(e), str(e)) + +def test_len() -> None: + b = bytearray() + a: Any = b + for i in range(20): + assert len(b) == len(a) == i + a.append(i) + del a[3:7] + assert len(b) == len(a) == 16 + a.extend(b"xyz") + assert len(b) == len(a) == 19 + a.clear() + assert len(b) == len(a) == 0 + +def test_get_item() -> None: + b = bytearray(b"\x00\x7f\x80\xfe\xff") + a: Any = b + n = len(b) + for i in list(range(-n - 2, n + 2)) + BIG_INTS + [-x for x in BIG_INTS]: + assert outcome(lambda: b[i]) == outcome(lambda: a[i]), i + with assertRaises(IndexError, "bytearray index out of range"): + b[n + int()] + assert outcome(lambda: bytearray()[int()]) == outcome(lambda: bytearray(a[:0])[0]) + +def test_set_item() -> None: + values = [-1, 0, 1, 127, 128, 255, 256] + BIG_INTS + [-x for x in BIG_INTS] + n = 4 + for i in list(range(-n - 2, n + 2)) + BIG_INTS + [-x for x in BIG_INTS]: + for v in values: + b = bytearray(b"abcd") + a: Any = bytearray(b"abcd") + + def set_native() -> None: + b[i] = v + + def set_generic() -> None: + a[i] = v + + assert outcome(set_native) == outcome(set_generic), (i, v) + assert b == a, (i, v) + b = bytearray(b"abcd") + # The value is checked before the index, like in CPython + with assertRaises(ValueError, "byte must be in range(0, 256)"): + b[10 + int()] = 256 + with assertRaises(IndexError, "bytearray index out of range"): + b[10 + int()] = 255 + b[1] += 1 + b[-1] -= 2 + assert b == b"accb" + +def test_slice() -> None: + b = bytearray(b"abcdefg") + a: Any = b + n = len(b) + bounds = list(range(-n - 2, n + 3)) + BIG_INTS + [-x for x in BIG_INTS] + for i in bounds: + assert b[i:] == a[i:], i + assert b[:i] == a[:i], i + for j in bounds: + assert b[i:j] == a[i:j], (i, j) + assert type(b[i:j]) is bytearray + c = b[:] + assert c == b and c is not b + c[0] = ord("z") + assert b == b"abcdefg" + assert bytearray()[1:2] == bytearray() + +def test_subclass() -> None: + s = ByteArraySubclass(b"abc") + assert len(s) == 3 + assert s[1] == ord("b") + assert s[-1] == ord("c") + s[0] = ord("x") + assert s == b"xbc" + t = s[1:] + assert t == b"bc" + assert type(t) is bytearray + with assertRaises(IndexError, "bytearray index out of range"): + s[3 + int()] + + o = ByteArrayOverrides(b"abc") + assert o[0] == 42 + assert o[-1] == 42 + o[1] = 5 + assert o.last_set == (1, 5) + assert o == b"abc" + assert o[0:2] == b"slice" + +[file basubclass.py] +from typing import Any + +class ByteArraySubclass(bytearray): + pass + +class ByteArrayOverrides(bytearray): + last_set: Any = None + + def __getitem__(self, i: Any) -> Any: + if isinstance(i, slice): + return bytearray(b"slice") + return 42 + + def __setitem__(self, i: Any, v: Any) -> None: + self.last_set = (i, v) + [case testBytesJoin] from typing import Any from testutil import assertRaises From 9f607358002c56285729f87714ccc3a3ebdc7329 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Mon, 9 Nov 2026 14:05:10 +0500 Subject: [PATCH 2/3] Check the result type of bytearray slicing on subclasses A subclass may override __getitem__ to return something other than a bytearray. Also make the subclass tests use bytearray as the static type, so that they exercise the primitives. --- mypyc/lib-rt/bytearray_extra_ops.c | 9 ++++++++- mypyc/test-data/run-bytes.test | 29 +++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/mypyc/lib-rt/bytearray_extra_ops.c b/mypyc/lib-rt/bytearray_extra_ops.c index 61d11aaca8dba..4eb2da8e073f1 100644 --- a/mypyc/lib-rt/bytearray_extra_ops.c +++ b/mypyc/lib-rt/bytearray_extra_ops.c @@ -150,5 +150,12 @@ PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { } // Generic path for subclasses and large indexes - return CPyObject_GetSlice(obj, start, end); + PyObject *result = CPyObject_GetSlice(obj, start, end); + if (result != NULL && unlikely(!PyByteArray_Check(result))) { + // A subclass may override __getitem__ to return anything + CPy_TypeError("bytearray", result); + Py_DECREF(result); + return NULL; + } + return result; } diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index 00ba0b3f58bb8..db85a97e2760e 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -572,7 +572,7 @@ from typing import Any, Callable from testutil import assertRaises -from basubclass import ByteArraySubclass, ByteArrayOverrides +from basubclass import ByteArraySubclass, ByteArrayOverrides, WrongSliceType BIG_INTS = [2**31, 2**62 - 1, 2**62, 2**63, 2**70] @@ -649,7 +649,8 @@ def test_slice() -> None: assert bytearray()[1:2] == bytearray() def test_subclass() -> None: - s = ByteArraySubclass(b"abc") + # Use bytearray as the static type, so that the primitives are used + s: bytearray = ByteArraySubclass(b"abc") assert len(s) == 3 assert s[1] == ord("b") assert s[-1] == ord("c") @@ -661,14 +662,26 @@ def test_subclass() -> None: with assertRaises(IndexError, "bytearray index out of range"): s[3 + int()] - o = ByteArrayOverrides(b"abc") + overrides = ByteArrayOverrides(b"abc") + o: bytearray = overrides assert o[0] == 42 assert o[-1] == 42 o[1] = 5 - assert o.last_set == (1, 5) + assert overrides.last_set == (1, 5) assert o == b"abc" assert o[0:2] == b"slice" + wrong = WrongSliceType(b"abc") + w: bytearray = wrong + wrong.result = 1.5 + with assertRaises(TypeError, "bytearray object expected; got float"): + w[0:2] + wrong.result = b"bc" + with assertRaises(TypeError, "bytearray object expected; got bytes"): + w[1:] + wrong.result = ByteArraySubclass(b"bc") + assert w[1:] == b"bc" + [file basubclass.py] from typing import Any @@ -686,6 +699,14 @@ class ByteArrayOverrides(bytearray): def __setitem__(self, i: Any, v: Any) -> None: self.last_set = (i, v) +class WrongSliceType(bytearray): + result: Any = None + + def __getitem__(self, i: Any) -> Any: + if isinstance(i, slice): + return self.result + return super().__getitem__(i) + [case testBytesJoin] from typing import Any from testutil import assertRaises From 409027b7fed1c858b816c5667c902753281767c0 Mon Sep 17 00:00:00 2001 From: Jahongir Qurbonov Date: Tue, 10 Nov 2026 23:31:39 +0500 Subject: [PATCH 3/3] Use critical section macros directly and clean up tests --- mypyc/lib-rt/bytearray_extra_ops.c | 22 ++++++++-------------- mypyc/test-data/fixtures/ir.py | 1 + mypyc/test-data/run-bytes.test | 3 ++- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/mypyc/lib-rt/bytearray_extra_ops.c b/mypyc/lib-rt/bytearray_extra_ops.c index 4eb2da8e073f1..3c49522b2f93a 100644 --- a/mypyc/lib-rt/bytearray_extra_ops.c +++ b/mypyc/lib-rt/bytearray_extra_ops.c @@ -33,20 +33,14 @@ PyObject *CPyByteArray_FromBytesSlice(PyObject *obj, CPyTagged start, CPyTagged } // On free-threaded builds, the item array of a bytearray may be resized or freed -// concurrently, so it must only be accessed while holding the object's lock. -#ifdef Py_GIL_DISABLED -#define CPY_BYTEARRAY_LOCK(obj) Py_BEGIN_CRITICAL_SECTION(obj) -#define CPY_BYTEARRAY_UNLOCK() Py_END_CRITICAL_SECTION() -#else -#define CPY_BYTEARRAY_LOCK(obj) { -#define CPY_BYTEARRAY_UNLOCK() } -#endif +// concurrently, so it must only be accessed in a critical section. On other builds, +// the critical section macros don't do anything. CPyTagged CPyByteArray_GetItem(PyObject *obj, CPyTagged index) { if (likely(PyByteArray_CheckExact(obj) && CPyTagged_CheckShort(index))) { Py_ssize_t n = CPyTagged_ShortAsSsize_t(index); CPyTagged result = CPY_INT_TAG; - CPY_BYTEARRAY_LOCK(obj); + Py_BEGIN_CRITICAL_SECTION(obj); Py_ssize_t size = PyByteArray_GET_SIZE(obj); if (n < 0) { n += size; @@ -56,7 +50,7 @@ CPyTagged CPyByteArray_GetItem(PyObject *obj, CPyTagged index) { } else { result = (CPyTagged)(unsigned char)PyByteArray_AS_STRING(obj)[n] << 1; } - CPY_BYTEARRAY_UNLOCK(); + Py_END_CRITICAL_SECTION(); return result; } @@ -88,7 +82,7 @@ bool CPyByteArray_SetItem(PyObject *obj, CPyTagged index, CPyTagged value) { return false; } bool ok = false; - CPY_BYTEARRAY_LOCK(obj); + Py_BEGIN_CRITICAL_SECTION(obj); Py_ssize_t size = PyByteArray_GET_SIZE(obj); if (n < 0) { n += size; @@ -99,7 +93,7 @@ bool CPyByteArray_SetItem(PyObject *obj, CPyTagged index, CPyTagged value) { PyByteArray_AS_STRING(obj)[n] = (char)v; ok = true; } - CPY_BYTEARRAY_UNLOCK(); + Py_END_CRITICAL_SECTION(); return ok; } @@ -125,7 +119,7 @@ PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start); Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end); PyObject *result; - CPY_BYTEARRAY_LOCK(obj); + Py_BEGIN_CRITICAL_SECTION(obj); Py_ssize_t size = PyByteArray_GET_SIZE(obj); if (startn < 0) { startn += size; @@ -145,7 +139,7 @@ PyObject *CPyByteArray_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) { } Py_ssize_t len = endn > startn ? endn - startn : 0; result = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(obj) + startn, len); - CPY_BYTEARRAY_UNLOCK(); + Py_END_CRITICAL_SECTION(); return result; } diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 8fed798bbc695..99ca3b13e5a95 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -220,6 +220,7 @@ def join(self, x: Iterable[object]) -> bytes: ... def startswith(self, t: bytes) -> bool: ... def endswith(self, t: bytes) -> bool: ... def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... class memoryview: def __init__(self, x: object) -> None: pass diff --git a/mypyc/test-data/run-bytes.test b/mypyc/test-data/run-bytes.test index db85a97e2760e..31493ce73ebcb 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -603,7 +603,8 @@ def test_get_item() -> None: assert outcome(lambda: b[i]) == outcome(lambda: a[i]), i with assertRaises(IndexError, "bytearray index out of range"): b[n + int()] - assert outcome(lambda: bytearray()[int()]) == outcome(lambda: bytearray(a[:0])[0]) + with assertRaises(IndexError, "bytearray index out of range"): + bytearray()[int()] def test_set_item() -> None: values = [-1, 0, 1, 127, 128, 255, 256] + BIG_INTS + [-x for x in BIG_INTS]