Commits

Anonymous committed da67e5b Draft

Add a readline() implementation for _io.BytesIO which should be faster than _io._BufferedIOBase's one.

  • Participants
  • Parent commits 48cf370

Comments (0)

Files changed (2)

File pypy/module/_io/interp_bytesio.py

         self.pos += size
         return space.wrap(output)
 
+    def readline_w(self, space, w_limit=None):
+        self._check_closed(space)
+        limit = convert_size(space, w_limit)
+
+        cur_pos = self.pos
+        if limit < 0:
+            end_pos = self.string_size
+        else:
+            end_pos = min(cur_pos + limit, self.string_size)
+        while cur_pos != end_pos:
+            if self.buf[cur_pos] == '\n':
+                cur_pos += 1
+                break
+            cur_pos += 1
+
+        output = buffer2string(self.buf, self.pos, cur_pos)
+        self.pos = cur_pos
+        return space.wrap(output)
+
     def read1_w(self, space, w_size):
         return self.read_w(space, w_size)
 
 
     read = interp2app(W_BytesIO.read_w),
     read1 = interp2app(W_BytesIO.read1_w),
+    readline = interp2app(W_BytesIO.readline_w),
     readinto = interp2app(W_BytesIO.readinto_w),
     write = interp2app(W_BytesIO.write_w),
     truncate = interp2app(W_BytesIO.truncate_w),

File pypy/module/_io/test/test_bytesio.py

         b = _io.BytesIO("hello")
         b.close()
         raises(ValueError, b.readinto, bytearray("hello"))
+
+    def test_readline(self):
+        import _io
+        f = _io.BytesIO(b'abc\ndef\nxyzzy\nfoo\x00bar\nanother line')
+        assert f.readline() == b'abc\n'
+        assert f.readline(10) == b'def\n'
+        assert f.readline(2) == b'xy'
+        assert f.readline(4) == b'zzy\n'
+        assert f.readline() == b'foo\x00bar\n'
+        assert f.readline(None) == b'another line'
+        raises(TypeError, f.readline, 5.3)
+
+    def test_overread(self):
+        import _io
+        f = _io.BytesIO(b'abc')
+        assert f.readline(10) == b'abc'