Debian Codegraph @

rpython/rlib/streamio.py

raw symbols SCIP
1 """New standard I/O library.
2
3 Based on sio.py from Guido van Rossum.
4
5 - This module contains various stream classes which provide a subset of the
6 classic Python I/O API: read(n), write(s), tell(), seek(offset, whence=0),
7 readall(), readline(), truncate(size), flush(), close(), peek(),
8 flushable(), try_to_find_file_descriptor().
9
10 - This is not for general usage:
11 * read(n) may return less than n bytes, just like os.read().
12 * some other methods also have no default parameters.
13 * close() should be called exactly once and no further operations performed;
14 there is no __del__() closing the stream for you.
15 * some methods may raise MyNotImplementedError.
16 * peek() returns some (or no) characters that have already been read ahead.
17 * flushable() returns True/False if flushing that stream is useful/pointless.
18
19 - A 'basis stream' provides I/O using a low-level API, like the os, mmap or
20 socket modules.
21
22 - A 'filtering stream' builds on top of another stream. There are filtering
23 streams for universal newline translation, for unicode translation, and
24 for buffering.
25
26 You typically take a basis stream, place zero or more filtering
27 streams on top of it, and then top it off with an input-buffering and/or
28 an outout-buffering stream.
29 """
30
31 # File offsets are all 'r_longlong', but a single read or write cannot
32 # transfer more data that fits in an RPython 'int' (because that would not
33 # fit in a single string anyway). This module needs to be careful about
34 # where r_longlong values end up: as argument to seek() and truncate() and
35 # return value of tell(), but not as argument to read().
36
37 import os, sys, errno
38 from rpython.rlib.objectmodel import specialize, we_are_translated, not_rpython
39 from rpython.rlib.rarithmetic import r_longlong, intmask
40 from rpython.rlib import rposix, nonconst, _rsocket_rffi as _c
41 from rpython.rlib.rstring import StringBuilder
42
43 from os import O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC, O_APPEND
44 O_BINARY = getattr(os, "O_BINARY", 0)
45
46 # (basemode, plus)
47 OS_MODE = {('r', False): O_RDONLY,
48 ('r', True): O_RDWR,
49 ('w', False): O_WRONLY | O_CREAT | O_TRUNC,
50 ('w', True): O_RDWR | O_CREAT | O_TRUNC,
51 ('a', False): O_WRONLY | O_CREAT | O_APPEND,
52 ('a', True): O_RDWR | O_CREAT | O_APPEND,
53 }
54
55 class MyNotImplementedError(Exception):
56 """Catching NotImplementedError is not RPython, so we use this custom class
57 instead of it
58 """
59
60 # ____________________________________________________________
61
62 def replace_crlf_with_lf(s, first_index=-1):
63 if first_index < 0:
64 first_index = s.find("\r")
65 if first_index < 0:
66 return s
67 builder = StringBuilder(len(s))
68 builder.append_slice(s, 0, first_index)
69 while first_index < len(s):
70 builder.append("\n")
71 index = s.find("\r", first_index + 1)
72 if index < 0:
73 index = len(s)
74 if first_index + 1 < len(s) and s[first_index + 1] == "\n":
75 # \r\n
76 first_index += 1
77 builder.append_slice(s, first_index + 1, index)
78 first_index = index
79 return builder.build()
80
81 def replace_char_with_str(string, c, s):
82 return s.join(string.split(c))
83
84
85 @specialize.argtype(0)
86 def open_file_as_stream(path, mode="r", buffering=-1, signal_checker=None):
87 os_flags, universal, reading, writing, basemode, binary = decode_mode(mode)
88 stream = open_path_helper(path, os_flags, basemode == "a", signal_checker)
89 return construct_stream_tower(stream, buffering, universal, reading,
90 writing, binary)
91
92 def _setfd_binary(fd):
93 pass
94
95 if hasattr(_c, 'fcntl'):
96 def _check_fd_mode(fd, reading, writing):
97 flags = intmask(_c.fcntl(fd, _c.F_GETFL, 0))
98 if flags & _c.O_RDWR:
99 return
100 elif flags & _c.O_WRONLY:
101 if not reading:
102 return
103 else: # O_RDONLY
104 if not writing:
105 return
106 raise OSError(22, "Invalid argument")
107 else:
108 def _check_fd_mode(fd, reading, writing):
109 # XXX
110 pass
111
112 def fdopen_as_stream(fd, mode, buffering=-1, signal_checker=None):
113 os_flags, universal, reading, writing, basemode, binary = decode_mode(mode)
114 _check_fd_mode(fd, reading, writing)
115 _setfd_binary(fd)
116 stream = DiskFile(fd, signal_checker)
117 return construct_stream_tower(stream, buffering, universal, reading,
118 writing, binary)
119
120 @specialize.argtype(0)
121 def open_path_helper(path, os_flags, append, signal_checker=None):
122 # XXX for now always return DiskFile
123 fd = rposix.open(path, os_flags, 0666)
124 if append:
125 try:
126 os.lseek(fd, 0, 2)
127 except OSError:
128 # XXX does this pass make sense?
129 pass
130 return DiskFile(fd, signal_checker)
131
132 def decode_mode(mode):
133 if mode[0] == 'U':
134 mode = 'r' + mode
135
136 basemode = mode[0] # 'r', 'w' or 'a'
137 plus = False
138 universal = False
139 binary = False
140
141 for c in mode[1:]:
142 if c == '+':
143 plus = True
144 elif c == 'U':
145 universal = True
146 elif c == 'b':
147 binary = True
148 else:
149 break
150
151 flag = OS_MODE[basemode, plus]
152 flag |= O_BINARY
153
154 reading = basemode == 'r' or plus
155 writing = basemode != 'r' or plus
156
157 return flag, universal, reading, writing, basemode, binary
158
159
160 def construct_stream_tower(stream, buffering, universal, reading, writing,
161 binary):
162 if buffering == 0: # no buffering
163 pass
164 elif buffering == 1: # line-buffering
165 if writing:
166 stream = LineBufferingOutputStream(stream)
167 if reading:
168 stream = BufferingInputStream(stream)
169
170 else: # default or explicit buffer sizes
171 if buffering is not None and buffering < 0:
172 buffering = -1
173 if writing:
174 stream = BufferingOutputStream(stream, buffering)
175 if reading:
176 stream = BufferingInputStream(stream, buffering)
177
178 if universal: # Wants universal newlines
179 if writing and os.linesep != '\n':
180 stream = TextOutputFilter(stream)
181 if reading:
182 stream = TextInputFilter(stream)
183 elif not binary and os.linesep == '\r\n':
184 stream = TextCRLFFilter(stream)
185 if nonconst.NonConstant(False):
186 stream.flush_buffers() # annotation workaround for untranslated tests
187 return stream
188
189
190 class StreamError(Exception):
191 def __init__(self, message):
192 self.message = message
193
194 StreamErrors = (OSError, StreamError) # errors that can generally be raised
195
196
197 if sys.platform == "win32":
198 from rpython.rlib.rwin32 import BOOL, HANDLE, get_osfhandle
199 from rpython.rlib.rwin32 import GetLastError_saved
200 from rpython.translator.tool.cbuild import ExternalCompilationInfo
201 from rpython.rtyper.lltypesystem import rffi
202
203 _eci = ExternalCompilationInfo()
204 _setmode = rffi.llexternal('_setmode', [rffi.INT, rffi.INT], rffi.INT,
205 compilation_info=_eci)
206 SetEndOfFile = rffi.llexternal('SetEndOfFile', [HANDLE], BOOL,
207 compilation_info=_eci,
208 save_err=rffi.RFFI_SAVE_LASTERROR)
209
210 def _setfd_binary(fd):
211 # Allow this to succeed on invalid fd's
212 with rposix.SuppressIPH():
213 _setmode(fd, os.O_BINARY)
214
215 def ftruncate_win32(fd, size):
216 curpos = os.lseek(fd, 0, 1)
217 try:
218 # move to the position to be truncated
219 os.lseek(fd, size, 0)
220 # Truncate. Note that this may grow the file!
221 handle = get_osfhandle(fd)
222 if not SetEndOfFile(handle):
223 raise OSError(GetLastError_saved(),
224 "Could not truncate file")
225 finally:
226 # we restore the file pointer position in any case
227 os.lseek(fd, curpos, 0)
228
229
230 class Stream(object):
231 """Base class for streams. Provides a default implementation of
232 some methods."""
233
234 def read(self, n):
235 raise MyNotImplementedError
236
237 def write(self, data):
238 raise MyNotImplementedError
239
240 def tell(self):
241 raise MyNotImplementedError
242
243 def seek(self, offset, whence):
244 raise MyNotImplementedError
245
246 def readall(self):
247 bufsize = 8192
248 result = []
249 while True:
250 try:
251 data = self.read(bufsize)
252 except OSError:
253 # like CPython < 3.4, partial results followed by an error
254 # are returned as data
255 if not result:
256 raise
257 break
258 if not data:
259 break
260 result.append(data)
261 if bufsize < 4194304: # 4 Megs
262 bufsize <<= 1
263 return ''.join(result)
264
265 def readline(self):
266 # very inefficient unless there is a peek()
267 result = []
268 while True:
269 # "peeks" on the underlying stream to see how many characters
270 # we can safely read without reading past an end-of-line
271 startindex, peeked = self.peek()
272 assert 0 <= startindex <= len(peeked)
273 pn = peeked.find("\n", startindex)
274 if pn < 0:
275 pn = len(peeked)
276 c = self.read(pn - startindex + 1)
277 if not c:
278 break
279 result.append(c)
280 if c.endswith('\n'):
281 break
282 return ''.join(result)
283
284 def truncate(self, size):
285 raise MyNotImplementedError
286
287 def flush_buffers(self):
288 pass
289
290 def flush(self):
291 pass
292
293 def flushable(self):
294 return False
295
296 def close(self):
297 self.close1(True)
298
299 def close1(self, closefileno):
300 pass
301
302 def peek(self):
303 return (0, '')
304
305 def count_buffered_bytes(self):
306 pos, buf = self.peek()
307 return len(buf) - pos
308
309 def try_to_find_file_descriptor(self):
310 return -1
311
312 def getnewlines(self):
313 return 0
314
315
316 class DiskFile(Stream):
317 """Standard I/O basis stream using os.open/close/read/write/lseek"""
318
319 def __init__(self, fd, signal_checker=None):
320 self.fd = fd
321 self.signal_checker = signal_checker
322
323 def seek(self, offset, whence):
324 os.lseek(self.fd, offset, whence)
325
326 def tell(self):
327 result = os.lseek(self.fd, 0, 1)
328 return r_longlong(result)
329
330 def read(self, n):
331 assert isinstance(n, int)
332 while True:
333 try:
334 return os.read(self.fd, n)
335 except OSError as e:
336 if e.errno != errno.EINTR:
337 raise
338 if self.signal_checker is not None:
339 self.signal_checker()
340 # else try again
341
342 def readline(self):
343 # mostly inefficient, but not as laughably bad as with the default
344 # readline() from Stream
345 result = StringBuilder()
346 while True:
347 try:
348 c = os.read(self.fd, 1)
349 except OSError as e:
350 if e.errno != errno.EINTR:
351 raise
352 if self.signal_checker is not None:
353 self.signal_checker()
354 continue # try again
355 if not c:
356 break
357 c = c[0]
358 result.append(c)
359 if c == '\n':
360 break
361 return result.build()
362
363 def write(self, data):
364 while data:
365 try:
366 n = os.write(self.fd, data)
367 except OSError as e:
368 if e.errno != errno.EINTR:
369 raise
370 if self.signal_checker is not None:
371 self.signal_checker()
372 else:
373 data = data[n:]
374
375 def close1(self, closefileno):
376 if closefileno:
377 os.close(self.fd)
378
379 if sys.platform == "win32":
380 def truncate(self, size):
381 ftruncate_win32(self.fd, size)
382 else:
383 def truncate(self, size):
384 # Note: for consistency, in translated programs a failing
385 # os.ftruncate() raises OSError. However, on top of
386 # CPython, we get an IOError. As it is (as far as I know)
387 # the only place that have this behavior, we just convert it
388 # to an OSError instead of adding IOError to StreamErrors.
389 if we_are_translated():
390 os.ftruncate(self.fd, size)
391 else:
392 try:
393 os.ftruncate(self.fd, size)
394 except IOError as e:
395 raise OSError(*e.args)
396
397 def try_to_find_file_descriptor(self):
398 return self.fd
399
400 # next class is not RPython
401
402 class MMapFile(Stream):
403 """Standard I/O basis stream using mmap."""
404
405 @not_rpython
406 def __init__(self, fd, mmapaccess):
407 self.fd = fd
408 self.access = mmapaccess
409 self.pos = 0
410 self.remapfile()
411
412 def remapfile(self):
413 import mmap
414 size = os.fstat(self.fd).st_size
415 self.mm = mmap.mmap(self.fd, size, access=self.access)
416
417 def close1(self, closefileno):
418 self.mm.close()
419 if closefileno:
420 os.close(self.fd)
421
422 def tell(self):
423 return self.pos
424
425 def seek(self, offset, whence):
426 if whence == 0:
427 self.pos = max(0, offset)
428 elif whence == 1:
429 self.pos = max(0, self.pos + offset)
430 elif whence == 2:
431 self.pos = max(0, self.mm.size() + offset)
432 else:
433 raise StreamError("seek(): whence must be 0, 1 or 2")
434
435 def readall(self):
436 filesize = self.mm.size() # Actual file size, may be more than mapped
437 n = filesize - self.pos
438 data = self.mm[self.pos:]
439 if len(data) < n:
440 del data
441 # File grew since opened; remap to get the new data
442 self.remapfile()
443 data = self.mm[self.pos:]
444 self.pos += len(data)
445 return data
446
447 def read(self, n):
448 assert isinstance(n, int)
449 end = self.pos + n
450 data = self.mm[self.pos:end]
451 if not data:
452 # is there more data to read?
453 filesize = self.mm.size() #Actual file size, may be more than mapped
454 if filesize > self.pos:
455 # File grew since opened; remap to get the new data
456 self.remapfile()
457 data = self.mm[self.pos:end]
458 self.pos += len(data)
459 return data
460
461 def readline(self):
462 hit = self.mm.find("\n", self.pos) + 1
463 if not hit:
464 # is there more data to read?
465 filesize = self.mm.size() #Actual file size, may be more than mapped
466 if filesize > len(self.mm):
467 # File grew since opened; remap to get the new data
468 self.remapfile()
469 hit = self.mm.find("\n", self.pos) + 1
470 if hit:
471 # Got a whole line
472 data = self.mm[self.pos:hit]
473 self.pos = hit
474 else:
475 # Read whatever we've got -- may be empty
476 data = self.mm[self.pos:]
477 self.pos += len(data)
478 return data
479
480 def write(self, data):
481 end = self.pos + len(data)
482 try:
483 self.mm[self.pos:end] = data
484 # This can raise IndexError on Windows, ValueError on Unix
485 except (IndexError, ValueError):
486 # XXX On Unix, this resize() call doesn't work
487 self.mm.resize(end)
488 self.mm[self.pos:end] = data
489 self.pos = end
490
491 def flush(self):
492 self.mm.flush()
493
494 def flushable(self):
495 import mmap
496 return self.access == mmap.ACCESS_WRITE
497
498 def try_to_find_file_descriptor(self):
499 return self.fd
500
501 # ____________________________________________________________
502
503 STREAM_METHODS = dict([
504 ("read", [int]),
505 ("write", [str]),
506 ("tell", []),
507 ("seek", [r_longlong, int]),
508 ("readall", []),
509 ("readline", []),
510 ("truncate", [r_longlong]),
511 ("flush", []),
512 ("flushable", []),
513 ("close1", [int]),
514 ("peek", []),
515 ("try_to_find_file_descriptor", []),
516 ("getnewlines", []),
517 ])
518
519 def PassThrough(meth_name, flush_buffers):
520 if meth_name in STREAM_METHODS:
521 signature = STREAM_METHODS[meth_name]
522 args = ", ".join(["v%s" % (i, ) for i in range(len(signature))])
523 else:
524 assert 0, "not a good idea"
525 args = "*args"
526 if flush_buffers:
527 code = """def %s(self, %s):
528 self.flush_buffers()
529 return self.base.%s(%s)
530 """
531 else:
532 code = """def %s(self, %s):
533 return self.base.%s(%s)
534 """
535 d = {}
536 exec(code % (meth_name, args, meth_name, args), d)
537 return d[meth_name]
538
539
540 def offset2int(offset):
541 intoffset = intmask(offset)
542 if intoffset != offset:
543 raise StreamError("seek() from a non-seekable source:"
544 " this would read and discard more"
545 " than sys.maxint bytes")
546 return intoffset
547
548 class BufferingInputStream(Stream):
549 """Standard buffering input stream.
550
551 This, and BufferingOutputStream if needed, are typically at the top of
552 the stack of streams.
553 """
554
555 bigsize = 2**19 # Half a Meg
556 bufsize = 2**13 # 8 K
557
558 def __init__(self, base, bufsize=-1):
559 self.base = base
560 self.do_read = base.read # function to fill buffer some more
561 self.do_tell = base.tell # return a byte offset
562 self.do_seek = base.seek # seek to a byte offset
563 if bufsize == -1: # Get default from the class
564 bufsize = self.bufsize
565 self.bufsize = bufsize # buffer size (hint only)
566 self.buf = "" # raw data
567 self.pos = 0
568
569 def flush_buffers(self):
570 if self.buf:
571 try:
572 self.do_seek(self.pos - len(self.buf), 1)
573 except (MyNotImplementedError, OSError):
574 pass
575 else:
576 self.buf = ""
577 self.pos = 0
578
579 def tell(self):
580 tellpos = self.do_tell() # This may fail
581 # Best-effort: to avoid extra system calls to tell() all the
582 # time, and a more complicated logic in this class, we can
583 # only assume that nobody changed the underlying file
584 # descriptor position while we have buffered data. If they
585 # do, we might get bogus results here (and the following
586 # read() will still return the data cached at the old
587 # position). Just make sure that we don't fail an assert.
588 offset = len(self.buf) - self.pos
589 if tellpos < offset:
590 # bug! someone changed the fd position under our feet,
591 # and moved it at or very close to the beginning of the
592 # file, so that we have more buffered data than the
593 # current offset.
594 self.buf = ""
595 self.pos = 0
596 offset = 0
597 return tellpos - offset
598
599 def seek(self, offset, whence):
600 # This may fail on the do_seek() or on the tell() call.
601 # But it won't depend on either on a relative forward seek.
602 # Nor on a seek to the very end.
603 if whence == 0 or whence == 1:
604 if whence == 0:
605 difpos = offset - self.tell() # may clean up self.buf/self.pos
606 else:
607 difpos = offset
608 currentsize = len(self.buf) - self.pos
609 if -self.pos <= difpos <= currentsize:
610 self.pos += intmask(difpos)
611 return
612 if whence == 1:
613 offset -= currentsize
614 try:
615 self.do_seek(offset, whence)
616 except MyNotImplementedError:
617 self.buf = ""
618 self.pos = 0
619 if difpos < 0:
620 raise
621 if whence == 0:
622 offset = difpos - currentsize
623 intoffset = offset2int(offset)
624 self.read(intoffset)
625 else:
626 self.buf = ""
627 self.pos = 0
628 return
629 if whence == 2:
630 try:
631 self.do_seek(offset, 2)
632 except MyNotImplementedError:
633 pass
634 else:
635 self.pos = 0
636 self.buf = ""
637 return
638 # Skip relative to EOF by reading and saving only just as
639 # much as needed
640 intoffset = offset2int(offset)
641 pos = self.pos
642 assert pos >= 0
643 buffers = [self.buf[pos:]]
644 total = len(buffers[0])
645 self.buf = ""
646 self.pos = 0
647 while 1:
648 data = self.do_read(self.bufsize)
649 if not data:
650 break
651 buffers.append(data)
652 total += len(data)
653 while buffers and total >= len(buffers[0]) - intoffset:
654 total -= len(buffers[0])
655 del buffers[0]
656 cutoff = total + intoffset
657 if cutoff < 0:
658 raise StreamError("cannot seek back")
659 if buffers:
660 assert cutoff >= 0
661 buffers[0] = buffers[0][cutoff:]
662 self.buf = "".join(buffers)
663 return
664
665 raise StreamError("whence should be 0, 1 or 2")
666
667 def readall(self):
668 pos = self.pos
669 assert pos >= 0
670 builder = StringBuilder()
671 if self.buf:
672 builder.append_slice(self.buf, pos, len(self.buf))
673 self.buf = ""
674 self.pos = 0
675 bufsize = self.bufsize
676 while 1:
677 try:
678 data = self.do_read(bufsize)
679 except OSError as o:
680 # like CPython < 3.4, partial results followed by an error
681 # are returned as data
682 if not builder.getlength():
683 raise
684 break
685 if not data:
686 break
687 builder.append(data)
688 bufsize = min(bufsize*2, self.bigsize)
689 return builder.build()
690
691 def read(self, n=-1):
692 assert isinstance(n, int)
693 if n < 0:
694 return self.readall()
695 currentsize = len(self.buf) - self.pos
696 start = self.pos
697 assert start >= 0
698 if n <= currentsize:
699 stop = start + n
700 assert stop >= 0
701 result = self.buf[start:stop]
702 self.pos += n
703 return result
704 else:
705 builder = StringBuilder(n)
706 builder.append_slice(self.buf, start, len(self.buf))
707 while 1:
708 self.buf = self.do_read(self.bufsize)
709 if not self.buf:
710 self.pos = 0
711 break
712 currentsize += len(self.buf)
713 if currentsize >= n:
714 self.pos = len(self.buf) - (currentsize - n)
715 stop = self.pos
716 assert stop >= 0
717 builder.append_slice(self.buf, 0, stop)
718 break
719 buf = self.buf
720 assert buf is not None
721 builder.append(buf)
722 return builder.build()
723
724 def readline(self):
725 pos = self.pos
726 assert pos >= 0
727 i = self.buf.find("\n", pos)
728 start = self.pos
729 assert start >= 0
730 if i >= 0: # new line found
731 i += 1
732 result = self.buf[start:i]
733 self.pos = i
734 return result
735 temp = self.buf[start:]
736 # read one buffer and most of the time a new line will be found
737 self.buf = self.do_read(self.bufsize)
738 i = self.buf.find("\n")
739 if i >= 0: # new line found
740 i += 1
741 result = temp + self.buf[:i]
742 self.pos = i
743 return result
744 if not self.buf:
745 self.pos = 0
746 return temp
747 # need to keep getting data until we find a new line
748 builder = StringBuilder(len(temp) + len(self.buf)) # at least
749 builder.append(temp)
750 builder.append(self.buf)
751 while 1:
752 self.buf = self.do_read(self.bufsize)
753 if not self.buf:
754 self.pos = 0
755 break
756 i = self.buf.find("\n")
757 if i >= 0:
758 i += 1
759 builder.append_slice(self.buf, 0, i)
760 self.pos = i
761 break
762 builder.append(self.buf)
763 return builder.build()
764
765 def peek(self):
766 return (self.pos, self.buf)
767
768 write = PassThrough("write", flush_buffers=True)
769 truncate = PassThrough("truncate", flush_buffers=True)
770 flush = PassThrough("flush", flush_buffers=True)
771 flushable = PassThrough("flushable", flush_buffers=False)
772 close1 = PassThrough("close1", flush_buffers=False)
773 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
774 flush_buffers=False)
775
776
777 class BufferingOutputStream(Stream):
778 """Standard buffering output stream.
779
780 This, and BufferingInputStream if needed, are typically at the top of
781 the stack of streams.
782 """
783
784 bigsize = 2**19 # Half a Meg
785 bufsize = 2**13 # 8 K
786
787 def __init__(self, base, bufsize=-1):
788 self.base = base
789 self.do_tell = base.tell # return a byte offset
790 if bufsize == -1: # Get default from the class
791 bufsize = self.bufsize
792 self.bufsize = bufsize # buffer size (hint only)
793 self.buf = []
794 self.buflen = 0
795 self.error = False
796
797 def do_write(self, data):
798 try:
799 self.base.write(data)
800 except:
801 self.error = True
802 raise
803
804 def flush_buffers(self):
805 if self.buf and not self.error:
806 self.do_write(''.join(self.buf))
807 self.buf = []
808 self.buflen = 0
809
810 def tell(self):
811 return self.do_tell() + self.buflen
812
813 def write(self, data):
814 self.error = False
815 buflen = self.buflen
816 datalen = len(data)
817 if datalen + buflen < self.bufsize:
818 self.buf.append(data)
819 self.buflen += datalen
820 elif buflen:
821 self.buf.append(data)
822 self.do_write(''.join(self.buf))
823 self.buf = []
824 self.buflen = 0
825 else:
826 self.do_write(data)
827
828 read = PassThrough("read", flush_buffers=True)
829 readall = PassThrough("readall", flush_buffers=True)
830 readline = PassThrough("readline", flush_buffers=True)
831 seek = PassThrough("seek", flush_buffers=True)
832 truncate = PassThrough("truncate", flush_buffers=True)
833 flush = PassThrough("flush", flush_buffers=True)
834 close1 = PassThrough("close1", flush_buffers=True)
835 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
836 flush_buffers=False)
837
838 def flushable(self):
839 return True
840
841
842 class LineBufferingOutputStream(BufferingOutputStream):
843 """Line buffering output stream.
844
845 This is typically the top of the stack.
846 """
847
848 def write(self, data):
849 self.error = False
850 p = data.rfind('\n') + 1
851 assert p >= 0
852 if self.buflen + len(data) < self.bufsize:
853 if p == 0:
854 self.buf.append(data)
855 self.buflen += len(data)
856 else:
857 if self.buflen:
858 self.buf.append(data[:p])
859 self.do_write(''.join(self.buf))
860 else:
861 self.do_write(data[:p])
862 self.buf = [data[p:]]
863 self.buflen = len(self.buf[0])
864 else:
865 if self.buflen + p < self.bufsize:
866 p = self.bufsize - self.buflen
867 if self.buflen:
868 self.do_write(''.join(self.buf))
869 assert p >= 0
870 self.do_write(data[:p])
871 self.buf = [data[p:]]
872 self.buflen = len(self.buf[0])
873
874 # ____________________________________________________________
875
876 class CRLFFilter(Stream):
877 """Filtering stream for universal newlines.
878
879 TextInputFilter is more general, but this is faster when you don't
880 need tell/seek.
881 """
882
883 def __init__(self, base):
884 self.base = base
885 self.do_read = base.read
886 self.atcr = False
887
888 def read(self, n):
889 data = self.do_read(n)
890 if self.atcr:
891 if data.startswith("\n"):
892 data = data[1:] # Very rare case: in the middle of "\r\n"
893 self.atcr = False
894 if "\r" in data:
895 self.atcr = data.endswith("\r") # Test this before removing \r
896 data = replace_crlf_with_lf(data)
897 return data
898
899 flush = PassThrough("flush", flush_buffers=False)
900 flushable= PassThrough("flushable", flush_buffers=False)
901 close1 = PassThrough("close1", flush_buffers=False)
902 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
903 flush_buffers=False)
904
905 class TextCRLFFilter(Stream):
906 """Filtering stream for universal newlines.
907
908 TextInputFilter is more general, but this is faster when you don't
909 need tell/seek.
910 """
911
912 def __init__(self, base):
913 self.base = base
914 self.do_read = base.read
915 self.do_write = base.write
916 self.do_flush = base.flush_buffers
917 self.readahead_count = 0 # either 0 or 1
918
919 def read(self, n=-1):
920 """If n >= 1, this should read between 1 and n bytes."""
921 if n <= 0:
922 if n < 0:
923 return self.readall()
924 else:
925 return ""
926
927 data = self.do_read(n - self.readahead_count)
928 if self.readahead_count > 0:
929 data = self.readahead_char + data
930 self.readahead_count = 0
931
932 if data.endswith("\r"):
933 c = self.do_read(1)
934 if len(c) >= 1:
935 assert len(c) == 1
936 if c[0] == '\n':
937 data = data + '\n'
938 else:
939 self.readahead_char = c[0]
940 self.readahead_count = 1
941
942 result = []
943 offset = 0
944 while True:
945 newoffset = data.find('\r\n', offset)
946 if newoffset < 0:
947 result.append(data[offset:])
948 break
949 result.append(data[offset:newoffset])
950 offset = newoffset + 2
951
952 return '\n'.join(result)
953
954 def readline(self):
955 line = self.base.readline()
956 limit = len(line) - 2
957 if limit >= 0 and line[limit] == '\r' and line[limit + 1] == '\n':
958 line = line[:limit] + '\n'
959 return line
960
961 def tell(self):
962 pos = self.base.tell()
963 return pos - self.readahead_count
964
965 def seek(self, offset, whence):
966 if whence == 1:
967 offset -= self.readahead_count # correct for already-read-ahead character
968 self.base.seek(offset, whence)
969 self.readahead_count = 0
970
971 def flush_buffers(self):
972 if self.readahead_count > 0:
973 try:
974 self.base.seek(-self.readahead_count, 1)
975 except (MyNotImplementedError, OSError):
976 return
977 self.readahead_count = 0
978 self.do_flush()
979
980 def write(self, data):
981 data = replace_char_with_str(data, '\n', '\r\n')
982 self.flush_buffers()
983 self.do_write(data)
984
985 truncate = PassThrough("truncate", flush_buffers=True)
986 flush = PassThrough("flush", flush_buffers=False)
987 flushable= PassThrough("flushable", flush_buffers=False)
988 close1 = PassThrough("close1", flush_buffers=False)
989 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
990 flush_buffers=False)
991
992 class TextInputFilter(Stream):
993 """Filtering input stream for universal newline translation."""
994
995 def __init__(self, base):
996 self.base = base # must implement read, may implement tell, seek
997 self.do_read = base.read
998 self.atcr = False # Set when last char read was \r
999 self.buf = "" # Optional one-character read-ahead buffer
1000 self.CR = False
1001 self.NL = False
1002 self.CRLF = False
1003
1004 def getnewlines(self):
1005 return self.CR * 1 + self.NL * 2 + self.CRLF * 4
1006
1007 def read(self, n):
1008 """Read up to n bytes."""
1009 if self.buf:
1010 assert not self.atcr
1011 data = self.buf
1012 self.buf = ""
1013 else:
1014 data = self.do_read(n)
1015
1016 # The following whole ugly mess is because we need to keep track of
1017 # exactly which line separators we have seen for self.newlines,
1018 # grumble, grumble. This has an interesting corner-case.
1019 #
1020 # Consider a file consisting of exactly one line ending with '\r'.
1021 # The first time you read(), you will not know whether it is a
1022 # CR separator or half of a CRLF separator. Neither will be marked
1023 # as seen, since you are waiting for your next read to determine
1024 # what you have seen. But there's no more to read ...
1025
1026 if self.atcr:
1027 if data.startswith("\n"):
1028 data = data[1:]
1029 self.CRLF = True
1030 if not data:
1031 data = self.do_read(n)
1032 else:
1033 self.CR = True
1034 self.atcr = False
1035
1036 seen_cr = -1
1037 for i in range(len(data)):
1038 if data[i] == '\n':
1039 if i > 0 and data[i-1] == '\r':
1040 if seen_cr < 0:
1041 seen_cr = i - 1
1042 self.CRLF = True
1043 else:
1044 self.NL = True
1045 elif data[i] == '\r':
1046 if seen_cr < 0:
1047 seen_cr = i
1048 if i < len(data)-1 and data[i+1] != '\n':
1049 self.CR = True
1050
1051 if seen_cr >= 0:
1052 self.atcr = data.endswith("\r")
1053 data = replace_crlf_with_lf(data, first_index=seen_cr)
1054
1055 return data
1056
1057 def readline(self):
1058 result = []
1059 while True:
1060 # "peeks" on the underlying stream to see how many characters
1061 # we can safely read without reading past an end-of-line
1062 startindex, peeked = self.base.peek()
1063 assert 0 <= startindex <= len(peeked)
1064 cl_or_lf_pos = len(peeked)
1065 for i in range(startindex, len(peeked)):
1066 ch = peeked[i]
1067 if ch == '\n' or ch == '\r':
1068 cl_or_lf_pos = i
1069 break
1070 c = self.read(cl_or_lf_pos - startindex + 1)
1071 if not c:
1072 break
1073 result.append(c)
1074 if c.endswith('\n'):
1075 break
1076 return ''.join(result)
1077
1078 def seek(self, offset, whence):
1079 """Seeks based on knowledge that does not come from a tell()
1080 may go to the wrong place, since the number of
1081 characters seen may not match the number of characters
1082 that are actually in the file (where \r\n is the
1083 line separator). Arithmetics on the result
1084 of a tell() that moves beyond a newline character may in the
1085 same way give the wrong result.
1086 """
1087 if whence == 1:
1088 offset -= len(self.buf) # correct for already-read-ahead character
1089 self.base.seek(offset, whence)
1090 self.atcr = False
1091 self.buf = ""
1092
1093 def tell(self):
1094 pos = self.base.tell()
1095 if self.atcr:
1096 # Must read the next byte to see if it's \n,
1097 # because then we must report the next position.
1098 assert not self.buf
1099 self.buf = self.do_read(1)
1100 pos += 1
1101 self.atcr = False
1102 if self.buf == "\n":
1103 self.CRLF = True
1104 self.buf = ""
1105 return pos - len(self.buf)
1106
1107 def flush_buffers(self):
1108 if self.atcr:
1109 assert not self.buf
1110 self.buf = self.do_read(1)
1111 self.atcr = False
1112 if self.buf == "\n":
1113 self.buf = ""
1114 if self.buf:
1115 try:
1116 self.base.seek(-len(self.buf), 1)
1117 except (MyNotImplementedError, OSError):
1118 pass
1119 else:
1120 self.buf = ""
1121
1122 def peek(self):
1123 return (0, self.buf)
1124
1125 write = PassThrough("write", flush_buffers=True)
1126 truncate = PassThrough("truncate", flush_buffers=True)
1127 flush = PassThrough("flush", flush_buffers=True)
1128 flushable = PassThrough("flushable", flush_buffers=False)
1129 close1 = PassThrough("close1", flush_buffers=False)
1130 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
1131 flush_buffers=False)
1132
1133
1134 class TextOutputFilter(Stream):
1135 """Filtering output stream for universal newline translation."""
1136
1137 def __init__(self, base, linesep=os.linesep):
1138 assert linesep in ["\n", "\r\n", "\r"]
1139 self.base = base # must implement write, may implement seek, tell
1140 self.linesep = linesep
1141
1142 def write(self, data):
1143 data = replace_char_with_str(data, "\n", self.linesep)
1144 self.base.write(data)
1145
1146 tell = PassThrough("tell", flush_buffers=False)
1147 seek = PassThrough("seek", flush_buffers=False)
1148 read = PassThrough("read", flush_buffers=False)
1149 readall = PassThrough("readall", flush_buffers=False)
1150 readline = PassThrough("readline", flush_buffers=False)
1151 truncate = PassThrough("truncate", flush_buffers=False)
1152 flush = PassThrough("flush", flush_buffers=False)
1153 flushable = PassThrough("flushable", flush_buffers=False)
1154 close1 = PassThrough("close1", flush_buffers=False)
1155 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
1156 flush_buffers=False)
1157
1158
1159 class CallbackReadFilter(Stream):
1160 """Pseudo read filter that invokes a callback before blocking on a read.
1161 """
1162
1163 def __init__(self, base, callback):
1164 self.base = base
1165 self.callback = callback
1166
1167 def flush_buffers(self):
1168 self.callback()
1169
1170 tell = PassThrough("tell", flush_buffers=False)
1171 seek = PassThrough("seek", flush_buffers=False)
1172 read = PassThrough("read", flush_buffers=True)
1173 readall = PassThrough("readall", flush_buffers=True)
1174 readline = PassThrough("readline", flush_buffers=True)
1175 peek = PassThrough("peek", flush_buffers=False)
1176 flush = PassThrough("flush", flush_buffers=False)
1177 flushable = PassThrough("flushable", flush_buffers=False)
1178 close1 = PassThrough("close1", flush_buffers=False)
1179 write = PassThrough("write", flush_buffers=False)
1180 truncate = PassThrough("truncate", flush_buffers=False)
1181 getnewlines= PassThrough("getnewlines",flush_buffers=False)
1182 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
1183 flush_buffers=False)
1184
1185 # _________________________________________________
1186 # The following functions are _not_ RPython!
1187
1188 class DecodingInputFilter(Stream):
1189 """Filtering input stream that decodes an encoded file."""
1190
1191 @not_rpython
1192 def __init__(self, base, encoding="utf8", errors="strict"):
1193 self.base = base
1194 self.do_read = base.read
1195 self.encoding = encoding
1196 self.errors = errors
1197
1198 def read(self, n):
1199 """Read *approximately* n bytes, then decode them.
1200
1201 Under extreme circumstances,
1202 the return length could be longer than n!
1203
1204 Always return a unicode string.
1205
1206 This does *not* translate newlines;
1207 you can stack TextInputFilter.
1208 """
1209 data = self.do_read(n)
1210 try:
1211 return data.decode(self.encoding, self.errors)
1212 except ValueError:
1213 # XXX Sigh. decode() doesn't handle incomplete strings well.
1214 # Use the retry strategy from codecs.StreamReader.
1215 for i in range(9):
1216 more = self.do_read(1)
1217 if not more:
1218 raise
1219 data += more
1220 try:
1221 return data.decode(self.encoding, self.errors)
1222 except ValueError:
1223 pass
1224 raise
1225
1226 write = PassThrough("write", flush_buffers=False)
1227 truncate = PassThrough("truncate", flush_buffers=False)
1228 flush = PassThrough("flush", flush_buffers=False)
1229 flushable = PassThrough("flushable", flush_buffers=False)
1230 close1 = PassThrough("close1", flush_buffers=False)
1231 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
1232 flush_buffers=False)
1233
1234 class EncodingOutputFilter(Stream):
1235 """Filtering output stream that writes to an encoded file."""
1236
1237 @not_rpython
1238 def __init__(self, base, encoding="utf8", errors="strict"):
1239 self.base = base
1240 self.do_write = base.write
1241 self.encoding = encoding
1242 self.errors = errors
1243
1244 def write(self, chars):
1245 if isinstance(chars, str):
1246 chars = unicode(chars) # Fail if it's not ASCII
1247 self.do_write(chars.encode(self.encoding, self.errors))
1248
1249 tell = PassThrough("tell", flush_buffers=False)
1250 seek = PassThrough("seek", flush_buffers=False)
1251 read = PassThrough("read", flush_buffers=False)
1252 readall = PassThrough("readall", flush_buffers=False)
1253 readline = PassThrough("readline", flush_buffers=False)
1254 truncate = PassThrough("truncate", flush_buffers=False)
1255 flush = PassThrough("flush", flush_buffers=False)
1256 flushable = PassThrough("flushable", flush_buffers=False)
1257 close1 = PassThrough("close1", flush_buffers=False)
1258 try_to_find_file_descriptor = PassThrough("try_to_find_file_descriptor",
1259 flush_buffers=False)