Skip to content

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

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

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

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

Copy link
Copy Markdown
Member

Fixes #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.

Copilot AI left a comment

Copy link
Copy Markdown

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}"
@b-long b-long marked this pull request as ready for review June 29, 2026 01:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

2 participants