Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Optimize checks; add bytearray tests
  • Loading branch information
esarp committed Dec 10, 2025
commit 69fbc684df64fbb7fea0ecdbda636ff6c24302bd
9 changes: 4 additions & 5 deletions mypyc/lib-rt/bytes_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -178,20 +178,19 @@ int CPyBytes_Startswith(PyObject *self, PyObject *subobj) {
return 1;
}

Py_ssize_t self_len = PyBytes_GET_SIZE(self);
Py_ssize_t subobj_len = PyBytes_GET_SIZE(subobj);
if (subobj_len == 0) {
return 1;
}

Py_ssize_t self_len = PyBytes_GET_SIZE(self);
if (subobj_len > self_len) {
return 0;
}

const char *self_buf = PyBytes_AS_STRING(self);
const char *subobj_buf = PyBytes_AS_STRING(subobj);

if (subobj_len == 0) {
return 1;
}

return memcmp(self_buf, subobj_buf, (size_t)subobj_len) == 0 ? 1 : 0;
}
_Py_IDENTIFIER(startswith);
Expand Down
1 change: 1 addition & 0 deletions mypyc/test-data/fixtures/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ def __add__(self, s: bytes) -> bytearray: ...
def __setitem__(self, i: int, o: int) -> None: ...
def __getitem__(self, i: int) -> int: ...
def decode(self, x: str = ..., y: str = ...) -> str: ...
def startswith(self, t: bytes) -> bool: ...

class bool(int):
def __init__(self, o: object = ...) -> None: ...
Expand Down
8 changes: 8 additions & 0 deletions mypyc/test-data/run-bytes.test
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,14 @@ def test_startswith() -> None:
assert b''.startswith(b'')
assert not b''.startswith(test)

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.

Test with bytearray 1) as the receiver object and 2) the argument. This way we will also test the slow path.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added a few checks to cover those as well


# Test bytearray to verify slow paths
assert test.startswith(bytearray(b'some'))
assert not test.startswith(bytearray(b'other'))

test = bytearray(b'some string')
assert test.startswith(b'some')
assert not test.startswith(b'other')

[case testBytesSlicing]
def test_bytes_slicing() -> None:
b = b'abcdefg'
Expand Down