Skip to content

Fix crash when converting 0-length Go []byte to Python bytes#394

Draft
b-long wants to merge 1 commit into
masterfrom
fix/359-zero-length-byte-slice
Draft

Fix crash when converting 0-length Go []byte to Python bytes#394
b-long wants to merge 1 commit into
masterfrom
fix/359-zero-length-byte-slice

Conversation

@b-long
Copy link
Copy Markdown
Member

@b-long b-long commented Jun 4, 2026

Relates to issue 359

Slice_byte_to_bytes indexed s[0] unconditionally, causing a runtime panic on empty slices. Guard with an early return via PyBytes_FromStringAndSize(nil, 0) which the CPython API handles correctly.

…359)

`Slice_byte_to_bytes` indexed `s[0]` unconditionally, causing a runtime
panic on empty slices. Guard with an early return via
`PyBytes_FromStringAndSize(nil, 0)` which the CPython API handles correctly.
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a runtime panic when converting a zero-length Go []byte (go.Slice_byte) into Python bytes by avoiding &s[0] indexing on empty slices, and adds a regression check for issue #359.

Changes:

  • Add an early return in generated Slice_byte_to_bytes to safely create empty Python bytes for len(s) == 0.
  • Extend the _examples/gobytes example to exercise bytes(empty_slice) and assert it produces b''.
  • Update the corresponding golden output in main_test.go.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
bind/gen_slice.go Guards zero-length []byte conversions by returning an empty PyBytes object before indexing.
_examples/gobytes/test.py Adds a regression test path that converts an empty Go byte slice to Python bytes.
main_test.go Updates expected output to include the new empty-slice test prints.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread _examples/gobytes/test.py
empty = gobytes.CreateBytes(0)
print("Go empty slice: ", empty)
empty_bytes = bytes(empty)
assert empty_bytes == b"", f"expected b'', got {empty_bytes!r}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants