Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 1 | """New I/O library conforming to PEP 3116. |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 3 | This is a prototype; hopefully eventually some of this will be |
| 4 | reimplemented in C. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 5 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 6 | Conformance of alternative implementations: all arguments are intended |
| 7 | to be positional-only except the arguments of the open() function. |
| 8 | Argument names except those of the open() function are not part of the |
| 9 | specification. Instance variables and methods whose name starts with |
| 10 | a leading underscore are not part of the specification (except "magic" |
| 11 | names like __iter__). Only the top-level names listed in the __all__ |
| 12 | variable are part of the specification. |
Guido van Rossum | c819dea | 2007-03-15 18:59:31 +0000 | [diff] [blame] | 13 | |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 14 | XXX edge cases when switching between reading/writing |
Guido van Rossum | c819dea | 2007-03-15 18:59:31 +0000 | [diff] [blame] | 15 | XXX need to default buffer size to 1 if isatty() |
| 16 | XXX need to support 1 meaning line-buffered |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 17 | XXX don't use assert to validate input requirements |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 18 | XXX whenever an argument is None, use the default value |
| 19 | XXX read/write ops should check readable/writable |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 20 | """ |
| 21 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 22 | __author__ = ("Guido van Rossum <guido@python.org>, " |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 23 | "Mike Verdone <mike.verdone@gmail.com>, " |
| 24 | "Mark Russell <mark.russell@zen.co.uk>") |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 25 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 26 | __all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO", |
| 27 | "SocketIO", "BytesIO", "StringIO", "BufferedIOBase", |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 28 | "BufferedReader", "BufferedWriter", "BufferedRWPair", |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 29 | "BufferedRandom", "TextIOBase", "TextIOWrapper"] |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 30 | |
| 31 | import os |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 32 | import sys |
| 33 | import codecs |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 34 | import _fileio |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 35 | import warnings |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 36 | |
Guido van Rossum | 0dd32e2 | 2007-04-11 05:40:58 +0000 | [diff] [blame] | 37 | try: |
| 38 | import cPickle as pickle |
| 39 | except ImportError: |
| 40 | import pickle |
| 41 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 42 | # XXX Shouldn't we use st_blksize whenever we can? |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 43 | DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 44 | |
| 45 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 46 | class BlockingIOError(IOError): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 47 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 48 | """Exception raised when I/O would block on a non-blocking I/O stream.""" |
| 49 | |
| 50 | def __init__(self, errno, strerror, characters_written=0): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 51 | IOError.__init__(self, errno, strerror) |
| 52 | self.characters_written = characters_written |
| 53 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 54 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 55 | def open(file, mode="r", buffering=None, *, encoding=None, newline=None): |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 56 | """Replacement for the built-in open function. |
| 57 | |
| 58 | Args: |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 59 | file: string giving the name of the file to be opened; |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 60 | or integer file descriptor of the file to be wrapped (*). |
| 61 | mode: optional mode string; see below. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 62 | buffering: optional int >= 0 giving the buffer size; values |
| 63 | can be: 0 = unbuffered, 1 = line buffered, |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 64 | larger = fully buffered. |
| 65 | Keywords (for text modes only; *must* be given as keyword arguments): |
| 66 | encoding: optional string giving the text encoding. |
| 67 | newline: optional newlines specifier; must be None, '\n' or '\r\n'; |
| 68 | specifies the line ending expected on input and written on |
| 69 | output. If None, use universal newlines on input and |
| 70 | use os.linesep on output. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 71 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 72 | (*) If a file descriptor is given, it is closed when the returned |
| 73 | I/O object is closed. If you don't want this to happen, use |
| 74 | os.dup() to create a duplicate file descriptor. |
| 75 | |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 76 | Mode strings characters: |
| 77 | 'r': open for reading (default) |
| 78 | 'w': open for writing, truncating the file first |
| 79 | 'a': open for writing, appending to the end if the file exists |
| 80 | 'b': binary mode |
| 81 | 't': text mode (default) |
| 82 | '+': open a disk file for updating (implies reading and writing) |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 83 | 'U': universal newline mode (for backwards compatibility) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 84 | |
| 85 | Constraints: |
| 86 | - encoding must not be given when a binary mode is given |
| 87 | - buffering must not be zero when a text mode is given |
| 88 | |
| 89 | Returns: |
| 90 | Depending on the mode and buffering arguments, either a raw |
| 91 | binary stream, a buffered binary stream, or a buffered text |
| 92 | stream, open for reading and/or writing. |
| 93 | """ |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 94 | # XXX Don't use asserts for these checks; raise TypeError or ValueError |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 95 | assert isinstance(file, (basestring, int)), repr(file) |
| 96 | assert isinstance(mode, basestring), repr(mode) |
| 97 | assert buffering is None or isinstance(buffering, int), repr(buffering) |
| 98 | assert encoding is None or isinstance(encoding, basestring), repr(encoding) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 99 | modes = set(mode) |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 100 | if modes - set("arwb+tU") or len(mode) > len(modes): |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 101 | raise ValueError("invalid mode: %r" % mode) |
| 102 | reading = "r" in modes |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 103 | writing = "w" in modes |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 104 | appending = "a" in modes |
| 105 | updating = "+" in modes |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 106 | text = "t" in modes |
| 107 | binary = "b" in modes |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 108 | if "U" in modes and not (reading or writing or appending): |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 109 | reading = True |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 110 | if text and binary: |
| 111 | raise ValueError("can't have text and binary mode at once") |
| 112 | if reading + writing + appending > 1: |
| 113 | raise ValueError("can't have read/write/append mode at once") |
| 114 | if not (reading or writing or appending): |
| 115 | raise ValueError("must have exactly one of read/write/append mode") |
| 116 | if binary and encoding is not None: |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 117 | raise ValueError("binary mode doesn't take an encoding argument") |
| 118 | if binary and newline is not None: |
| 119 | raise ValueError("binary mode doesn't take a newline argument") |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 120 | raw = FileIO(file, |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 121 | (reading and "r" or "") + |
| 122 | (writing and "w" or "") + |
| 123 | (appending and "a" or "") + |
| 124 | (updating and "+" or "")) |
| 125 | if buffering is None: |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 126 | buffering = DEFAULT_BUFFER_SIZE |
| 127 | # XXX Should default to line buffering if os.isatty(raw.fileno()) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 128 | try: |
| 129 | bs = os.fstat(raw.fileno()).st_blksize |
| 130 | except (os.error, AttributeError): |
Guido van Rossum | bb09b21 | 2007-03-18 03:36:28 +0000 | [diff] [blame] | 131 | pass |
| 132 | else: |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 133 | if bs > 1: |
| 134 | buffering = bs |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 135 | if buffering < 0: |
| 136 | raise ValueError("invalid buffering size") |
| 137 | if buffering == 0: |
| 138 | if binary: |
| 139 | return raw |
| 140 | raise ValueError("can't have unbuffered text I/O") |
| 141 | if updating: |
| 142 | buffer = BufferedRandom(raw, buffering) |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 143 | elif writing or appending: |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 144 | buffer = BufferedWriter(raw, buffering) |
| 145 | else: |
| 146 | assert reading |
| 147 | buffer = BufferedReader(raw, buffering) |
| 148 | if binary: |
| 149 | return buffer |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 150 | return TextIOWrapper(buffer, encoding, newline) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 151 | |
| 152 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 153 | class IOBase: |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 154 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 155 | """Base class for all I/O classes. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 156 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 157 | This class provides dummy implementations for many methods that |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 158 | derived classes can override selectively; the default |
| 159 | implementations represent a file that cannot be read, written or |
| 160 | seeked. |
| 161 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 162 | This does not define read(), readinto() and write(), nor |
| 163 | readline() and friends, since their signatures vary per layer. |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 164 | |
| 165 | Not that calling any method (even inquiries) on a closed file is |
| 166 | undefined. Implementations may raise IOError in this case. |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 167 | """ |
| 168 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 169 | ### Internal ### |
| 170 | |
| 171 | def _unsupported(self, name: str) -> IOError: |
| 172 | """Internal: raise an exception for unsupported operations.""" |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 173 | raise IOError("%s.%s() not supported" % (self.__class__.__name__, |
| 174 | name)) |
| 175 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 176 | ### Positioning ### |
| 177 | |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 178 | def seek(self, pos: int, whence: int = 0) -> int: |
| 179 | """seek(pos: int, whence: int = 0) -> int. Change stream position. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 180 | |
| 181 | Seek to byte offset pos relative to position indicated by whence: |
| 182 | 0 Start of stream (the default). pos should be >= 0; |
| 183 | 1 Current position - whence may be negative; |
| 184 | 2 End of stream - whence usually negative. |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 185 | Returns the new absolute position. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 186 | """ |
| 187 | self._unsupported("seek") |
| 188 | |
| 189 | def tell(self) -> int: |
| 190 | """tell() -> int. Return current stream position.""" |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 191 | return self.seek(0, 1) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 192 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 193 | def truncate(self, pos: int = None) -> int: |
| 194 | """truncate(size: int = None) -> int. Truncate file to size bytes. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 195 | |
| 196 | Size defaults to the current IO position as reported by tell(). |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 197 | Returns the new size. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 198 | """ |
| 199 | self._unsupported("truncate") |
| 200 | |
| 201 | ### Flush and close ### |
| 202 | |
| 203 | def flush(self) -> None: |
| 204 | """flush() -> None. Flushes write buffers, if applicable. |
| 205 | |
| 206 | This is a no-op for read-only and non-blocking streams. |
| 207 | """ |
| 208 | |
| 209 | __closed = False |
| 210 | |
| 211 | def close(self) -> None: |
| 212 | """close() -> None. Flushes and closes the IO object. |
| 213 | |
| 214 | This must be idempotent. It should also set a flag for the |
| 215 | 'closed' property (see below) to test. |
| 216 | """ |
| 217 | if not self.__closed: |
| 218 | self.__closed = True |
| 219 | self.flush() |
| 220 | |
| 221 | def __del__(self) -> None: |
| 222 | """Destructor. Calls close().""" |
| 223 | # The try/except block is in case this is called at program |
| 224 | # exit time, when it's possible that globals have already been |
| 225 | # deleted, and then the close() call might fail. Since |
| 226 | # there's nothing we can do about such failures and they annoy |
| 227 | # the end users, we suppress the traceback. |
| 228 | try: |
| 229 | self.close() |
| 230 | except: |
| 231 | pass |
| 232 | |
| 233 | ### Inquiries ### |
| 234 | |
| 235 | def seekable(self) -> bool: |
| 236 | """seekable() -> bool. Return whether object supports random access. |
| 237 | |
| 238 | If False, seek(), tell() and truncate() will raise IOError. |
| 239 | This method may need to do a test seek(). |
| 240 | """ |
| 241 | return False |
| 242 | |
| 243 | def readable(self) -> bool: |
| 244 | """readable() -> bool. Return whether object was opened for reading. |
| 245 | |
| 246 | If False, read() will raise IOError. |
| 247 | """ |
| 248 | return False |
| 249 | |
| 250 | def writable(self) -> bool: |
| 251 | """writable() -> bool. Return whether object was opened for writing. |
| 252 | |
| 253 | If False, write() and truncate() will raise IOError. |
| 254 | """ |
| 255 | return False |
| 256 | |
| 257 | @property |
| 258 | def closed(self): |
| 259 | """closed: bool. True iff the file has been closed. |
| 260 | |
| 261 | For backwards compatibility, this is a property, not a predicate. |
| 262 | """ |
| 263 | return self.__closed |
| 264 | |
| 265 | ### Context manager ### |
| 266 | |
| 267 | def __enter__(self) -> "IOBase": # That's a forward reference |
| 268 | """Context management protocol. Returns self.""" |
| 269 | return self |
| 270 | |
| 271 | def __exit__(self, *args) -> None: |
| 272 | """Context management protocol. Calls close()""" |
| 273 | self.close() |
| 274 | |
| 275 | ### Lower-level APIs ### |
| 276 | |
| 277 | # XXX Should these be present even if unimplemented? |
| 278 | |
| 279 | def fileno(self) -> int: |
| 280 | """fileno() -> int. Returns underlying file descriptor if one exists. |
| 281 | |
| 282 | Raises IOError if the IO object does not use a file descriptor. |
| 283 | """ |
| 284 | self._unsupported("fileno") |
| 285 | |
| 286 | def isatty(self) -> bool: |
| 287 | """isatty() -> int. Returns whether this is an 'interactive' stream. |
| 288 | |
| 289 | Returns False if we don't know. |
| 290 | """ |
| 291 | return False |
| 292 | |
| 293 | |
| 294 | class RawIOBase(IOBase): |
| 295 | |
| 296 | """Base class for raw binary I/O. |
| 297 | |
| 298 | The read() method is implemented by calling readinto(); derived |
| 299 | classes that want to support read() only need to implement |
| 300 | readinto() as a primitive operation. In general, readinto() |
| 301 | can be more efficient than read(). |
| 302 | |
| 303 | (It would be tempting to also provide an implementation of |
| 304 | readinto() in terms of read(), in case the latter is a more |
| 305 | suitable primitive operation, but that would lead to nasty |
| 306 | recursion in case a subclass doesn't implement either.) |
| 307 | """ |
| 308 | |
| 309 | def read(self, n: int) -> bytes: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 310 | """read(n: int) -> bytes. Read and return up to n bytes. |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 311 | |
| 312 | Returns an empty bytes array on EOF, or None if the object is |
| 313 | set not to block and has no data to read. |
| 314 | """ |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 315 | b = bytes(n.__index__()) |
Guido van Rossum | 00efead | 2007-03-07 05:23:25 +0000 | [diff] [blame] | 316 | n = self.readinto(b) |
| 317 | del b[n:] |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 318 | return b |
| 319 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 320 | def readinto(self, b: bytes) -> int: |
| 321 | """readinto(b: bytes) -> int. Read up to len(b) bytes into b. |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 322 | |
| 323 | Returns number of bytes read (0 for EOF), or None if the object |
| 324 | is set not to block as has no data to read. |
| 325 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 326 | self._unsupported("readinto") |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 327 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 328 | def write(self, b: bytes) -> int: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 329 | """write(b: bytes) -> int. Write the given buffer to the IO stream. |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 330 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 331 | Returns the number of bytes written, which may be less than len(b). |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 332 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 333 | self._unsupported("write") |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 334 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 335 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 336 | class FileIO(_fileio._FileIO, RawIOBase): |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 337 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 338 | """Raw I/O implementation for OS files. |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 339 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 340 | This multiply inherits from _FileIO and RawIOBase to make |
| 341 | isinstance(io.FileIO(), io.RawIOBase) return True without |
| 342 | requiring that _fileio._FileIO inherits from io.RawIOBase (which |
| 343 | would be hard to do since _fileio.c is written in C). |
| 344 | """ |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 345 | |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 346 | def close(self): |
| 347 | _fileio._FileIO.close(self) |
| 348 | RawIOBase.close(self) |
| 349 | |
Guido van Rossum | a9e2024 | 2007-03-08 00:43:48 +0000 | [diff] [blame] | 350 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 351 | class SocketIO(RawIOBase): |
| 352 | |
| 353 | """Raw I/O implementation for stream sockets.""" |
| 354 | |
Guido van Rossum | 17e43e5 | 2007-02-27 15:45:13 +0000 | [diff] [blame] | 355 | # XXX More docs |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 356 | # XXX Hook this up to socket.py |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 357 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 358 | def __init__(self, sock, mode): |
| 359 | assert mode in ("r", "w", "rw") |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 360 | RawIOBase.__init__(self) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 361 | self._sock = sock |
| 362 | self._mode = mode |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 363 | |
| 364 | def readinto(self, b): |
| 365 | return self._sock.recv_into(b) |
| 366 | |
| 367 | def write(self, b): |
| 368 | return self._sock.send(b) |
| 369 | |
| 370 | def close(self): |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 371 | if not self.closed: |
| 372 | RawIOBase.close() |
| 373 | self._sock.close() |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 374 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 375 | def readable(self): |
| 376 | return "r" in self._mode |
| 377 | |
| 378 | def writable(self): |
| 379 | return "w" in self._mode |
| 380 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 381 | def fileno(self): |
| 382 | return self._sock.fileno() |
Neal Norwitz | 8b41c3d | 2007-02-27 06:26:14 +0000 | [diff] [blame] | 383 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 384 | |
Guido van Rossum | cce92b2 | 2007-04-10 14:41:39 +0000 | [diff] [blame] | 385 | class BufferedIOBase(IOBase): |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 386 | |
| 387 | """Base class for buffered IO objects. |
| 388 | |
| 389 | The main difference with RawIOBase is that the read() method |
| 390 | supports omitting the size argument, and does not have a default |
| 391 | implementation that defers to readinto(). |
| 392 | |
| 393 | In addition, read(), readinto() and write() may raise |
| 394 | BlockingIOError if the underlying raw stream is in non-blocking |
| 395 | mode and not ready; unlike their raw counterparts, they will never |
| 396 | return None. |
| 397 | |
| 398 | A typical implementation should not inherit from a RawIOBase |
| 399 | implementation, but wrap one. |
| 400 | """ |
| 401 | |
| 402 | def read(self, n: int = -1) -> bytes: |
| 403 | """read(n: int = -1) -> bytes. Read and return up to n bytes. |
| 404 | |
| 405 | If the argument is omitted, or negative, reads and returns all |
| 406 | data until EOF. |
| 407 | |
| 408 | If the argument is positive, and the underlying raw stream is |
| 409 | not 'interactive', multiple raw reads may be issued to satisfy |
| 410 | the byte count (unless EOF is reached first). But for |
| 411 | interactive raw streams (XXX and for pipes?), at most one raw |
| 412 | read will be issued, and a short result does not imply that |
| 413 | EOF is imminent. |
| 414 | |
| 415 | Returns an empty bytes array on EOF. |
| 416 | |
| 417 | Raises BlockingIOError if the underlying raw stream has no |
| 418 | data at the moment. |
| 419 | """ |
| 420 | self._unsupported("read") |
| 421 | |
| 422 | def readinto(self, b: bytes) -> int: |
| 423 | """readinto(b: bytes) -> int. Read up to len(b) bytes into b. |
| 424 | |
| 425 | Like read(), this may issue multiple reads to the underlying |
| 426 | raw stream, unless the latter is 'interactive' (XXX or a |
| 427 | pipe?). |
| 428 | |
| 429 | Returns the number of bytes read (0 for EOF). |
| 430 | |
| 431 | Raises BlockingIOError if the underlying raw stream has no |
| 432 | data at the moment. |
| 433 | """ |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 434 | data = self.read(len(b)) |
| 435 | n = len(data) |
| 436 | b[:n] = data |
| 437 | return n |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 438 | |
| 439 | def write(self, b: bytes) -> int: |
| 440 | """write(b: bytes) -> int. Write the given buffer to the IO stream. |
| 441 | |
| 442 | Returns the number of bytes written, which is never less than |
| 443 | len(b). |
| 444 | |
| 445 | Raises BlockingIOError if the buffer is full and the |
| 446 | underlying raw stream cannot accept more data at the moment. |
| 447 | """ |
| 448 | self._unsupported("write") |
| 449 | |
| 450 | |
| 451 | class _BufferedIOMixin(BufferedIOBase): |
| 452 | |
| 453 | """A mixin implementation of BufferedIOBase with an underlying raw stream. |
| 454 | |
| 455 | This passes most requests on to the underlying raw stream. It |
| 456 | does *not* provide implementations of read(), readinto() or |
| 457 | write(). |
| 458 | """ |
| 459 | |
| 460 | def __init__(self, raw): |
| 461 | self.raw = raw |
| 462 | |
| 463 | ### Positioning ### |
| 464 | |
| 465 | def seek(self, pos, whence=0): |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 466 | return self.raw.seek(pos, whence) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 467 | |
| 468 | def tell(self): |
| 469 | return self.raw.tell() |
| 470 | |
| 471 | def truncate(self, pos=None): |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 472 | return self.raw.truncate(pos) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 473 | |
| 474 | ### Flush and close ### |
| 475 | |
| 476 | def flush(self): |
| 477 | self.raw.flush() |
| 478 | |
| 479 | def close(self): |
| 480 | self.flush() |
| 481 | self.raw.close() |
| 482 | |
| 483 | ### Inquiries ### |
| 484 | |
| 485 | def seekable(self): |
| 486 | return self.raw.seekable() |
| 487 | |
| 488 | def readable(self): |
| 489 | return self.raw.readable() |
| 490 | |
| 491 | def writable(self): |
| 492 | return self.raw.writable() |
| 493 | |
| 494 | @property |
| 495 | def closed(self): |
| 496 | return self.raw.closed |
| 497 | |
| 498 | ### Lower-level APIs ### |
| 499 | |
| 500 | def fileno(self): |
| 501 | return self.raw.fileno() |
| 502 | |
| 503 | def isatty(self): |
| 504 | return self.raw.isatty() |
| 505 | |
| 506 | |
| 507 | class _MemoryIOMixin(BufferedIOBase): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 508 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 509 | # XXX docstring |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 510 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 511 | def __init__(self, buffer): |
| 512 | self._buffer = buffer |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 513 | self._pos = 0 |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 514 | |
| 515 | def getvalue(self): |
| 516 | return self._buffer |
| 517 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 518 | def read(self, n=-1): |
| 519 | assert n is not None |
| 520 | if n < 0: |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 521 | n = len(self._buffer) |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 522 | newpos = min(len(self._buffer), self._pos + n) |
| 523 | b = self._buffer[self._pos : newpos] |
| 524 | self._pos = newpos |
| 525 | return b |
| 526 | |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 527 | def write(self, b): |
| 528 | n = len(b) |
| 529 | newpos = self._pos + n |
| 530 | self._buffer[self._pos:newpos] = b |
| 531 | self._pos = newpos |
| 532 | return n |
| 533 | |
| 534 | def seek(self, pos, whence=0): |
| 535 | if whence == 0: |
| 536 | self._pos = max(0, pos) |
| 537 | elif whence == 1: |
| 538 | self._pos = max(0, self._pos + pos) |
| 539 | elif whence == 2: |
| 540 | self._pos = max(0, len(self._buffer) + pos) |
| 541 | else: |
| 542 | raise IOError("invalid whence value") |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 543 | return self._pos |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 544 | |
| 545 | def tell(self): |
| 546 | return self._pos |
| 547 | |
| 548 | def truncate(self, pos=None): |
| 549 | if pos is None: |
| 550 | pos = self._pos |
| 551 | else: |
| 552 | self._pos = max(0, pos) |
| 553 | del self._buffer[pos:] |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 554 | return pos |
Guido van Rossum | 28524c7 | 2007-02-27 05:47:44 +0000 | [diff] [blame] | 555 | |
| 556 | def readable(self): |
| 557 | return True |
| 558 | |
| 559 | def writable(self): |
| 560 | return True |
| 561 | |
| 562 | def seekable(self): |
| 563 | return True |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 564 | |
| 565 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 566 | class BytesIO(_MemoryIOMixin): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 567 | |
| 568 | """Buffered I/O implementation using a bytes buffer, like StringIO.""" |
| 569 | |
| 570 | # XXX More docs |
| 571 | |
| 572 | def __init__(self, inital_bytes=None): |
| 573 | buffer = b"" |
| 574 | if inital_bytes is not None: |
| 575 | buffer += inital_bytes |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 576 | _MemoryIOMixin.__init__(self, buffer) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 577 | |
| 578 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 579 | # XXX This should inherit from TextIOBase |
| 580 | class StringIO(_MemoryIOMixin): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 581 | |
| 582 | """Buffered I/O implementation using a string buffer, like StringIO.""" |
| 583 | |
| 584 | # XXX More docs |
| 585 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 586 | # Reuses the same code as BytesIO, just with a string rather that |
| 587 | # bytes as the _buffer value. |
| 588 | |
| 589 | # XXX This doesn't work; _MemoryIOMixin's write() and truncate() |
| 590 | # methods assume the buffer is mutable. Simply redefining those |
| 591 | # to use slice concatenation will make it awfully slow (in fact, |
| 592 | # quadratic in the number of write() calls). |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 593 | |
| 594 | def __init__(self, inital_string=None): |
| 595 | buffer = "" |
| 596 | if inital_string is not None: |
| 597 | buffer += inital_string |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 598 | _MemoryIOMixin.__init__(self, buffer) |
| 599 | |
| 600 | def readinto(self, b: bytes) -> int: |
| 601 | self._unsupported("readinto") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 602 | |
| 603 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 604 | class BufferedReader(_BufferedIOMixin): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 605 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 606 | """Buffer for a readable sequential RawIO object.""" |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 607 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 608 | def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 609 | """Create a new buffered reader using the given readable raw IO object. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 610 | """ |
| 611 | assert raw.readable() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 612 | _BufferedIOMixin.__init__(self, raw) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 613 | self._read_buf = b"" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 614 | self.buffer_size = buffer_size |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 615 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 616 | def read(self, n=-1): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 617 | """Read n bytes. |
| 618 | |
| 619 | Returns exactly n bytes of data unless the underlying raw IO |
| 620 | stream reaches EOF of if the call would block in non-blocking |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 621 | mode. If n is negative, read until EOF or until read() would |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 622 | block. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 623 | """ |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 624 | assert n is not None |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 625 | nodata_val = b"" |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 626 | while n < 0 or len(self._read_buf) < n: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 627 | to_read = max(self.buffer_size, |
| 628 | n if n is not None else 2*len(self._read_buf)) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 629 | current = self.raw.read(to_read) |
| 630 | |
| 631 | if current in (b"", None): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 632 | nodata_val = current |
| 633 | break |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 634 | self._read_buf += current |
| 635 | if self._read_buf: |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 636 | if n < 0: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 637 | n = len(self._read_buf) |
| 638 | out = self._read_buf[:n] |
| 639 | self._read_buf = self._read_buf[n:] |
| 640 | else: |
| 641 | out = nodata_val |
| 642 | return out |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 643 | |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 644 | def tell(self): |
| 645 | return self.raw.tell() - len(self._read_buf) |
| 646 | |
| 647 | def seek(self, pos, whence=0): |
| 648 | if whence == 1: |
| 649 | pos -= len(self._read_buf) |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 650 | pos = self.raw.seek(pos, whence) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 651 | self._read_buf = b"" |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 652 | return pos |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 653 | |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 654 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 655 | class BufferedWriter(_BufferedIOMixin): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 656 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 657 | # XXX docstring |
| 658 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 659 | def __init__(self, raw, |
| 660 | buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 661 | assert raw.writable() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 662 | _BufferedIOMixin.__init__(self, raw) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 663 | self.buffer_size = buffer_size |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 664 | self.max_buffer_size = (2*buffer_size |
| 665 | if max_buffer_size is None |
| 666 | else max_buffer_size) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 667 | self._write_buf = b"" |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 668 | |
| 669 | def write(self, b): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 670 | # XXX we can implement some more tricks to try and avoid partial writes |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 671 | if len(self._write_buf) > self.buffer_size: |
| 672 | # We're full, so let's pre-flush the buffer |
| 673 | try: |
| 674 | self.flush() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 675 | except BlockingIOError as e: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 676 | # We can't accept anything else. |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 677 | # XXX Why not just let the exception pass through? |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 678 | raise BlockingIOError(e.errno, e.strerror, 0) |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 679 | self._write_buf.extend(b) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 680 | if len(self._write_buf) > self.buffer_size: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 681 | try: |
| 682 | self.flush() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 683 | except BlockingIOError as e: |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 684 | if (len(self._write_buf) > self.max_buffer_size): |
| 685 | # We've hit max_buffer_size. We have to accept a partial |
| 686 | # write and cut back our buffer. |
| 687 | overage = len(self._write_buf) - self.max_buffer_size |
| 688 | self._write_buf = self._write_buf[:self.max_buffer_size] |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 689 | raise BlockingIOError(e.errno, e.strerror, overage) |
Guido van Rossum | 8742977 | 2007-04-10 21:06:59 +0000 | [diff] [blame] | 690 | return len(b) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 691 | |
| 692 | def flush(self): |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 693 | written = 0 |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 694 | try: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 695 | while self._write_buf: |
| 696 | n = self.raw.write(self._write_buf) |
| 697 | del self._write_buf[:n] |
| 698 | written += n |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 699 | except BlockingIOError as e: |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 700 | n = e.characters_written |
| 701 | del self._write_buf[:n] |
| 702 | written += n |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 703 | raise BlockingIOError(e.errno, e.strerror, written) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 704 | |
| 705 | def tell(self): |
| 706 | return self.raw.tell() + len(self._write_buf) |
| 707 | |
| 708 | def seek(self, pos, whence=0): |
| 709 | self.flush() |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 710 | return self.raw.seek(pos, whence) |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 711 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 712 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 713 | class BufferedRWPair(BufferedIOBase): |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 714 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 715 | """A buffered reader and writer object together. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 716 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 717 | A buffered reader object and buffered writer object put together |
| 718 | to form a sequential IO object that can read and write. |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 719 | |
| 720 | This is typically used with a socket or two-way pipe. |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 721 | |
| 722 | XXX The usefulness of this (compared to having two separate IO |
| 723 | objects) is questionable. |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 724 | """ |
| 725 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 726 | def __init__(self, reader, writer, |
| 727 | buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): |
| 728 | """Constructor. |
| 729 | |
| 730 | The arguments are two RawIO instances. |
| 731 | """ |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 732 | assert reader.readable() |
| 733 | assert writer.writable() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 734 | self.reader = BufferedReader(reader, buffer_size) |
| 735 | self.writer = BufferedWriter(writer, buffer_size, max_buffer_size) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 736 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 737 | def read(self, n=-1): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 738 | return self.reader.read(n) |
| 739 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 740 | def readinto(self, b): |
| 741 | return self.reader.readinto(b) |
| 742 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 743 | def write(self, b): |
| 744 | return self.writer.write(b) |
| 745 | |
| 746 | def readable(self): |
| 747 | return self.reader.readable() |
| 748 | |
| 749 | def writable(self): |
| 750 | return self.writer.writable() |
| 751 | |
| 752 | def flush(self): |
| 753 | return self.writer.flush() |
Guido van Rossum | 68bbcd2 | 2007-02-27 17:19:33 +0000 | [diff] [blame] | 754 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 755 | def close(self): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 756 | self.writer.close() |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 757 | self.reader.close() |
| 758 | |
| 759 | def isatty(self): |
| 760 | return self.reader.isatty() or self.writer.isatty() |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 761 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 762 | @property |
| 763 | def closed(self): |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 764 | return self.writer.closed() |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 765 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 766 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 767 | class BufferedRandom(BufferedWriter, BufferedReader): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 768 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 769 | # XXX docstring |
| 770 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 771 | def __init__(self, raw, |
| 772 | buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 773 | assert raw.seekable() |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 774 | BufferedReader.__init__(self, raw, buffer_size) |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 775 | BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size) |
| 776 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 777 | def seek(self, pos, whence=0): |
| 778 | self.flush() |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 779 | # First do the raw seek, then empty the read buffer, so that |
| 780 | # if the raw seek fails, we don't lose buffered data forever. |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 781 | pos = self.raw.seek(pos, whence) |
Guido van Rossum | 76c5d4d | 2007-04-06 19:10:29 +0000 | [diff] [blame] | 782 | self._read_buf = b"" |
Guido van Rossum | 53807da | 2007-04-10 19:01:47 +0000 | [diff] [blame] | 783 | return pos |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 784 | |
| 785 | def tell(self): |
| 786 | if (self._write_buf): |
| 787 | return self.raw.tell() + len(self._write_buf) |
| 788 | else: |
| 789 | return self.raw.tell() - len(self._read_buf) |
| 790 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 791 | def read(self, n=-1): |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 792 | self.flush() |
| 793 | return BufferedReader.read(self, n) |
| 794 | |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 795 | def readinto(self, b): |
| 796 | self.flush() |
| 797 | return BufferedReader.readinto(self, b) |
| 798 | |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 799 | def write(self, b): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 800 | if self._read_buf: |
| 801 | self.raw.seek(-len(self._read_buf), 1) # Undo readahead |
| 802 | self._read_buf = b"" |
Guido van Rossum | 01a2752 | 2007-03-07 01:00:12 +0000 | [diff] [blame] | 803 | return BufferedWriter.write(self, b) |
| 804 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 805 | |
Guido van Rossum | cce92b2 | 2007-04-10 14:41:39 +0000 | [diff] [blame] | 806 | class TextIOBase(IOBase): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 807 | |
| 808 | """Base class for text I/O. |
| 809 | |
| 810 | This class provides a character and line based interface to stream I/O. |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 811 | |
| 812 | There is no readinto() method, as character strings are immutable. |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 813 | """ |
| 814 | |
| 815 | def read(self, n: int = -1) -> str: |
| 816 | """read(n: int = -1) -> str. Read at most n characters from stream. |
| 817 | |
| 818 | Read from underlying buffer until we have n characters or we hit EOF. |
| 819 | If n is negative or omitted, read until EOF. |
| 820 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 821 | self._unsupported("read") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 822 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 823 | def write(self, s: str) -> int: |
| 824 | """write(s: str) -> int. Write string s to stream.""" |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 825 | self._unsupported("write") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 826 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 827 | def truncate(self, pos: int = None) -> int: |
| 828 | """truncate(pos: int = None) -> int. Truncate size to pos.""" |
| 829 | self.flush() |
| 830 | if pos is None: |
| 831 | pos = self.tell() |
| 832 | self.seek(pos) |
| 833 | return self.buffer.truncate() |
| 834 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 835 | def readline(self) -> str: |
| 836 | """readline() -> str. Read until newline or EOF. |
| 837 | |
| 838 | Returns an empty string if EOF is hit immediately. |
| 839 | """ |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 840 | self._unsupported("readline") |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 841 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 842 | def __iter__(self) -> "TextIOBase": # That's a forward reference |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 843 | """__iter__() -> Iterator. Return line iterator (actually just self). |
| 844 | """ |
| 845 | return self |
| 846 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 847 | def next(self) -> str: |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 848 | """Same as readline() except raises StopIteration on immediate EOF.""" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 849 | line = self.readline() |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 850 | if not line: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 851 | raise StopIteration |
| 852 | return line |
| 853 | |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 854 | # The following are provided for backwards compatibility |
| 855 | |
| 856 | def readlines(self, hint=None): |
| 857 | if hint is None: |
| 858 | return list(self) |
| 859 | n = 0 |
| 860 | lines = [] |
| 861 | while not lines or n < hint: |
| 862 | line = self.readline() |
| 863 | if not line: |
| 864 | break |
| 865 | lines.append(line) |
| 866 | n += len(line) |
| 867 | return lines |
| 868 | |
| 869 | def writelines(self, lines): |
| 870 | for line in lines: |
| 871 | self.write(line) |
| 872 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 873 | |
| 874 | class TextIOWrapper(TextIOBase): |
| 875 | |
| 876 | """Buffered text stream. |
| 877 | |
| 878 | Character and line based layer over a BufferedIOBase object. |
| 879 | """ |
| 880 | |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 881 | _CHUNK_SIZE = 128 |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 882 | |
| 883 | def __init__(self, buffer, encoding=None, newline=None): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 884 | if newline not in (None, "\n", "\r\n"): |
| 885 | raise ValueError("illegal newline value: %r" % (newline,)) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 886 | if encoding is None: |
| 887 | # XXX This is questionable |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 888 | encoding = sys.getfilesystemencoding() or "latin-1" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 889 | |
| 890 | self.buffer = buffer |
| 891 | self._encoding = encoding |
| 892 | self._newline = newline or os.linesep |
| 893 | self._fix_newlines = newline is None |
| 894 | self._decoder = None |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 895 | self._decoder_in_rest_pickle = None |
| 896 | self._pending = "" |
| 897 | self._snapshot = None |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 898 | self._seekable = self._telling = self.buffer.seekable() |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 899 | |
| 900 | # A word about _snapshot. This attribute is either None, or a |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 901 | # tuple (decoder_pickle, readahead, pending) where decoder_pickle |
| 902 | # is a pickled decoder state, readahead is the chunk of bytes that |
| 903 | # was read, and pending is the characters that were rendered by |
| 904 | # the decoder after feeding it those bytes. We use this to |
| 905 | # reconstruct intermediate decoder states in tell(). |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 906 | |
| 907 | def _seekable(self): |
| 908 | return self._seekable |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 909 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 910 | def flush(self): |
| 911 | self.buffer.flush() |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 912 | self._telling = self._seekable |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 913 | |
| 914 | def close(self): |
| 915 | self.flush() |
| 916 | self.buffer.close() |
| 917 | |
| 918 | @property |
| 919 | def closed(self): |
| 920 | return self.buffer.closed |
| 921 | |
Guido van Rossum | 9be5597 | 2007-04-07 02:59:27 +0000 | [diff] [blame] | 922 | def fileno(self): |
| 923 | return self.buffer.fileno() |
| 924 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 925 | def write(self, s: str): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 926 | # XXX What if we were just reading? |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 927 | b = s.encode(self._encoding) |
| 928 | if isinstance(b, str): |
| 929 | b = bytes(b) |
| 930 | n = self.buffer.write(b) |
| 931 | if "\n" in s: |
| 932 | self.flush() |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 933 | self._snapshot = self._decoder = None |
| 934 | return len(s) |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 935 | |
| 936 | def _get_decoder(self): |
| 937 | make_decoder = codecs.getincrementaldecoder(self._encoding) |
| 938 | if make_decoder is None: |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 939 | raise IOError("Can't find an incremental decoder for encoding %s" % |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 940 | self._encoding) |
| 941 | decoder = self._decoder = make_decoder() # XXX: errors |
| 942 | if isinstance(decoder, codecs.BufferedIncrementalDecoder): |
| 943 | # XXX Hack: make the codec use bytes instead of strings |
| 944 | decoder.buffer = b"" |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 945 | self._decoder_in_rest_pickle = pickle.dumps(decoder, 2) # For tell() |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 946 | return decoder |
| 947 | |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 948 | def _read_chunk(self): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 949 | assert self._decoder is not None |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 950 | if not self._telling: |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 951 | readahead = self.buffer.read(self._CHUNK_SIZE) |
| 952 | pending = self._decoder.decode(readahead, not readahead) |
| 953 | return readahead, pending |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 954 | decoder_state = pickle.dumps(self._decoder, 2) |
| 955 | readahead = self.buffer.read(self._CHUNK_SIZE) |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 956 | pending = self._decoder.decode(readahead, not readahead) |
| 957 | self._snapshot = (decoder_state, readahead, pending) |
| 958 | return readahead, pending |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 959 | |
| 960 | def _encode_decoder_state(self, ds, pos): |
| 961 | if ds == self._decoder_in_rest_pickle: |
| 962 | return pos |
| 963 | x = 0 |
| 964 | for i in bytes(ds): |
| 965 | x = x<<8 | i |
| 966 | return (x<<64) | pos |
| 967 | |
| 968 | def _decode_decoder_state(self, pos): |
| 969 | x, pos = divmod(pos, 1<<64) |
| 970 | if not x: |
| 971 | return None, pos |
| 972 | b = b"" |
| 973 | while x: |
| 974 | b.append(x&0xff) |
| 975 | x >>= 8 |
| 976 | return str(b[::-1]), pos |
| 977 | |
| 978 | def tell(self): |
| 979 | if not self._seekable: |
| 980 | raise IOError("Underlying stream is not seekable") |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 981 | if not self._telling: |
| 982 | raise IOError("Telling position disabled by next() call") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 983 | self.flush() |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 984 | position = self.buffer.tell() |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 985 | if self._decoder is None or self._snapshot is None: |
| 986 | assert self._pending == "" |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 987 | return position |
| 988 | decoder_state, readahead, pending = self._snapshot |
| 989 | position -= len(readahead) |
| 990 | needed = len(pending) - len(self._pending) |
| 991 | if not needed: |
| 992 | return self._encode_decoder_state(decoder_state, position) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 993 | decoder = pickle.loads(decoder_state) |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 994 | n = 0 |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 995 | for i, b in enumerate(readahead): |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 996 | n += len(decoder.decode(bytes([b]))) |
| 997 | if n >= needed: |
| 998 | decoder_state = pickle.dumps(decoder, 2) |
| 999 | return self._encode_decoder_state(decoder_state, position+i+1) |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1000 | raise IOError("Can't reconstruct logical file position") |
| 1001 | |
| 1002 | def seek(self, pos, whence=0): |
| 1003 | if not self._seekable: |
| 1004 | raise IOError("Underlying stream is not seekable") |
| 1005 | if whence == 1: |
| 1006 | if pos != 0: |
| 1007 | raise IOError("Can't do nonzero cur-relative seeks") |
| 1008 | return self.tell() |
| 1009 | if whence == 2: |
| 1010 | if pos != 0: |
| 1011 | raise IOError("Can't do nonzero end-relative seeks") |
| 1012 | self.flush() |
| 1013 | pos = self.buffer.seek(0, 2) |
| 1014 | self._snapshot = None |
| 1015 | self._pending = "" |
| 1016 | self._decoder = None |
| 1017 | return pos |
| 1018 | if whence != 0: |
| 1019 | raise ValueError("Invalid whence (%r, should be 0, 1 or 2)" % |
| 1020 | (whence,)) |
| 1021 | if pos < 0: |
| 1022 | raise ValueError("Negative seek position %r" % (pos,)) |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 1023 | self.flush() |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1024 | orig_pos = pos |
| 1025 | ds, pos = self._decode_decoder_state(pos) |
| 1026 | if not ds: |
| 1027 | self.buffer.seek(pos) |
| 1028 | self._snapshot = None |
| 1029 | self._pending = "" |
| 1030 | self._decoder = None |
| 1031 | return pos |
| 1032 | decoder = pickle.loads(ds) |
| 1033 | self.buffer.seek(pos) |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 1034 | self._snapshot = (ds, b"", "") |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1035 | self._pending = "" |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 1036 | if not self._decoder_in_rest_pickle: |
| 1037 | self._get_decoder() # For its side effect |
| 1038 | self._decoder = decoder |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1039 | return orig_pos |
| 1040 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1041 | def read(self, n: int = -1): |
| 1042 | decoder = self._decoder or self._get_decoder() |
| 1043 | res = self._pending |
| 1044 | if n < 0: |
| 1045 | res += decoder.decode(self.buffer.read(), True) |
Guido van Rossum | 141f767 | 2007-04-10 00:22:16 +0000 | [diff] [blame] | 1046 | self._pending = "" |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1047 | self._snapshot = None |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1048 | return res |
| 1049 | else: |
| 1050 | while len(res) < n: |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 1051 | readahead, pending = self._read_chunk() |
| 1052 | res += pending |
| 1053 | if not readahead: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1054 | break |
| 1055 | self._pending = res[n:] |
| 1056 | return res[:n] |
| 1057 | |
Guido van Rossum | b9c4c3e | 2007-04-11 16:07:50 +0000 | [diff] [blame^] | 1058 | def next(self) -> str: |
| 1059 | self._telling = False |
| 1060 | line = self.readline() |
| 1061 | if not line: |
| 1062 | self._snapshot = None |
| 1063 | self._telling = self._seekable |
| 1064 | raise StopIteration |
| 1065 | return line |
| 1066 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 1067 | def readline(self, limit=None): |
| 1068 | if limit is not None: |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1069 | # XXX Hack to support limit argument, for backwards compatibility |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 1070 | line = self.readline() |
| 1071 | if len(line) <= limit: |
| 1072 | return line |
| 1073 | line, self._pending = line[:limit], line[limit:] + self._pending |
| 1074 | return line |
| 1075 | |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1076 | line = self._pending |
| 1077 | start = 0 |
| 1078 | decoder = self._decoder or self._get_decoder() |
| 1079 | |
| 1080 | while True: |
| 1081 | # In C we'd look for these in parallel of course. |
| 1082 | nlpos = line.find("\n", start) |
| 1083 | crpos = line.find("\r", start) |
| 1084 | if nlpos >= 0 and crpos >= 0: |
| 1085 | endpos = min(nlpos, crpos) |
| 1086 | else: |
| 1087 | endpos = nlpos if nlpos >= 0 else crpos |
| 1088 | |
| 1089 | if endpos != -1: |
| 1090 | endc = line[endpos] |
| 1091 | if endc == "\n": |
| 1092 | ending = "\n" |
| 1093 | break |
| 1094 | |
| 1095 | # We've seen \r - is it standalone, \r\n or \r at end of line? |
| 1096 | if endpos + 1 < len(line): |
Guido van Rossum | 9b76da6 | 2007-04-11 01:09:03 +0000 | [diff] [blame] | 1097 | if line[endpos+1] == "\n": |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1098 | ending = "\r\n" |
| 1099 | else: |
| 1100 | ending = "\r" |
| 1101 | break |
| 1102 | # There might be a following \n in the next block of data ... |
| 1103 | start = endpos |
| 1104 | else: |
| 1105 | start = len(line) |
| 1106 | |
| 1107 | # No line ending seen yet - get more data |
| 1108 | while True: |
Guido van Rossum | cba608c | 2007-04-11 14:19:59 +0000 | [diff] [blame] | 1109 | readahead, pending = self._read_chunk() |
| 1110 | more_line = pending |
| 1111 | if more_line or not readahead: |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1112 | break |
| 1113 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 1114 | if not more_line: |
| 1115 | ending = "" |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1116 | endpos = len(line) |
| 1117 | break |
| 1118 | |
| 1119 | line += more_line |
| 1120 | |
| 1121 | nextpos = endpos + len(ending) |
| 1122 | self._pending = line[nextpos:] |
| 1123 | |
| 1124 | # XXX Update self.newlines here if we want to support that |
| 1125 | |
Guido van Rossum | 4f0db6e | 2007-04-08 23:59:06 +0000 | [diff] [blame] | 1126 | if self._fix_newlines and ending not in ("\n", ""): |
Guido van Rossum | 78892e4 | 2007-04-06 17:31:18 +0000 | [diff] [blame] | 1127 | return line[:endpos] + "\n" |
| 1128 | else: |
| 1129 | return line[:nextpos] |