blob: fdf1299330b1709122103505fe7f456a23f20830 [file] [log] [blame]
Guido van Rossum53807da2007-04-10 19:01:47 +00001"""New I/O library conforming to PEP 3116.
Guido van Rossum28524c72007-02-27 05:47:44 +00002
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00003This is a prototype; hopefully eventually some of this will be
4reimplemented in C.
Guido van Rossum17e43e52007-02-27 15:45:13 +00005
Guido van Rossum53807da2007-04-10 19:01:47 +00006Conformance of alternative implementations: all arguments are intended
7to be positional-only except the arguments of the open() function.
8Argument names except those of the open() function are not part of the
9specification. Instance variables and methods whose name starts with
10a leading underscore are not part of the specification (except "magic"
11names like __iter__). Only the top-level names listed in the __all__
12variable are part of the specification.
Guido van Rossumc819dea2007-03-15 18:59:31 +000013
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +000014XXX edge cases when switching between reading/writing
Guido van Rossumc819dea2007-03-15 18:59:31 +000015XXX need to default buffer size to 1 if isatty()
16XXX need to support 1 meaning line-buffered
Guido van Rossum76c5d4d2007-04-06 19:10:29 +000017XXX don't use assert to validate input requirements
Guido van Rossum9b76da62007-04-11 01:09:03 +000018XXX whenever an argument is None, use the default value
19XXX read/write ops should check readable/writable
Guido van Rossumd4103952007-04-12 05:44:49 +000020XXX buffered readinto should work with arbitrary buffer objects
Guido van Rossumd76e7792007-04-17 02:38:04 +000021XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
Guido van Rossum28524c72007-02-27 05:47:44 +000022"""
23
Guido van Rossum68bbcd22007-02-27 17:19:33 +000024__author__ = ("Guido van Rossum <guido@python.org>, "
Guido van Rossum78892e42007-04-06 17:31:18 +000025 "Mike Verdone <mike.verdone@gmail.com>, "
26 "Mark Russell <mark.russell@zen.co.uk>")
Guido van Rossum28524c72007-02-27 05:47:44 +000027
Guido van Rossum141f7672007-04-10 00:22:16 +000028__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
29 "SocketIO", "BytesIO", "StringIO", "BufferedIOBase",
Guido van Rossum01a27522007-03-07 01:00:12 +000030 "BufferedReader", "BufferedWriter", "BufferedRWPair",
Guido van Rossum141f7672007-04-10 00:22:16 +000031 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
Guido van Rossum28524c72007-02-27 05:47:44 +000032
33import os
Guido van Rossum78892e42007-04-06 17:31:18 +000034import sys
35import codecs
Guido van Rossum141f7672007-04-10 00:22:16 +000036import _fileio
Guido van Rossum78892e42007-04-06 17:31:18 +000037import warnings
Guido van Rossum28524c72007-02-27 05:47:44 +000038
Guido van Rossum9b76da62007-04-11 01:09:03 +000039# XXX Shouldn't we use st_blksize whenever we can?
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000040DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
Guido van Rossum01a27522007-03-07 01:00:12 +000041
42
Guido van Rossum141f7672007-04-10 00:22:16 +000043class BlockingIOError(IOError):
Guido van Rossum78892e42007-04-06 17:31:18 +000044
Guido van Rossum141f7672007-04-10 00:22:16 +000045 """Exception raised when I/O would block on a non-blocking I/O stream."""
46
47 def __init__(self, errno, strerror, characters_written=0):
Guido van Rossum01a27522007-03-07 01:00:12 +000048 IOError.__init__(self, errno, strerror)
49 self.characters_written = characters_written
50
Guido van Rossum68bbcd22007-02-27 17:19:33 +000051
Guido van Rossum9b76da62007-04-11 01:09:03 +000052def open(file, mode="r", buffering=None, *, encoding=None, newline=None):
Guido van Rossum17e43e52007-02-27 15:45:13 +000053 """Replacement for the built-in open function.
54
55 Args:
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000056 file: string giving the name of the file to be opened;
Guido van Rossum9b76da62007-04-11 01:09:03 +000057 or integer file descriptor of the file to be wrapped (*).
58 mode: optional mode string; see below.
Guido van Rossum17e43e52007-02-27 15:45:13 +000059 buffering: optional int >= 0 giving the buffer size; values
60 can be: 0 = unbuffered, 1 = line buffered,
Guido van Rossum9b76da62007-04-11 01:09:03 +000061 larger = fully buffered.
62 Keywords (for text modes only; *must* be given as keyword arguments):
63 encoding: optional string giving the text encoding.
64 newline: optional newlines specifier; must be None, '\n' or '\r\n';
65 specifies the line ending expected on input and written on
66 output. If None, use universal newlines on input and
67 use os.linesep on output.
Guido van Rossum17e43e52007-02-27 15:45:13 +000068
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000069 (*) If a file descriptor is given, it is closed when the returned
70 I/O object is closed. If you don't want this to happen, use
71 os.dup() to create a duplicate file descriptor.
72
Guido van Rossum17e43e52007-02-27 15:45:13 +000073 Mode strings characters:
74 'r': open for reading (default)
75 'w': open for writing, truncating the file first
76 'a': open for writing, appending to the end if the file exists
77 'b': binary mode
78 't': text mode (default)
79 '+': open a disk file for updating (implies reading and writing)
Guido van Rossum9be55972007-04-07 02:59:27 +000080 'U': universal newline mode (for backwards compatibility)
Guido van Rossum17e43e52007-02-27 15:45:13 +000081
82 Constraints:
83 - encoding must not be given when a binary mode is given
84 - buffering must not be zero when a text mode is given
85
86 Returns:
87 Depending on the mode and buffering arguments, either a raw
88 binary stream, a buffered binary stream, or a buffered text
89 stream, open for reading and/or writing.
90 """
Guido van Rossum9b76da62007-04-11 01:09:03 +000091 # XXX Don't use asserts for these checks; raise TypeError or ValueError
Guido van Rossum4f0db6e2007-04-08 23:59:06 +000092 assert isinstance(file, (basestring, int)), repr(file)
93 assert isinstance(mode, basestring), repr(mode)
94 assert buffering is None or isinstance(buffering, int), repr(buffering)
95 assert encoding is None or isinstance(encoding, basestring), repr(encoding)
Guido van Rossum28524c72007-02-27 05:47:44 +000096 modes = set(mode)
Guido van Rossum9be55972007-04-07 02:59:27 +000097 if modes - set("arwb+tU") or len(mode) > len(modes):
Guido van Rossum28524c72007-02-27 05:47:44 +000098 raise ValueError("invalid mode: %r" % mode)
99 reading = "r" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000100 writing = "w" in modes
Guido van Rossum28524c72007-02-27 05:47:44 +0000101 appending = "a" in modes
102 updating = "+" in modes
Guido van Rossum17e43e52007-02-27 15:45:13 +0000103 text = "t" in modes
104 binary = "b" in modes
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000105 if "U" in modes and not (reading or writing or appending):
Guido van Rossum9be55972007-04-07 02:59:27 +0000106 reading = True
Guido van Rossum28524c72007-02-27 05:47:44 +0000107 if text and binary:
108 raise ValueError("can't have text and binary mode at once")
109 if reading + writing + appending > 1:
110 raise ValueError("can't have read/write/append mode at once")
111 if not (reading or writing or appending):
112 raise ValueError("must have exactly one of read/write/append mode")
113 if binary and encoding is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +0000114 raise ValueError("binary mode doesn't take an encoding argument")
115 if binary and newline is not None:
116 raise ValueError("binary mode doesn't take a newline argument")
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000117 raw = FileIO(file,
Guido van Rossum28524c72007-02-27 05:47:44 +0000118 (reading and "r" or "") +
119 (writing and "w" or "") +
120 (appending and "a" or "") +
121 (updating and "+" or ""))
122 if buffering is None:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000123 buffering = DEFAULT_BUFFER_SIZE
124 # XXX Should default to line buffering if os.isatty(raw.fileno())
Guido van Rossum17e43e52007-02-27 15:45:13 +0000125 try:
126 bs = os.fstat(raw.fileno()).st_blksize
127 except (os.error, AttributeError):
Guido van Rossumbb09b212007-03-18 03:36:28 +0000128 pass
129 else:
Guido van Rossum17e43e52007-02-27 15:45:13 +0000130 if bs > 1:
131 buffering = bs
Guido van Rossum28524c72007-02-27 05:47:44 +0000132 if buffering < 0:
133 raise ValueError("invalid buffering size")
134 if buffering == 0:
135 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000136 raw._name = file
137 raw._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000138 return raw
139 raise ValueError("can't have unbuffered text I/O")
140 if updating:
141 buffer = BufferedRandom(raw, buffering)
Guido van Rossum17e43e52007-02-27 15:45:13 +0000142 elif writing or appending:
Guido van Rossum28524c72007-02-27 05:47:44 +0000143 buffer = BufferedWriter(raw, buffering)
144 else:
145 assert reading
146 buffer = BufferedReader(raw, buffering)
147 if binary:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000148 buffer.name = file
149 buffer.mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000150 return buffer
Guido van Rossum13633bb2007-04-13 18:42:35 +0000151 text = TextIOWrapper(buffer, encoding, newline)
152 text.name = file
153 text.mode = mode
154 return text
Guido van Rossum28524c72007-02-27 05:47:44 +0000155
156
Guido van Rossum141f7672007-04-10 00:22:16 +0000157class IOBase:
Guido van Rossum28524c72007-02-27 05:47:44 +0000158
Guido van Rossum141f7672007-04-10 00:22:16 +0000159 """Base class for all I/O classes.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000160
Guido van Rossum141f7672007-04-10 00:22:16 +0000161 This class provides dummy implementations for many methods that
Guido van Rossum17e43e52007-02-27 15:45:13 +0000162 derived classes can override selectively; the default
163 implementations represent a file that cannot be read, written or
164 seeked.
165
Guido van Rossum141f7672007-04-10 00:22:16 +0000166 This does not define read(), readinto() and write(), nor
167 readline() and friends, since their signatures vary per layer.
Guido van Rossum53807da2007-04-10 19:01:47 +0000168
169 Not that calling any method (even inquiries) on a closed file is
170 undefined. Implementations may raise IOError in this case.
Guido van Rossum17e43e52007-02-27 15:45:13 +0000171 """
172
Guido van Rossum141f7672007-04-10 00:22:16 +0000173 ### Internal ###
174
175 def _unsupported(self, name: str) -> IOError:
176 """Internal: raise an exception for unsupported operations."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000177 raise IOError("%s.%s() not supported" % (self.__class__.__name__,
178 name))
179
Guido van Rossum141f7672007-04-10 00:22:16 +0000180 ### Positioning ###
181
Guido van Rossum53807da2007-04-10 19:01:47 +0000182 def seek(self, pos: int, whence: int = 0) -> int:
183 """seek(pos: int, whence: int = 0) -> int. Change stream position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000184
185 Seek to byte offset pos relative to position indicated by whence:
186 0 Start of stream (the default). pos should be >= 0;
187 1 Current position - whence may be negative;
188 2 End of stream - whence usually negative.
Guido van Rossum53807da2007-04-10 19:01:47 +0000189 Returns the new absolute position.
Guido van Rossum141f7672007-04-10 00:22:16 +0000190 """
191 self._unsupported("seek")
192
193 def tell(self) -> int:
194 """tell() -> int. Return current stream position."""
Guido van Rossum53807da2007-04-10 19:01:47 +0000195 return self.seek(0, 1)
Guido van Rossum141f7672007-04-10 00:22:16 +0000196
Guido van Rossum87429772007-04-10 21:06:59 +0000197 def truncate(self, pos: int = None) -> int:
198 """truncate(size: int = None) -> int. Truncate file to size bytes.
Guido van Rossum141f7672007-04-10 00:22:16 +0000199
200 Size defaults to the current IO position as reported by tell().
Guido van Rossum87429772007-04-10 21:06:59 +0000201 Returns the new size.
Guido van Rossum141f7672007-04-10 00:22:16 +0000202 """
203 self._unsupported("truncate")
204
205 ### Flush and close ###
206
207 def flush(self) -> None:
208 """flush() -> None. Flushes write buffers, if applicable.
209
210 This is a no-op for read-only and non-blocking streams.
211 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000212 # XXX Should this return the number of bytes written???
Guido van Rossum141f7672007-04-10 00:22:16 +0000213
214 __closed = False
215
216 def close(self) -> None:
217 """close() -> None. Flushes and closes the IO object.
218
219 This must be idempotent. It should also set a flag for the
220 'closed' property (see below) to test.
221 """
222 if not self.__closed:
223 self.__closed = True
224 self.flush()
225
226 def __del__(self) -> None:
227 """Destructor. Calls close()."""
228 # The try/except block is in case this is called at program
229 # exit time, when it's possible that globals have already been
230 # deleted, and then the close() call might fail. Since
231 # there's nothing we can do about such failures and they annoy
232 # the end users, we suppress the traceback.
233 try:
234 self.close()
235 except:
236 pass
237
238 ### Inquiries ###
239
240 def seekable(self) -> bool:
241 """seekable() -> bool. Return whether object supports random access.
242
243 If False, seek(), tell() and truncate() will raise IOError.
244 This method may need to do a test seek().
245 """
246 return False
247
248 def readable(self) -> bool:
249 """readable() -> bool. Return whether object was opened for reading.
250
251 If False, read() will raise IOError.
252 """
253 return False
254
255 def writable(self) -> bool:
256 """writable() -> bool. Return whether object was opened for writing.
257
258 If False, write() and truncate() will raise IOError.
259 """
260 return False
261
262 @property
263 def closed(self):
264 """closed: bool. True iff the file has been closed.
265
266 For backwards compatibility, this is a property, not a predicate.
267 """
268 return self.__closed
269
270 ### Context manager ###
271
272 def __enter__(self) -> "IOBase": # That's a forward reference
273 """Context management protocol. Returns self."""
274 return self
275
276 def __exit__(self, *args) -> None:
277 """Context management protocol. Calls close()"""
278 self.close()
279
280 ### Lower-level APIs ###
281
282 # XXX Should these be present even if unimplemented?
283
284 def fileno(self) -> int:
285 """fileno() -> int. Returns underlying file descriptor if one exists.
286
287 Raises IOError if the IO object does not use a file descriptor.
288 """
289 self._unsupported("fileno")
290
291 def isatty(self) -> bool:
292 """isatty() -> int. Returns whether this is an 'interactive' stream.
293
294 Returns False if we don't know.
295 """
296 return False
297
298
299class RawIOBase(IOBase):
300
301 """Base class for raw binary I/O.
302
303 The read() method is implemented by calling readinto(); derived
304 classes that want to support read() only need to implement
305 readinto() as a primitive operation. In general, readinto()
306 can be more efficient than read().
307
308 (It would be tempting to also provide an implementation of
309 readinto() in terms of read(), in case the latter is a more
310 suitable primitive operation, but that would lead to nasty
311 recursion in case a subclass doesn't implement either.)
312 """
313
314 def read(self, n: int) -> bytes:
Guido van Rossum78892e42007-04-06 17:31:18 +0000315 """read(n: int) -> bytes. Read and return up to n bytes.
Guido van Rossum01a27522007-03-07 01:00:12 +0000316
317 Returns an empty bytes array on EOF, or None if the object is
318 set not to block and has no data to read.
319 """
Guido van Rossum28524c72007-02-27 05:47:44 +0000320 b = bytes(n.__index__())
Guido van Rossum00efead2007-03-07 05:23:25 +0000321 n = self.readinto(b)
322 del b[n:]
Guido van Rossum28524c72007-02-27 05:47:44 +0000323 return b
324
Guido van Rossum141f7672007-04-10 00:22:16 +0000325 def readinto(self, b: bytes) -> int:
326 """readinto(b: bytes) -> int. Read up to len(b) bytes into b.
Guido van Rossum78892e42007-04-06 17:31:18 +0000327
328 Returns number of bytes read (0 for EOF), or None if the object
329 is set not to block as has no data to read.
330 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000331 self._unsupported("readinto")
Guido van Rossum28524c72007-02-27 05:47:44 +0000332
Guido van Rossum141f7672007-04-10 00:22:16 +0000333 def write(self, b: bytes) -> int:
Guido van Rossum78892e42007-04-06 17:31:18 +0000334 """write(b: bytes) -> int. Write the given buffer to the IO stream.
Guido van Rossum01a27522007-03-07 01:00:12 +0000335
Guido van Rossum78892e42007-04-06 17:31:18 +0000336 Returns the number of bytes written, which may be less than len(b).
Guido van Rossum01a27522007-03-07 01:00:12 +0000337 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000338 self._unsupported("write")
Guido van Rossum28524c72007-02-27 05:47:44 +0000339
Guido van Rossum78892e42007-04-06 17:31:18 +0000340
Guido van Rossum141f7672007-04-10 00:22:16 +0000341class FileIO(_fileio._FileIO, RawIOBase):
Guido van Rossum28524c72007-02-27 05:47:44 +0000342
Guido van Rossum141f7672007-04-10 00:22:16 +0000343 """Raw I/O implementation for OS files.
Guido van Rossum28524c72007-02-27 05:47:44 +0000344
Guido van Rossum141f7672007-04-10 00:22:16 +0000345 This multiply inherits from _FileIO and RawIOBase to make
346 isinstance(io.FileIO(), io.RawIOBase) return True without
347 requiring that _fileio._FileIO inherits from io.RawIOBase (which
348 would be hard to do since _fileio.c is written in C).
349 """
Guido van Rossuma9e20242007-03-08 00:43:48 +0000350
Guido van Rossum87429772007-04-10 21:06:59 +0000351 def close(self):
352 _fileio._FileIO.close(self)
353 RawIOBase.close(self)
354
Guido van Rossum13633bb2007-04-13 18:42:35 +0000355 @property
356 def name(self):
357 return self._name
358
359 @property
360 def mode(self):
361 return self._mode
362
Guido van Rossuma9e20242007-03-08 00:43:48 +0000363
Guido van Rossum28524c72007-02-27 05:47:44 +0000364class SocketIO(RawIOBase):
365
366 """Raw I/O implementation for stream sockets."""
367
Guido van Rossum17e43e52007-02-27 15:45:13 +0000368 # XXX More docs
Guido van Rossum141f7672007-04-10 00:22:16 +0000369 # XXX Hook this up to socket.py
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000370
Guido van Rossum28524c72007-02-27 05:47:44 +0000371 def __init__(self, sock, mode):
372 assert mode in ("r", "w", "rw")
Guido van Rossum141f7672007-04-10 00:22:16 +0000373 RawIOBase.__init__(self)
Guido van Rossum28524c72007-02-27 05:47:44 +0000374 self._sock = sock
375 self._mode = mode
Guido van Rossum28524c72007-02-27 05:47:44 +0000376
377 def readinto(self, b):
378 return self._sock.recv_into(b)
379
380 def write(self, b):
381 return self._sock.send(b)
382
383 def close(self):
Guido van Rossum141f7672007-04-10 00:22:16 +0000384 if not self.closed:
385 RawIOBase.close()
386 self._sock.close()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000387
Guido van Rossum28524c72007-02-27 05:47:44 +0000388 def readable(self):
389 return "r" in self._mode
390
391 def writable(self):
392 return "w" in self._mode
393
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000394 def fileno(self):
395 return self._sock.fileno()
Neal Norwitz8b41c3d2007-02-27 06:26:14 +0000396
Guido van Rossum28524c72007-02-27 05:47:44 +0000397
Guido van Rossumcce92b22007-04-10 14:41:39 +0000398class BufferedIOBase(IOBase):
Guido van Rossum141f7672007-04-10 00:22:16 +0000399
400 """Base class for buffered IO objects.
401
402 The main difference with RawIOBase is that the read() method
403 supports omitting the size argument, and does not have a default
404 implementation that defers to readinto().
405
406 In addition, read(), readinto() and write() may raise
407 BlockingIOError if the underlying raw stream is in non-blocking
408 mode and not ready; unlike their raw counterparts, they will never
409 return None.
410
411 A typical implementation should not inherit from a RawIOBase
412 implementation, but wrap one.
413 """
414
415 def read(self, n: int = -1) -> bytes:
416 """read(n: int = -1) -> bytes. Read and return up to n bytes.
417
418 If the argument is omitted, or negative, reads and returns all
419 data until EOF.
420
421 If the argument is positive, and the underlying raw stream is
422 not 'interactive', multiple raw reads may be issued to satisfy
423 the byte count (unless EOF is reached first). But for
424 interactive raw streams (XXX and for pipes?), at most one raw
425 read will be issued, and a short result does not imply that
426 EOF is imminent.
427
428 Returns an empty bytes array on EOF.
429
430 Raises BlockingIOError if the underlying raw stream has no
431 data at the moment.
432 """
433 self._unsupported("read")
434
435 def readinto(self, b: bytes) -> int:
436 """readinto(b: bytes) -> int. Read up to len(b) bytes into b.
437
438 Like read(), this may issue multiple reads to the underlying
439 raw stream, unless the latter is 'interactive' (XXX or a
440 pipe?).
441
442 Returns the number of bytes read (0 for EOF).
443
444 Raises BlockingIOError if the underlying raw stream has no
445 data at the moment.
446 """
Guido van Rossumd4103952007-04-12 05:44:49 +0000447 # XXX This ought to work with anything that supports the buffer API
Guido van Rossum87429772007-04-10 21:06:59 +0000448 data = self.read(len(b))
449 n = len(data)
450 b[:n] = data
451 return n
Guido van Rossum141f7672007-04-10 00:22:16 +0000452
453 def write(self, b: bytes) -> int:
454 """write(b: bytes) -> int. Write the given buffer to the IO stream.
455
456 Returns the number of bytes written, which is never less than
457 len(b).
458
459 Raises BlockingIOError if the buffer is full and the
460 underlying raw stream cannot accept more data at the moment.
461 """
462 self._unsupported("write")
463
464
465class _BufferedIOMixin(BufferedIOBase):
466
467 """A mixin implementation of BufferedIOBase with an underlying raw stream.
468
469 This passes most requests on to the underlying raw stream. It
470 does *not* provide implementations of read(), readinto() or
471 write().
472 """
473
474 def __init__(self, raw):
475 self.raw = raw
476
477 ### Positioning ###
478
479 def seek(self, pos, whence=0):
Guido van Rossum53807da2007-04-10 19:01:47 +0000480 return self.raw.seek(pos, whence)
Guido van Rossum141f7672007-04-10 00:22:16 +0000481
482 def tell(self):
483 return self.raw.tell()
484
485 def truncate(self, pos=None):
Guido van Rossum87429772007-04-10 21:06:59 +0000486 return self.raw.truncate(pos)
Guido van Rossum141f7672007-04-10 00:22:16 +0000487
488 ### Flush and close ###
489
490 def flush(self):
491 self.raw.flush()
492
493 def close(self):
494 self.flush()
495 self.raw.close()
496
497 ### Inquiries ###
498
499 def seekable(self):
500 return self.raw.seekable()
501
502 def readable(self):
503 return self.raw.readable()
504
505 def writable(self):
506 return self.raw.writable()
507
508 @property
509 def closed(self):
510 return self.raw.closed
511
512 ### Lower-level APIs ###
513
514 def fileno(self):
515 return self.raw.fileno()
516
517 def isatty(self):
518 return self.raw.isatty()
519
520
521class _MemoryIOMixin(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000522
Guido van Rossum78892e42007-04-06 17:31:18 +0000523 # XXX docstring
Guido van Rossum28524c72007-02-27 05:47:44 +0000524
Guido van Rossum78892e42007-04-06 17:31:18 +0000525 def __init__(self, buffer):
526 self._buffer = buffer
Guido van Rossum28524c72007-02-27 05:47:44 +0000527 self._pos = 0
Guido van Rossum28524c72007-02-27 05:47:44 +0000528
529 def getvalue(self):
530 return self._buffer
531
Guido van Rossum141f7672007-04-10 00:22:16 +0000532 def read(self, n=-1):
533 assert n is not None
534 if n < 0:
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000535 n = len(self._buffer)
Guido van Rossum28524c72007-02-27 05:47:44 +0000536 newpos = min(len(self._buffer), self._pos + n)
537 b = self._buffer[self._pos : newpos]
538 self._pos = newpos
539 return b
540
Guido van Rossum28524c72007-02-27 05:47:44 +0000541 def write(self, b):
542 n = len(b)
543 newpos = self._pos + n
544 self._buffer[self._pos:newpos] = b
545 self._pos = newpos
546 return n
547
548 def seek(self, pos, whence=0):
549 if whence == 0:
550 self._pos = max(0, pos)
551 elif whence == 1:
552 self._pos = max(0, self._pos + pos)
553 elif whence == 2:
554 self._pos = max(0, len(self._buffer) + pos)
555 else:
556 raise IOError("invalid whence value")
Guido van Rossum53807da2007-04-10 19:01:47 +0000557 return self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000558
559 def tell(self):
560 return self._pos
561
562 def truncate(self, pos=None):
563 if pos is None:
564 pos = self._pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000565 del self._buffer[pos:]
Guido van Rossum87429772007-04-10 21:06:59 +0000566 return pos
Guido van Rossum28524c72007-02-27 05:47:44 +0000567
568 def readable(self):
569 return True
570
571 def writable(self):
572 return True
573
574 def seekable(self):
575 return True
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000576
577
Guido van Rossum141f7672007-04-10 00:22:16 +0000578class BytesIO(_MemoryIOMixin):
Guido van Rossum78892e42007-04-06 17:31:18 +0000579
580 """Buffered I/O implementation using a bytes buffer, like StringIO."""
581
582 # XXX More docs
583
584 def __init__(self, inital_bytes=None):
585 buffer = b""
586 if inital_bytes is not None:
587 buffer += inital_bytes
Guido van Rossum141f7672007-04-10 00:22:16 +0000588 _MemoryIOMixin.__init__(self, buffer)
Guido van Rossum78892e42007-04-06 17:31:18 +0000589
590
Guido van Rossum141f7672007-04-10 00:22:16 +0000591# XXX This should inherit from TextIOBase
592class StringIO(_MemoryIOMixin):
Guido van Rossum78892e42007-04-06 17:31:18 +0000593
594 """Buffered I/O implementation using a string buffer, like StringIO."""
595
596 # XXX More docs
597
Guido van Rossum141f7672007-04-10 00:22:16 +0000598 # Reuses the same code as BytesIO, just with a string rather that
599 # bytes as the _buffer value.
600
601 # XXX This doesn't work; _MemoryIOMixin's write() and truncate()
602 # methods assume the buffer is mutable. Simply redefining those
603 # to use slice concatenation will make it awfully slow (in fact,
Guido van Rossuma5c313d2007-05-09 23:41:10 +0000604 # quadratic in the number of write() calls). Also, there are no
605 # readline() and readlines() methods. Etc., etc.
Guido van Rossum78892e42007-04-06 17:31:18 +0000606
607 def __init__(self, inital_string=None):
608 buffer = ""
609 if inital_string is not None:
610 buffer += inital_string
Guido van Rossum141f7672007-04-10 00:22:16 +0000611 _MemoryIOMixin.__init__(self, buffer)
612
613 def readinto(self, b: bytes) -> int:
614 self._unsupported("readinto")
Guido van Rossum78892e42007-04-06 17:31:18 +0000615
616
Guido van Rossum141f7672007-04-10 00:22:16 +0000617class BufferedReader(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000618
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000619 """Buffer for a readable sequential RawIO object."""
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000620
Guido van Rossum78892e42007-04-06 17:31:18 +0000621 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
Guido van Rossum01a27522007-03-07 01:00:12 +0000622 """Create a new buffered reader using the given readable raw IO object.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000623 """
624 assert raw.readable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000625 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum01a27522007-03-07 01:00:12 +0000626 self._read_buf = b""
Guido van Rossum78892e42007-04-06 17:31:18 +0000627 self.buffer_size = buffer_size
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000628
Guido van Rossum141f7672007-04-10 00:22:16 +0000629 def read(self, n=-1):
Guido van Rossum01a27522007-03-07 01:00:12 +0000630 """Read n bytes.
631
632 Returns exactly n bytes of data unless the underlying raw IO
633 stream reaches EOF of if the call would block in non-blocking
Guido van Rossum141f7672007-04-10 00:22:16 +0000634 mode. If n is negative, read until EOF or until read() would
Guido van Rossum01a27522007-03-07 01:00:12 +0000635 block.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000636 """
Guido van Rossum141f7672007-04-10 00:22:16 +0000637 assert n is not None
Guido van Rossum78892e42007-04-06 17:31:18 +0000638 nodata_val = b""
Guido van Rossum141f7672007-04-10 00:22:16 +0000639 while n < 0 or len(self._read_buf) < n:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000640 to_read = max(self.buffer_size,
641 n if n is not None else 2*len(self._read_buf))
Guido van Rossum78892e42007-04-06 17:31:18 +0000642 current = self.raw.read(to_read)
Guido van Rossum78892e42007-04-06 17:31:18 +0000643 if current in (b"", None):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000644 nodata_val = current
645 break
Guido van Rossum01a27522007-03-07 01:00:12 +0000646 self._read_buf += current
647 if self._read_buf:
Guido van Rossum141f7672007-04-10 00:22:16 +0000648 if n < 0:
Guido van Rossum01a27522007-03-07 01:00:12 +0000649 n = len(self._read_buf)
650 out = self._read_buf[:n]
651 self._read_buf = self._read_buf[n:]
652 else:
653 out = nodata_val
654 return out
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000655
Guido van Rossum13633bb2007-04-13 18:42:35 +0000656 def peek(self, n=0, *, unsafe=False):
657 """Returns buffered bytes without advancing the position.
658
659 The argument indicates a desired minimal number of bytes; we
660 do at most one raw read to satisfy it. We never return more
661 than self.buffer_size.
662
663 Unless unsafe=True is passed, we return a copy.
664 """
665 want = min(n, self.buffer_size)
666 have = len(self._read_buf)
667 if have < want:
668 to_read = self.buffer_size - have
669 current = self.raw.read(to_read)
670 if current:
671 self._read_buf += current
672 result = self._read_buf
673 if unsafe:
674 result = result[:]
675 return result
676
677 def read1(self, n):
678 """Reads up to n bytes.
679
680 Returns up to n bytes. If at least one byte is buffered,
681 we only return buffered bytes. Otherwise, we do one
682 raw read.
683 """
684 if n <= 0:
685 return b""
686 self.peek(1, unsafe=True)
687 return self.read(min(n, len(self._read_buf)))
688
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000689 def tell(self):
690 return self.raw.tell() - len(self._read_buf)
691
692 def seek(self, pos, whence=0):
693 if whence == 1:
694 pos -= len(self._read_buf)
Guido van Rossum53807da2007-04-10 19:01:47 +0000695 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000696 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000697 return pos
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000698
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000699
Guido van Rossum141f7672007-04-10 00:22:16 +0000700class BufferedWriter(_BufferedIOMixin):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000701
Guido van Rossum78892e42007-04-06 17:31:18 +0000702 # XXX docstring
703
Guido van Rossum141f7672007-04-10 00:22:16 +0000704 def __init__(self, raw,
705 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000706 assert raw.writable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000707 _BufferedIOMixin.__init__(self, raw)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000708 self.buffer_size = buffer_size
Guido van Rossum141f7672007-04-10 00:22:16 +0000709 self.max_buffer_size = (2*buffer_size
710 if max_buffer_size is None
711 else max_buffer_size)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000712 self._write_buf = b""
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000713
714 def write(self, b):
Guido van Rossum01a27522007-03-07 01:00:12 +0000715 # XXX we can implement some more tricks to try and avoid partial writes
Guido van Rossum01a27522007-03-07 01:00:12 +0000716 if len(self._write_buf) > self.buffer_size:
717 # We're full, so let's pre-flush the buffer
718 try:
719 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000720 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000721 # We can't accept anything else.
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000722 # XXX Why not just let the exception pass through?
Guido van Rossum141f7672007-04-10 00:22:16 +0000723 raise BlockingIOError(e.errno, e.strerror, 0)
Guido van Rossumd4103952007-04-12 05:44:49 +0000724 before = len(self._write_buf)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000725 self._write_buf.extend(b)
Guido van Rossumd4103952007-04-12 05:44:49 +0000726 written = len(self._write_buf) - before
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000727 if len(self._write_buf) > self.buffer_size:
Guido van Rossum01a27522007-03-07 01:00:12 +0000728 try:
729 self.flush()
Guido van Rossum141f7672007-04-10 00:22:16 +0000730 except BlockingIOError as e:
Guido van Rossum01a27522007-03-07 01:00:12 +0000731 if (len(self._write_buf) > self.max_buffer_size):
732 # We've hit max_buffer_size. We have to accept a partial
733 # write and cut back our buffer.
734 overage = len(self._write_buf) - self.max_buffer_size
735 self._write_buf = self._write_buf[:self.max_buffer_size]
Guido van Rossum141f7672007-04-10 00:22:16 +0000736 raise BlockingIOError(e.errno, e.strerror, overage)
Guido van Rossumd4103952007-04-12 05:44:49 +0000737 return written
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000738
739 def flush(self):
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000740 written = 0
Guido van Rossum01a27522007-03-07 01:00:12 +0000741 try:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000742 while self._write_buf:
743 n = self.raw.write(self._write_buf)
744 del self._write_buf[:n]
745 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000746 except BlockingIOError as e:
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000747 n = e.characters_written
748 del self._write_buf[:n]
749 written += n
Guido van Rossum141f7672007-04-10 00:22:16 +0000750 raise BlockingIOError(e.errno, e.strerror, written)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000751
752 def tell(self):
753 return self.raw.tell() + len(self._write_buf)
754
755 def seek(self, pos, whence=0):
756 self.flush()
Guido van Rossum53807da2007-04-10 19:01:47 +0000757 return self.raw.seek(pos, whence)
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000758
Guido van Rossum01a27522007-03-07 01:00:12 +0000759
Guido van Rossum141f7672007-04-10 00:22:16 +0000760class BufferedRWPair(BufferedIOBase):
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000761
Guido van Rossum01a27522007-03-07 01:00:12 +0000762 """A buffered reader and writer object together.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000763
Guido van Rossum141f7672007-04-10 00:22:16 +0000764 A buffered reader object and buffered writer object put together
765 to form a sequential IO object that can read and write.
Guido van Rossum78892e42007-04-06 17:31:18 +0000766
767 This is typically used with a socket or two-way pipe.
Guido van Rossum141f7672007-04-10 00:22:16 +0000768
769 XXX The usefulness of this (compared to having two separate IO
770 objects) is questionable.
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000771 """
772
Guido van Rossum141f7672007-04-10 00:22:16 +0000773 def __init__(self, reader, writer,
774 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
775 """Constructor.
776
777 The arguments are two RawIO instances.
778 """
Guido van Rossum01a27522007-03-07 01:00:12 +0000779 assert reader.readable()
780 assert writer.writable()
Guido van Rossum141f7672007-04-10 00:22:16 +0000781 self.reader = BufferedReader(reader, buffer_size)
782 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +0000783
Guido van Rossum141f7672007-04-10 00:22:16 +0000784 def read(self, n=-1):
Guido van Rossum01a27522007-03-07 01:00:12 +0000785 return self.reader.read(n)
786
Guido van Rossum141f7672007-04-10 00:22:16 +0000787 def readinto(self, b):
788 return self.reader.readinto(b)
789
Guido van Rossum01a27522007-03-07 01:00:12 +0000790 def write(self, b):
791 return self.writer.write(b)
792
Guido van Rossum13633bb2007-04-13 18:42:35 +0000793 def peek(self, n=0, *, unsafe=False):
794 return self.reader.peek(n, unsafe=unsafe)
795
796 def read1(self, n):
797 return self.reader.read1(n)
798
Guido van Rossum01a27522007-03-07 01:00:12 +0000799 def readable(self):
800 return self.reader.readable()
801
802 def writable(self):
803 return self.writer.writable()
804
805 def flush(self):
806 return self.writer.flush()
Guido van Rossum68bbcd22007-02-27 17:19:33 +0000807
Guido van Rossum01a27522007-03-07 01:00:12 +0000808 def close(self):
Guido van Rossum01a27522007-03-07 01:00:12 +0000809 self.writer.close()
Guido van Rossum141f7672007-04-10 00:22:16 +0000810 self.reader.close()
811
812 def isatty(self):
813 return self.reader.isatty() or self.writer.isatty()
Guido van Rossum01a27522007-03-07 01:00:12 +0000814
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000815 @property
816 def closed(self):
Guido van Rossum141f7672007-04-10 00:22:16 +0000817 return self.writer.closed()
Guido van Rossum01a27522007-03-07 01:00:12 +0000818
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000819
Guido van Rossum141f7672007-04-10 00:22:16 +0000820class BufferedRandom(BufferedWriter, BufferedReader):
Guido van Rossum01a27522007-03-07 01:00:12 +0000821
Guido van Rossum78892e42007-04-06 17:31:18 +0000822 # XXX docstring
823
Guido van Rossum141f7672007-04-10 00:22:16 +0000824 def __init__(self, raw,
825 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Guido van Rossum01a27522007-03-07 01:00:12 +0000826 assert raw.seekable()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000827 BufferedReader.__init__(self, raw, buffer_size)
Guido van Rossum01a27522007-03-07 01:00:12 +0000828 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
829
Guido van Rossum01a27522007-03-07 01:00:12 +0000830 def seek(self, pos, whence=0):
831 self.flush()
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000832 # First do the raw seek, then empty the read buffer, so that
833 # if the raw seek fails, we don't lose buffered data forever.
Guido van Rossum53807da2007-04-10 19:01:47 +0000834 pos = self.raw.seek(pos, whence)
Guido van Rossum76c5d4d2007-04-06 19:10:29 +0000835 self._read_buf = b""
Guido van Rossum53807da2007-04-10 19:01:47 +0000836 return pos
Guido van Rossum01a27522007-03-07 01:00:12 +0000837
838 def tell(self):
839 if (self._write_buf):
840 return self.raw.tell() + len(self._write_buf)
841 else:
842 return self.raw.tell() - len(self._read_buf)
843
Guido van Rossum141f7672007-04-10 00:22:16 +0000844 def read(self, n=-1):
Guido van Rossum01a27522007-03-07 01:00:12 +0000845 self.flush()
846 return BufferedReader.read(self, n)
847
Guido van Rossum141f7672007-04-10 00:22:16 +0000848 def readinto(self, b):
849 self.flush()
850 return BufferedReader.readinto(self, b)
851
Guido van Rossum13633bb2007-04-13 18:42:35 +0000852 def peek(self, n=0, *, unsafe=False):
853 self.flush()
854 return BufferedReader.peek(self, n, unsafe=unsafe)
855
856 def read1(self, n):
857 self.flush()
858 return BufferedReader.read1(self, n)
859
Guido van Rossum01a27522007-03-07 01:00:12 +0000860 def write(self, b):
Guido van Rossum78892e42007-04-06 17:31:18 +0000861 if self._read_buf:
862 self.raw.seek(-len(self._read_buf), 1) # Undo readahead
863 self._read_buf = b""
Guido van Rossum01a27522007-03-07 01:00:12 +0000864 return BufferedWriter.write(self, b)
865
Guido van Rossum78892e42007-04-06 17:31:18 +0000866
Guido van Rossumcce92b22007-04-10 14:41:39 +0000867class TextIOBase(IOBase):
Guido van Rossum78892e42007-04-06 17:31:18 +0000868
869 """Base class for text I/O.
870
871 This class provides a character and line based interface to stream I/O.
Guido van Rossum9b76da62007-04-11 01:09:03 +0000872
873 There is no readinto() method, as character strings are immutable.
Guido van Rossum78892e42007-04-06 17:31:18 +0000874 """
875
876 def read(self, n: int = -1) -> str:
877 """read(n: int = -1) -> str. Read at most n characters from stream.
878
879 Read from underlying buffer until we have n characters or we hit EOF.
880 If n is negative or omitted, read until EOF.
881 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000882 self._unsupported("read")
Guido van Rossum78892e42007-04-06 17:31:18 +0000883
Guido van Rossum9b76da62007-04-11 01:09:03 +0000884 def write(self, s: str) -> int:
885 """write(s: str) -> int. Write string s to stream."""
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000886 self._unsupported("write")
Guido van Rossum78892e42007-04-06 17:31:18 +0000887
Guido van Rossum9b76da62007-04-11 01:09:03 +0000888 def truncate(self, pos: int = None) -> int:
889 """truncate(pos: int = None) -> int. Truncate size to pos."""
890 self.flush()
891 if pos is None:
892 pos = self.tell()
893 self.seek(pos)
894 return self.buffer.truncate()
895
Guido van Rossum78892e42007-04-06 17:31:18 +0000896 def readline(self) -> str:
897 """readline() -> str. Read until newline or EOF.
898
899 Returns an empty string if EOF is hit immediately.
900 """
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000901 self._unsupported("readline")
Guido van Rossum78892e42007-04-06 17:31:18 +0000902
Guido van Rossum9b76da62007-04-11 01:09:03 +0000903 def __iter__(self) -> "TextIOBase": # That's a forward reference
Guido van Rossum78892e42007-04-06 17:31:18 +0000904 """__iter__() -> Iterator. Return line iterator (actually just self).
905 """
906 return self
907
Georg Brandla18af4e2007-04-21 15:47:16 +0000908 def __next__(self) -> str:
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000909 """Same as readline() except raises StopIteration on immediate EOF."""
Guido van Rossum78892e42007-04-06 17:31:18 +0000910 line = self.readline()
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000911 if not line:
Guido van Rossum78892e42007-04-06 17:31:18 +0000912 raise StopIteration
913 return line
914
Guido van Rossum9be55972007-04-07 02:59:27 +0000915 # The following are provided for backwards compatibility
916
917 def readlines(self, hint=None):
918 if hint is None:
919 return list(self)
920 n = 0
921 lines = []
922 while not lines or n < hint:
923 line = self.readline()
924 if not line:
925 break
926 lines.append(line)
927 n += len(line)
928 return lines
929
930 def writelines(self, lines):
931 for line in lines:
932 self.write(line)
933
Guido van Rossum78892e42007-04-06 17:31:18 +0000934
935class TextIOWrapper(TextIOBase):
936
937 """Buffered text stream.
938
939 Character and line based layer over a BufferedIOBase object.
940 """
941
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +0000942 _CHUNK_SIZE = 128
Guido van Rossum78892e42007-04-06 17:31:18 +0000943
944 def __init__(self, buffer, encoding=None, newline=None):
Guido van Rossum9b76da62007-04-11 01:09:03 +0000945 if newline not in (None, "\n", "\r\n"):
946 raise ValueError("illegal newline value: %r" % (newline,))
Guido van Rossum78892e42007-04-06 17:31:18 +0000947 if encoding is None:
948 # XXX This is questionable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000949 encoding = sys.getfilesystemencoding() or "latin-1"
Guido van Rossum78892e42007-04-06 17:31:18 +0000950
951 self.buffer = buffer
952 self._encoding = encoding
953 self._newline = newline or os.linesep
954 self._fix_newlines = newline is None
955 self._decoder = None
Guido van Rossum9b76da62007-04-11 01:09:03 +0000956 self._pending = ""
957 self._snapshot = None
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +0000958 self._seekable = self._telling = self.buffer.seekable()
Guido van Rossum9b76da62007-04-11 01:09:03 +0000959
960 # A word about _snapshot. This attribute is either None, or a
Guido van Rossumd76e7792007-04-17 02:38:04 +0000961 # tuple (decoder_state, readahead, pending) where decoder_state is
962 # the second (integer) item of the decoder state, readahead is the
963 # chunk of bytes that was read, and pending is the characters that
964 # were rendered by the decoder after feeding it those bytes. We
965 # use this to reconstruct intermediate decoder states in tell().
Guido van Rossum9b76da62007-04-11 01:09:03 +0000966
967 def _seekable(self):
968 return self._seekable
Guido van Rossum78892e42007-04-06 17:31:18 +0000969
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000970 def flush(self):
971 self.buffer.flush()
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +0000972 self._telling = self._seekable
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000973
974 def close(self):
975 self.flush()
976 self.buffer.close()
977
978 @property
979 def closed(self):
980 return self.buffer.closed
981
Guido van Rossum9be55972007-04-07 02:59:27 +0000982 def fileno(self):
983 return self.buffer.fileno()
984
Guido van Rossum78892e42007-04-06 17:31:18 +0000985 def write(self, s: str):
Guido van Rossum9b76da62007-04-11 01:09:03 +0000986 # XXX What if we were just reading?
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000987 b = s.encode(self._encoding)
988 if isinstance(b, str):
989 b = bytes(b)
990 n = self.buffer.write(b)
991 if "\n" in s:
Guido van Rossum13633bb2007-04-13 18:42:35 +0000992 # XXX only if isatty
Guido van Rossum4f0db6e2007-04-08 23:59:06 +0000993 self.flush()
Guido van Rossum9b76da62007-04-11 01:09:03 +0000994 self._snapshot = self._decoder = None
995 return len(s)
Guido van Rossum78892e42007-04-06 17:31:18 +0000996
997 def _get_decoder(self):
998 make_decoder = codecs.getincrementaldecoder(self._encoding)
999 if make_decoder is None:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001000 raise IOError("Can't find an incremental decoder for encoding %s" %
Guido van Rossum78892e42007-04-06 17:31:18 +00001001 self._encoding)
1002 decoder = self._decoder = make_decoder() # XXX: errors
Guido van Rossum78892e42007-04-06 17:31:18 +00001003 return decoder
1004
Guido van Rossum9b76da62007-04-11 01:09:03 +00001005 def _read_chunk(self):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001006 assert self._decoder is not None
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001007 if not self._telling:
Guido van Rossum13633bb2007-04-13 18:42:35 +00001008 readahead = self.buffer.read1(self._CHUNK_SIZE)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001009 pending = self._decoder.decode(readahead, not readahead)
1010 return readahead, pending
Guido van Rossumd76e7792007-04-17 02:38:04 +00001011 decoder_buffer, decoder_state = self._decoder.getstate()
Guido van Rossum13633bb2007-04-13 18:42:35 +00001012 readahead = self.buffer.read1(self._CHUNK_SIZE)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001013 pending = self._decoder.decode(readahead, not readahead)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001014 self._snapshot = (decoder_state, decoder_buffer + readahead, pending)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001015 return readahead, pending
Guido van Rossum9b76da62007-04-11 01:09:03 +00001016
1017 def _encode_decoder_state(self, ds, pos):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001018 x = 0
1019 for i in bytes(ds):
1020 x = x<<8 | i
1021 return (x<<64) | pos
1022
1023 def _decode_decoder_state(self, pos):
1024 x, pos = divmod(pos, 1<<64)
1025 if not x:
1026 return None, pos
1027 b = b""
1028 while x:
1029 b.append(x&0xff)
1030 x >>= 8
1031 return str(b[::-1]), pos
1032
1033 def tell(self):
1034 if not self._seekable:
1035 raise IOError("Underlying stream is not seekable")
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001036 if not self._telling:
1037 raise IOError("Telling position disabled by next() call")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001038 self.flush()
Guido van Rossumcba608c2007-04-11 14:19:59 +00001039 position = self.buffer.tell()
Guido van Rossumd76e7792007-04-17 02:38:04 +00001040 decoder = self._decoder
1041 if decoder is None or self._snapshot is None:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001042 assert self._pending == ""
Guido van Rossumcba608c2007-04-11 14:19:59 +00001043 return position
1044 decoder_state, readahead, pending = self._snapshot
1045 position -= len(readahead)
1046 needed = len(pending) - len(self._pending)
1047 if not needed:
1048 return self._encode_decoder_state(decoder_state, position)
Guido van Rossumd76e7792007-04-17 02:38:04 +00001049 saved_state = decoder.getstate()
1050 try:
Guido van Rossum2b08b382007-05-08 20:18:39 +00001051 decoder.setstate((b"", decoder_state))
Guido van Rossumd76e7792007-04-17 02:38:04 +00001052 n = 0
1053 bb = bytes(1)
1054 for i, bb[0] in enumerate(readahead):
1055 n += len(decoder.decode(bb))
1056 if n >= needed:
1057 decoder_buffer, decoder_state = decoder.getstate()
1058 return self._encode_decoder_state(
1059 decoder_state,
1060 position + (i+1) - len(decoder_buffer))
1061 raise IOError("Can't reconstruct logical file position")
1062 finally:
1063 decoder.setstate(saved_state)
Guido van Rossum9b76da62007-04-11 01:09:03 +00001064
1065 def seek(self, pos, whence=0):
1066 if not self._seekable:
1067 raise IOError("Underlying stream is not seekable")
1068 if whence == 1:
1069 if pos != 0:
1070 raise IOError("Can't do nonzero cur-relative seeks")
Guido van Rossumaa43ed92007-04-12 05:24:24 +00001071 pos = self.tell()
1072 whence = 0
Guido van Rossum9b76da62007-04-11 01:09:03 +00001073 if whence == 2:
1074 if pos != 0:
1075 raise IOError("Can't do nonzero end-relative seeks")
1076 self.flush()
1077 pos = self.buffer.seek(0, 2)
1078 self._snapshot = None
1079 self._pending = ""
1080 self._decoder = None
1081 return pos
1082 if whence != 0:
1083 raise ValueError("Invalid whence (%r, should be 0, 1 or 2)" %
1084 (whence,))
1085 if pos < 0:
1086 raise ValueError("Negative seek position %r" % (pos,))
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001087 self.flush()
Guido van Rossum9b76da62007-04-11 01:09:03 +00001088 orig_pos = pos
1089 ds, pos = self._decode_decoder_state(pos)
1090 if not ds:
1091 self.buffer.seek(pos)
1092 self._snapshot = None
1093 self._pending = ""
1094 self._decoder = None
1095 return pos
Guido van Rossumd76e7792007-04-17 02:38:04 +00001096 decoder = self._decoder or self._get_decoder()
1097 decoder.set_state(("", ds))
Guido van Rossum9b76da62007-04-11 01:09:03 +00001098 self.buffer.seek(pos)
Guido van Rossumcba608c2007-04-11 14:19:59 +00001099 self._snapshot = (ds, b"", "")
Guido van Rossum9b76da62007-04-11 01:09:03 +00001100 self._pending = ""
Guido van Rossumcba608c2007-04-11 14:19:59 +00001101 self._decoder = decoder
Guido van Rossum9b76da62007-04-11 01:09:03 +00001102 return orig_pos
1103
Guido van Rossum13633bb2007-04-13 18:42:35 +00001104 def _simplify(self, u):
1105 # XXX Hack until str/unicode unification: return str instead
1106 # of unicode if it's all ASCII
1107 try:
1108 return str(u)
1109 except UnicodeEncodeError:
1110 return u
1111
Guido van Rossum78892e42007-04-06 17:31:18 +00001112 def read(self, n: int = -1):
1113 decoder = self._decoder or self._get_decoder()
1114 res = self._pending
1115 if n < 0:
1116 res += decoder.decode(self.buffer.read(), True)
Guido van Rossum141f7672007-04-10 00:22:16 +00001117 self._pending = ""
Guido van Rossum9b76da62007-04-11 01:09:03 +00001118 self._snapshot = None
Guido van Rossum13633bb2007-04-13 18:42:35 +00001119 return self._simplify(res)
Guido van Rossum78892e42007-04-06 17:31:18 +00001120 else:
1121 while len(res) < n:
Guido van Rossumcba608c2007-04-11 14:19:59 +00001122 readahead, pending = self._read_chunk()
1123 res += pending
1124 if not readahead:
Guido van Rossum78892e42007-04-06 17:31:18 +00001125 break
1126 self._pending = res[n:]
Guido van Rossum13633bb2007-04-13 18:42:35 +00001127 return self._simplify(res[:n])
Guido van Rossum78892e42007-04-06 17:31:18 +00001128
Georg Brandla18af4e2007-04-21 15:47:16 +00001129 def __next__(self) -> str:
Guido van Rossumb9c4c3e2007-04-11 16:07:50 +00001130 self._telling = False
1131 line = self.readline()
1132 if not line:
1133 self._snapshot = None
1134 self._telling = self._seekable
1135 raise StopIteration
1136 return line
1137
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001138 def readline(self, limit=None):
1139 if limit is not None:
Guido van Rossum9b76da62007-04-11 01:09:03 +00001140 # XXX Hack to support limit argument, for backwards compatibility
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001141 line = self.readline()
1142 if len(line) <= limit:
Guido van Rossum13633bb2007-04-13 18:42:35 +00001143 return self._simplify(line)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001144 line, self._pending = line[:limit], line[limit:] + self._pending
Guido van Rossum13633bb2007-04-13 18:42:35 +00001145 return self._simplify(line)
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001146
Guido van Rossum78892e42007-04-06 17:31:18 +00001147 line = self._pending
1148 start = 0
1149 decoder = self._decoder or self._get_decoder()
1150
1151 while True:
1152 # In C we'd look for these in parallel of course.
1153 nlpos = line.find("\n", start)
1154 crpos = line.find("\r", start)
1155 if nlpos >= 0 and crpos >= 0:
1156 endpos = min(nlpos, crpos)
1157 else:
1158 endpos = nlpos if nlpos >= 0 else crpos
1159
1160 if endpos != -1:
1161 endc = line[endpos]
1162 if endc == "\n":
1163 ending = "\n"
1164 break
1165
1166 # We've seen \r - is it standalone, \r\n or \r at end of line?
1167 if endpos + 1 < len(line):
Guido van Rossum9b76da62007-04-11 01:09:03 +00001168 if line[endpos+1] == "\n":
Guido van Rossum78892e42007-04-06 17:31:18 +00001169 ending = "\r\n"
1170 else:
1171 ending = "\r"
1172 break
1173 # There might be a following \n in the next block of data ...
1174 start = endpos
1175 else:
1176 start = len(line)
1177
1178 # No line ending seen yet - get more data
1179 while True:
Guido van Rossumcba608c2007-04-11 14:19:59 +00001180 readahead, pending = self._read_chunk()
1181 more_line = pending
1182 if more_line or not readahead:
Guido van Rossum78892e42007-04-06 17:31:18 +00001183 break
1184
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001185 if not more_line:
1186 ending = ""
Guido van Rossum78892e42007-04-06 17:31:18 +00001187 endpos = len(line)
1188 break
1189
1190 line += more_line
1191
1192 nextpos = endpos + len(ending)
1193 self._pending = line[nextpos:]
1194
1195 # XXX Update self.newlines here if we want to support that
1196
Guido van Rossum4f0db6e2007-04-08 23:59:06 +00001197 if self._fix_newlines and ending not in ("\n", ""):
Guido van Rossum13633bb2007-04-13 18:42:35 +00001198 return self._simplify(line[:endpos] + "\n")
Guido van Rossum78892e42007-04-06 17:31:18 +00001199 else:
Guido van Rossum13633bb2007-04-13 18:42:35 +00001200 return self._simplify(line[:nextpos])