Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
11 changes: 7 additions & 4 deletions python/pyarrow/src/arrow/python/numpy_to_arrow.cc
Original file line number Diff line number Diff line change
Expand Up @@ -578,10 +578,13 @@ Status NumPyConverter::VisitBinary(T* builder) {
auto data = reinterpret_cast<const uint8_t*>(PyArray_DATA(arr_));

auto AppendNotNull = [builder, this](const uint8_t* data) {
// This is annoying. NumPy allows strings to have nul-terminators, so
// we must check for them here
const size_t item_size =
strnlen(reinterpret_cast<const char*>(data), static_cast<size_t>(itemsize_));
// NumPy's fixed-width bytes dtype (``S``) zero-pads values shorter than
// the item width. Strip only *trailing* null bytes so that genuine
// interior null bytes are preserved (GH-41388).
size_t item_size = static_cast<size_t>(itemsize_);
while (item_size > 0 && data[item_size - 1] == 0) {
--item_size;
}
return builder->Append(data, static_cast<int32_t>(item_size));
};

Expand Down
36 changes: 36 additions & 0 deletions python/pyarrow/tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -3894,6 +3894,42 @@ def test_binary_array_strided():
assert [b"ab", b"ef"] == arrow_array.to_pylist()


@pytest.mark.numpy
def test_binary_array_from_numpy_preserves_interior_nulls():
# GH-41388: numpy fixed-width bytes arrays with interior '\x00' bytes
# used to be truncated at the first null. NumPy only pads *trailing*
# bytes, so only trailing nulls should be stripped.
values = [b'contains \x00 interior', b'no nulls here']
np_array = np.array(values) # dtype='S20'

# Variable-length binary
arr = pa.array(np_array, type=pa.binary())
assert arr.to_pylist() == values

# Large binary uses the same converter path
arr_large = pa.array(np_array, type=pa.large_binary())
assert arr_large.to_pylist() == values

# Trailing padding on short values is still stripped (NumPy 'S' semantics)
short = np.array([b'short', b'exactlyten']) # dtype='S10'
arr_short = pa.array(short, type=pa.binary())
assert arr_short.to_pylist() == [b'short', b'exactlyten']

# Table.from_pydict goes through the same path
table = pa.Table.from_pydict({'x': np_array})
assert table['x'].to_pylist() == values

# Masked variant still preserves interior nulls
masked = pa.array(np_array, type=pa.binary(),
mask=np.array([False, False]))
assert masked.to_pylist() == values

# Strided variant still preserves interior nulls
stride = np.array([b'one \x00 one', b'two \x00 two', b'three'])
strided = pa.array(stride[::2], type=pa.binary())
assert strided.to_pylist() == [b'one \x00 one', b'three']


@pytest.mark.numpy
def test_array_invalid_mask_raises():
# ARROW-10742
Expand Down