summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2010-09-06 18:48:21 (GMT)
committerAntoine Pitrou <solipsis@pitrou.net>2010-09-06 18:48:21 (GMT)
commit972ee13e037432497fa003d4a786b2342a38db94 (patch)
treeab6585ebe7d0da0e725da7bd6f61a4cf739192f2 /Lib
parent6285774f06f44f04353801cc79fd2a5e67f884ec (diff)
downloadcpython-972ee13e037432497fa003d4a786b2342a38db94.zip
cpython-972ee13e037432497fa003d4a786b2342a38db94.tar.gz
cpython-972ee13e037432497fa003d4a786b2342a38db94.tar.bz2
Issue #5506: BytesIO objects now have a getbuffer() method exporting a
view of their contents without duplicating them. The view is both readable and writable.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/_pyio.py5
-rw-r--r--Lib/test/test_memoryio.py26
2 files changed, 30 insertions, 1 deletions
diff --git a/Lib/_pyio.py b/Lib/_pyio.py
index 12ae4b6..6b25640 100644
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -785,6 +785,11 @@ class BytesIO(BufferedIOBase):
raise ValueError("getvalue on closed file")
return bytes(self._buffer)
+ def getbuffer(self):
+ """Return a readable and writable view of the buffer.
+ """
+ return memoryview(self._buffer)
+
def read(self, n=None):
if self.closed:
raise ValueError("read from closed file")
diff --git a/Lib/test/test_memoryio.py b/Lib/test/test_memoryio.py
index 0decda5..dcf6d51 100644
--- a/Lib/test/test_memoryio.py
+++ b/Lib/test/test_memoryio.py
@@ -384,7 +384,31 @@ class MemoryTestMixin:
del __main__.PickleTestMemIO
-class PyBytesIOTest(MemoryTestMixin, MemorySeekTestMixin, unittest.TestCase):
+class BytesIOMixin:
+
+ def test_getbuffer(self):
+ memio = self.ioclass(b"1234567890")
+ buf = memio.getbuffer()
+ self.assertEqual(bytes(buf), b"1234567890")
+ memio.seek(5)
+ buf = memio.getbuffer()
+ self.assertEqual(bytes(buf), b"1234567890")
+ # Trying to change the size of the BytesIO while a buffer is exported
+ # raises a BufferError.
+ self.assertRaises(BufferError, memio.write, b'x' * 100)
+ self.assertRaises(BufferError, memio.truncate)
+ # Mutating the buffer updates the BytesIO
+ buf[3:6] = b"abc"
+ self.assertEqual(bytes(buf), b"123abc7890")
+ self.assertEqual(memio.getvalue(), b"123abc7890")
+ # After the buffer gets released, we can resize the BytesIO again
+ del buf
+ support.gc_collect()
+ memio.truncate()
+
+
+class PyBytesIOTest(MemoryTestMixin, MemorySeekTestMixin,
+ BytesIOMixin, unittest.TestCase):
UnsupportedOperation = pyio.UnsupportedOperation