diff --git a/mypyc/doc/bytes_operations.rst b/mypyc/doc/bytes_operations.rst index 6e9c27427e1e..6a0d659fac07 100644 --- a/mypyc/doc/bytes_operations.rst +++ b/mypyc/doc/bytes_operations.rst @@ -20,6 +20,7 @@ Operators * Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``) * Repetition (``b * n``, ``n * b``) * Comparisons (``==``, ``!=``) +* Containment (``n in b`` where ``n`` is an ``int``, ``b1 in b2``) .. _bytes-methods: diff --git a/mypyc/lib-rt/bytes_extra_ops.c b/mypyc/lib-rt/bytes_extra_ops.c index ae9e61b1cffa..bf6be2a31b6a 100644 --- a/mypyc/lib-rt/bytes_extra_ops.c +++ b/mypyc/lib-rt/bytes_extra_ops.c @@ -44,3 +44,52 @@ PyObject *CPyBytes_Translate(PyObject *bytes, PyObject *table) { return CPyBytes_CheckResult( PyObject_CallMethodOneArg(bytes, mypyc_interned_str.translate, table)); } + +// Needles up to this length are searched for directly. Longer needles use the +// generic implementation, which has better worst-case behavior. +#define CPY_BYTES_CONTAINS_MAX_DIRECT 32 + +int CPyBytes_ContainsInt(PyObject *self, CPyTagged value) { + if (likely(PyBytes_CheckExact(self))) { + if (likely(CPyTagged_CheckShort(value))) { + Py_ssize_t byte = CPyTagged_ShortAsSsize_t(value); + if (likely(byte >= 0 && byte < 256)) { + return memchr(PyBytes_AS_STRING(self), (int)byte, PyBytes_GET_SIZE(self)) != NULL; + } + } + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return -1; + } + PyObject *item = CPyTagged_AsObject(value); + int result = PySequence_Contains(self, item); + Py_DECREF(item); + return result; +} + +int CPyBytes_Contains(PyObject *self, PyObject *sub) { + if (likely(PyBytes_CheckExact(self) && PyBytes_CheckExact(sub))) { + Py_ssize_t len = PyBytes_GET_SIZE(self); + Py_ssize_t sub_len = PyBytes_GET_SIZE(sub); + if (sub_len == 0) { + return 1; + } + if (sub_len > len) { + return 0; + } + if (sub_len <= CPY_BYTES_CONTAINS_MAX_DIRECT) { + const char *buf = PyBytes_AS_STRING(self); + const char *sub_buf = PyBytes_AS_STRING(sub); + // One past the last position where a match can start + const char *end = buf + (len - sub_len + 1); + const char *p = buf; + while ((p = memchr(p, sub_buf[0], end - p)) != NULL) { + if (memcmp(p + 1, sub_buf + 1, sub_len - 1) == 0) { + return 1; + } + p++; + } + return 0; + } + } + return PySequence_Contains(self, sub); +} diff --git a/mypyc/lib-rt/bytes_extra_ops.h b/mypyc/lib-rt/bytes_extra_ops.h index 0f2917764ba0..e5c8798bf49d 100644 --- a/mypyc/lib-rt/bytes_extra_ops.h +++ b/mypyc/lib-rt/bytes_extra_ops.h @@ -8,6 +8,10 @@ // Optimized bytes translate operation PyObject *CPyBytes_Translate(PyObject *bytes, PyObject *table); +// Optimized bytes.__contains__ operations +int CPyBytes_ContainsInt(PyObject *self, CPyTagged value); +int CPyBytes_Contains(PyObject *self, PyObject *sub); + // Optimized bytes.__getitem__ operations // If index is negative, convert to non-negative index (no range checking) diff --git a/mypyc/primitives/bytes_ops.py b/mypyc/primitives/bytes_ops.py index 9efeb108afb6..4f14fb6f5a63 100644 --- a/mypyc/primitives/bytes_ops.py +++ b/mypyc/primitives/bytes_ops.py @@ -101,6 +101,30 @@ error_kind=ERR_MAGIC, ) +# int in bytes +binary_op( + name="in", + arg_types=[int_rprimitive, bytes_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyBytes_ContainsInt", + error_kind=ERR_NEG_INT, + truncated_type=bool_rprimitive, + ordering=[1, 0], + dependencies=[BYTES_EXTRA_OPS], +) + +# bytes in bytes +binary_op( + name="in", + arg_types=[bytes_rprimitive, bytes_rprimitive], + return_type=c_int_rprimitive, + c_function_name="CPyBytes_Contains", + error_kind=ERR_NEG_INT, + truncated_type=bool_rprimitive, + ordering=[1, 0], + dependencies=[BYTES_EXTRA_OPS], +) + # bytes.join(obj) method_op( name="join", diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 5a33c3336765..699b21148a51 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -205,6 +205,7 @@ def decode(self, encoding: str=..., errors: str=...) -> str: ... def translate(self, t: bytes | bytearray) -> bytes: ... def startswith(self, t: bytes | bytearray) -> bool: ... def endswith(self, t: bytes | bytearray) -> bool: ... + def __contains__(self, x: int | bytes | bytearray) -> bool: ... def __iter__(self) -> Iterator[int]: ... class bytearray: diff --git a/mypyc/test-data/irbuild-bytes.test b/mypyc/test-data/irbuild-bytes.test index 9dea9d9dd647..a77378b6b192 100644 --- a/mypyc/test-data/irbuild-bytes.test +++ b/mypyc/test-data/irbuild-bytes.test @@ -320,6 +320,116 @@ L0: r5 = cast(bytearray, r4) return r5 +[case testBytesContains] +def int_in(x: int, b: bytes) -> bool: + return x in b + +def int_not_in(x: int, b: bytes) -> bool: + return x not in b + +def bool_in(x: bool, b: bytes) -> bool: + return x in b + +def bytes_in(x: bytes, b: bytes) -> bool: + return x in b + +def bytes_not_in(x: bytes, b: bytes) -> bool: + return x not in b +[out] +def int_in(x, b): + x :: int + b :: bytes + r0 :: i32 + r1 :: bit + r2 :: bool +L0: + r0 = CPyBytes_ContainsInt(b, x) + r1 = r0 >= 0 :: signed + r2 = truncate r0: i32 to builtins.bool + return r2 +def int_not_in(x, b): + x :: int + b :: bytes + r0 :: i32 + r1 :: bit + r2, r3 :: bool +L0: + r0 = CPyBytes_ContainsInt(b, x) + r1 = r0 >= 0 :: signed + r2 = truncate r0: i32 to builtins.bool + r3 = r2 ^ 1 + return r3 +def bool_in(x, b): + x :: bool + b :: bytes + r0 :: bool + r1 :: int + r2 :: i32 + r3 :: bit + r4 :: bool +L0: + r0 = x << 1 + r1 = extend r0: builtins.bool to builtins.int + r2 = CPyBytes_ContainsInt(b, r1) + r3 = r2 >= 0 :: signed + r4 = truncate r2: i32 to builtins.bool + return r4 +def bytes_in(x, b): + x, b :: bytes + r0 :: i32 + r1 :: bit + r2 :: bool +L0: + r0 = CPyBytes_Contains(b, x) + r1 = r0 >= 0 :: signed + r2 = truncate r0: i32 to builtins.bool + return r2 +def bytes_not_in(x, b): + x, b :: bytes + r0 :: i32 + r1 :: bit + r2, r3 :: bool +L0: + r0 = CPyBytes_Contains(b, x) + r1 = r0 >= 0 :: signed + r2 = truncate r0: i32 to builtins.bool + r3 = r2 ^ 1 + return r3 + +[case testBytesContainsGeneric] +from typing import Optional, Union + +def optional_operand(x: int, b: Optional[bytes]) -> bool: + return x in b # type: ignore + +def union_item(x: Union[int, bytes], b: bytes) -> bool: + return x in b +[out] +def optional_operand(x, b): + x :: int + b :: union[bytes, None] + r0 :: object + r1 :: i32 + r2 :: bit + r3 :: bool +L0: + r0 = box(int, x) + r1 = PySequence_Contains(b, r0) + r2 = r1 >= 0 :: signed + r3 = truncate r1: i32 to builtins.bool + return r3 +def union_item(x, b): + x :: union[int, bytes] + b :: bytes + r0 :: i32 + r1 :: bit + r2 :: bool +L0: + r0 = PySequence_Contains(b, x) + r1 = r0 >= 0 :: signed + r2 = truncate r0: i32 to builtins.bool + return r2 + [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 a847fa5f7ecb..b7f11e894ffc 100644 --- a/mypyc/test-data/run-bytes.test +++ b/mypyc/test-data/run-bytes.test @@ -833,6 +833,96 @@ class WrongSliceType(bytearray): return self.result return super().__getitem__(i) +[case testBytesContains] +from typing import Any +from testutil import assertRaises +from bcsubclass import BytesSubclass, BytesContainsOverride + +HAYSTACKS = [ + b"", + b"a", + b"abc", + b"aaab", + b"\x00\x01\x7f\x80\xfe\xff", + b"abcabcabd" * 10, + bytes(range(256)), + b"x" * 40 + b"y", +] + +def outcome(f: Any) -> Any: + try: + return f() + except Exception as e: + return type(e), str(e) + +def needles(h: bytes) -> list[bytes]: + result = [b"", b"z", b"\x00", b"\xff", b"ab", b"abd", b"aab", h, h + b"!", b"!" + h] + for i in range(len(h)): + for j in range(i + 1, min(len(h), i + 35) + 1): + result.append(h[i:j]) + # Same length, but differs in the last byte + result.append(h[i:j - 1] + bytes([(h[j - 1] + 1) % 256])) + return result + +def test_int_in_bytes() -> None: + for h in HAYSTACKS: + a: Any = h + for n in list(range(-3, 260)) + [2**62, -2**62, 2**100, -2**100]: + an: Any = n + assert outcome(lambda: n in h) == outcome(lambda: an in a), (h, n) + assert outcome(lambda: n not in h) == outcome(lambda: an not in a), (h, n) + with assertRaises(ValueError, "byte must be in range(0, 256)"): + 256 in b"a" + with assertRaises(ValueError, "byte must be in range(0, 256)"): + -1 not in b"a" + +def test_bool_in_bytes() -> None: + t = True + f = False + assert t in b"\x01" + assert t not in b"\x00" + assert f in b"\x00" + assert f not in b"\x01" + +def test_bytes_in_bytes() -> None: + for h in HAYSTACKS: + a: Any = h + for x in needles(h): + ax: Any = x + assert (x in h) == (ax in a), (h, x) + assert (x not in h) == (ax not in a), (h, x) + +def test_long_needle() -> None: + h = b"a" * 100 + b"b" + for n in range(30, 40): + assert b"a" * n + b"b" in h + assert b"a" * n + b"c" not in h + assert b"b" + b"a" * n not in h + +def test_subclass() -> None: + s: bytes = BytesSubclass(b"abc") + assert 97 in s + assert 100 not in s + assert b"bc" in s + assert BytesSubclass(b"bc") in b"abc" + assert BytesSubclass(b"bd") not in b"abc" + assert BytesSubclass(b"") in b"" + + o: bytes = BytesContainsOverride(b"abc") + assert 1 in o + assert 97 not in o + assert 1000 in o + assert b"zz" in o + assert b"ab" not in o + +[file bcsubclass.py] +class BytesSubclass(bytes): + pass + +class BytesContainsOverride(bytes): + def __contains__(self, x: object) -> bool: + return x == 1 or x == 1000 or x == b"zz" + [case testBytesJoin] from typing import Any from testutil import assertRaises