Index: Python/pythonrun.c =================================================================== --- Python/pythonrun.c (revision 62328) +++ Python/pythonrun.c (working copy) @@ -240,11 +240,11 @@ } initmain(); /* Module __main__ */ + if (!Py_NoSiteFlag) + initsite(); /* Module site */ if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); - if (!Py_NoSiteFlag) - initsite(); /* Module site */ /* auto-thread-state API, if available */ #ifdef WITH_THREAD Index: setup.py =================================================================== --- setup.py (revision 62328) +++ setup.py (working copy) @@ -426,6 +426,8 @@ exts.append( Extension('operator', ['operator.c']) ) # _functools exts.append( Extension("_functools", ["_functoolsmodule.c"]) ) + # Memory-based IO accelerator modules + exts.append( Extension("_bytesio", ["_bytesio.c"]) ) # atexit exts.append( Extension("atexit", ["atexitmodule.c"]) ) # Python C API test module Index: Lib/io.py =================================================================== --- Lib/io.py (revision 62328) +++ Lib/io.py (working copy) @@ -491,6 +491,7 @@ terminator(s) recognized. """ # For backwards compatibility, a (slowish) readline(). + self._checkClosed() if hasattr(self, "peek"): def nreadahead(): readahead = self.peek(1) @@ -532,7 +533,7 @@ lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint. """ - if hint is None: + if hint is None or hint <= 0: return list(self) n = 0 lines = [] @@ -727,6 +728,8 @@ if pos is None: pos = self.tell() + # XXX: Should seek() be used, instead of passing the position + # XXX directly to truncate? return self.raw.truncate(pos) ### Flush and close ### @@ -766,7 +769,7 @@ return self.raw.isatty() -class BytesIO(BufferedIOBase): +class _BytesIO(BufferedIOBase): """Buffered I/O implementation using an in-memory bytes buffer.""" @@ -780,13 +783,19 @@ def getvalue(self): """getvalue() -> bytes Return the bytes value (contents) of the buffer """ + if self.closed: + raise ValueError("getvalue on closed file") return bytes(self._buffer) def read(self, n=None): + if self.closed: + raise ValueError("read from closed file") if n is None: n = -1 if n < 0: n = len(self._buffer) + if len(self._buffer) <= self._pos: + return self._buffer[:0] newpos = min(len(self._buffer), self._pos + n) b = self._buffer[self._pos : newpos] self._pos = newpos @@ -803,6 +812,8 @@ if isinstance(b, str): raise TypeError("can't write str to binary stream") n = len(b) + if n == 0: + return 0 newpos = self._pos + n if newpos > len(self._buffer): # Inserts null bytes between the current end of the file @@ -814,28 +825,38 @@ return n def seek(self, pos, whence=0): + if self.closed: + raise ValueError("seek on closed file") try: pos = pos.__index__() except AttributeError as err: raise TypeError("an integer is required") from err if whence == 0: self._pos = max(0, pos) + if pos < 0: + raise ValueError("negative seek position %r" % (pos,)) elif whence == 1: self._pos = max(0, self._pos + pos) elif whence == 2: self._pos = max(0, len(self._buffer) + pos) else: - raise IOError("invalid whence value") + raise ValueError("invalid whence value") return self._pos def tell(self): + if self.closed: + raise ValueError("tell on closed file") return self._pos def truncate(self, pos=None): + if self.closed: + raise ValueError("truncate on closed file") if pos is None: pos = self._pos + elif pos < 0: + raise ValueError("negative truncate position %r" % (pos,)) del self._buffer[pos:] - return pos + return self.seek(pos) def readable(self): return True @@ -846,7 +867,17 @@ def seekable(self): return True +# Use the faster implementation of BytesIO if available +try: + import _bytesio + class BytesIO(_bytesio._BytesIO, BufferedIOBase): + __doc__ = _bytesio._BytesIO.__doc__ + +except ImportError: + BytesIO = _BytesIO + + class BufferedReader(_BufferedIOMixin): """BufferedReader(raw[, buffer_size]) @@ -981,6 +1012,12 @@ raise BlockingIOError(e.errno, e.strerror, overage) return written + def truncate(self, pos=None): + self.flush() + if pos is None: + pos = self.raw.tell() + return self.raw.truncate(pos) + def flush(self): if self.closed: raise ValueError("flush of closed file") @@ -1102,6 +1139,13 @@ else: return self.raw.tell() - len(self._read_buf) + def truncate(self, pos=None): + if pos is None: + pos = self.tell() + # Use seek to flush the read buffer. + self.seek(pos) + return BufferedWriter.truncate(self) + def read(self, n=None): if n is None: n = -1 @@ -1150,11 +1194,7 @@ def truncate(self, pos: int = None) -> int: """truncate(pos: int = None) -> int. Truncate size to pos.""" - self.flush() - if pos is None: - pos = self.tell() - self.seek(pos) - return self.buffer.truncate() + self._unsupported("truncate") def readline(self) -> str: """readline() -> str. Read until newline or EOF. @@ -1354,6 +1394,12 @@ def seekable(self): return self._seekable + def readable(self): + return self.buffer.readable() + + def writable(self): + return self.buffer.writable() + def flush(self): self.buffer.flush() self._telling = self._seekable @@ -1547,7 +1593,16 @@ finally: decoder.setstate(saved_state) + def truncate(self, pos=None): + self.flush() + if pos is None: + pos = self.tell() + self.seek(pos) + return self.buffer.truncate() + def seek(self, cookie, whence=0): + if self.closed: + raise ValueError("tell on closed file") if not self._seekable: raise IOError("underlying stream is not seekable") if whence == 1: # seek relative to current position @@ -1634,6 +1689,8 @@ return line def readline(self, limit=None): + if self.closed: + raise ValueError("read from closed file") if limit is None: limit = -1 Index: Lib/test/test_io.py =================================================================== --- Lib/test/test_io.py (revision 62328) +++ Lib/test/test_io.py (working copy) @@ -98,7 +98,7 @@ self.assertEqual(f.seek(-1, 2), 13) self.assertEqual(f.tell(), 13) self.assertEqual(f.truncate(12), 12) - self.assertEqual(f.tell(), 13) + self.assertEqual(f.tell(), 12) self.assertRaises(TypeError, f.seek, 0.0) def read_ops(self, f, buffered=False): @@ -143,7 +143,7 @@ self.assertEqual(f.tell(), self.LARGE + 2) self.assertEqual(f.seek(0, 2), self.LARGE + 2) self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) - self.assertEqual(f.tell(), self.LARGE + 2) + self.assertEqual(f.tell(), self.LARGE + 1) self.assertEqual(f.seek(0, 2), self.LARGE + 1) self.assertEqual(f.seek(-1, 2), self.LARGE) self.assertEqual(f.read(2), b"x") @@ -727,6 +727,7 @@ txt.write("BB\nCCC\n") txt.write("X\rY\r\nZ") txt.flush() + self.assertEquals(buf.closed, False) self.assertEquals(buf.getvalue(), expected) def testNewlines(self): @@ -807,7 +808,8 @@ txt = io.TextIOWrapper(buf, encoding="ascii", newline=newline) txt.write(data) txt.close() - self.assertEquals(buf.getvalue(), expected) + self.assertEquals(buf.closed, True) + self.assertRaises(ValueError, buf.getvalue) finally: os.linesep = save_linesep Index: Lib/test/test_mimetools.py =================================================================== --- Lib/test/test_mimetools.py (revision 62328) +++ Lib/test/test_mimetools.py (working copy) @@ -58,7 +58,7 @@ s.add(nb) def test_message(self): - msg = mimetools.Message(io.StringIO(msgtext1)) + msg = mimetools.Message(io.StringIO(str(msgtext1))) self.assertEqual(msg.gettype(), "text/plain") self.assertEqual(msg.getmaintype(), "text") self.assertEqual(msg.getsubtype(), "plain") Index: Lib/test/test_StringIO.py (deleted) =================================================================== Index: Lib/test/test_largefile.py =================================================================== --- Lib/test/test_largefile.py (revision 62328) +++ Lib/test/test_largefile.py (working copy) @@ -120,14 +120,15 @@ newsize -= 1 f.seek(42) f.truncate(newsize) - self.assertEqual(f.tell(), 42) # else pointer moved + self.assertEqual(f.tell(), newsize) # else wasn't truncated f.seek(0, 2) - self.assertEqual(f.tell(), newsize) # else wasn't truncated + self.assertEqual(f.tell(), newsize) # XXX truncate(larger than true size) is ill-defined # across platform; cut it waaaaay back f.seek(0) f.truncate(1) - self.assertEqual(f.tell(), 0) # else pointer moved + self.assertEqual(f.tell(), 1) # else pointer moved + f.seek(0) self.assertEqual(len(f.read()), 1) # else wasn't truncated def test_main(): Index: Modules/cStringIO.c (deleted) =================================================================== Index: Modules/_fileio.c =================================================================== --- Modules/_fileio.c (revision 62328) +++ Modules/_fileio.c (working copy) @@ -552,11 +552,10 @@ PyErr_SetString(PyExc_TypeError, "an integer is required"); return NULL; } -#if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLong(posobj); +#if defined(HAVE_LARGEFILE_SUPPORT) + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif if (PyErr_Occurred()) return NULL; @@ -572,10 +571,10 @@ if (res < 0) return PyErr_SetFromErrno(PyExc_IOError); -#if !defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLong(res); -#else +#if defined(HAVE_LARGEFILE_SUPPORT) return PyLong_FromLongLong(res); +#else + return PyLong_FromLong(res); #endif } @@ -622,49 +621,30 @@ return NULL; if (posobj == Py_None || posobj == NULL) { + /* Get the current position. */ posobj = portable_lseek(fd, NULL, 1); if (posobj == NULL) - return NULL; + return NULL; } else { - Py_INCREF(posobj); + /* Move to the position to be truncated. */ + posobj = portable_lseek(fd, posobj, 0); } -#if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLong(posobj); +#if defined(HAVE_LARGEFILE_SUPPORT) + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) { - Py_DECREF(posobj); + if (PyErr_Occurred()) return NULL; - } #ifdef MS_WINDOWS /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, so don't even try using it. */ { HANDLE hFile; - PyObject *pos2, *oldposobj; - /* store the current position */ - oldposobj = portable_lseek(self->fd, NULL, 1); - if (oldposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - - /* Have to move current pos to desired endpoint on Windows. */ - errno = 0; - pos2 = portable_lseek(fd, posobj, SEEK_SET); - if (pos2 == NULL) { - Py_DECREF(posobj); - Py_DECREF(oldposobj); - return NULL; - } - Py_DECREF(pos2); - /* Truncate. Note that this may grow the file! */ Py_BEGIN_ALLOW_THREADS errno = 0; @@ -676,18 +656,6 @@ errno = EACCES; } Py_END_ALLOW_THREADS - - if (ret == 0) { - /* Move to the previous position in the file */ - pos2 = portable_lseek(fd, oldposobj, SEEK_SET); - if (pos2 == NULL) { - Py_DECREF(posobj); - Py_DECREF(oldposobj); - return NULL; - } - } - Py_DECREF(pos2); - Py_DECREF(oldposobj); } #else Py_BEGIN_ALLOW_THREADS @@ -697,7 +665,6 @@ #endif /* !MS_WINDOWS */ if (ret != 0) { - Py_DECREF(posobj); PyErr_SetFromErrno(PyExc_IOError); return NULL; } @@ -791,7 +758,8 @@ PyDoc_STRVAR(truncate_doc, "truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" "\n" -"Size defaults to the current file position, as returned by tell()."); +"Size defaults to the current file position, as returned by tell()." +"The current file position is changed to the value of size."); #endif PyDoc_STRVAR(tell_doc,