Skip to content
Closed
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
15 changes: 10 additions & 5 deletions python/pyarrow/io.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -505,12 +505,17 @@ cdef class BufferReader(NativeFile):

if isinstance(obj, Buffer):
self.buffer = obj
elif isinstance(obj, bytes):
buf.reset(new pyarrow.PyBytesBuffer(obj))
self.buffer = wrap_buffer(buf)
else:
raise ValueError('Unable to convert value to buffer: {0}'
.format(type(obj)))
try:
view = memoryview(obj)
except TypeError:
raise ValueError('Unable to convert value to Buffer: {0}'
.format(type(obj)))
if view.ndim != 1 or view.itemsize != 1:
raise ValueError('Value must be one-dimensional and byte-sized to convert to Buffer: {0}'
.format(type(obj)))
buf.reset(new pyarrow.PyBytesBuffer(view.obj))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think that view.obj is the base object here https://github.com/python/cpython/blob/6f0eb93183519024cb360162bdd81b9faec97ba6/Objects/memoryobject.c#L43 -- can you try using something other than a bytes object in your test case?

self.buffer = wrap_buffer(buf)

self.rd_file.reset(new CBufferReader(self.buffer.buffer))
self.is_readable = 1
Expand Down
20 changes: 18 additions & 2 deletions python/pyarrow/tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,23 @@ def test_bytes_reader():

f.close()

def test_buffer_reader_init_from_buffer_object():
import array
import struct

val = b'test data'
view = memoryview(val)
f = io.BufferReader(view)
assert f.read(4) == b'test'
val = array.array('H', [32000])
assert val.itemsize == 2
with pytest.raises(ValueError):
f = io.BufferReader(val)
val = memoryview(struct.pack('b'*6, *list(range(6)))).cast('b', shape=[2,3])
assert val.ndim == 2
with pytest.raises(ValueError):
f = io.BufferReader(val)


def test_bytes_reader_non_bytes():
with pytest.raises(ValueError):
Expand Down Expand Up @@ -143,7 +160,7 @@ def test_buffer_memoryview():

result = memoryview(buf)

assert result == val
assert bytes(result) == val


def test_buffer_memoryview_is_immutable():
Expand Down Expand Up @@ -199,7 +216,6 @@ def make_buffer(bytes_obj):
assert buf == b'foo'



# ----------------------------------------------------------------------
# OS files and memory maps

Expand Down