codecs.py 34.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
""" codecs -- Python Codec Registry, API and helpers.


Written by Marc-Andre Lemburg (mal@lemburg.com).

(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.

"""#"

10
import builtins, sys
11 12 13

### Registry and builtin stateless codec functions

14 15
try:
    from _codecs import *
16
except ImportError as why:
17
    raise SystemError('Failed to load the builtin codecs: %s' % why)
18

19
__all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE",
20 21
           "BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",
           "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE",
22 23 24 25
           "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE",
           "strict_errors", "ignore_errors", "replace_errors",
           "xmlcharrefreplace_errors",
           "register_error", "lookup_error"]
26

27 28 29
### Constants

#
30 31 32
# Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF)
# and its possible byte string values
# for UTF8/UTF16/UTF32 output and little/big endian machines
33 34
#

35
# UTF-8
36
BOM_UTF8 = b'\xef\xbb\xbf'
37 38

# UTF-16, little endian
39
BOM_LE = BOM_UTF16_LE = b'\xff\xfe'
40 41

# UTF-16, big endian
42
BOM_BE = BOM_UTF16_BE = b'\xfe\xff'
43 44

# UTF-32, little endian
45
BOM_UTF32_LE = b'\xff\xfe\x00\x00'
46 47

# UTF-32, big endian
48
BOM_UTF32_BE = b'\x00\x00\xfe\xff'
49

50
if sys.byteorder == 'little':
51

52 53 54 55 56 57 58 59 60 61 62 63 64
    # UTF-16, native endianness
    BOM = BOM_UTF16 = BOM_UTF16_LE

    # UTF-32, native endianness
    BOM_UTF32 = BOM_UTF32_LE

else:

    # UTF-16, native endianness
    BOM = BOM_UTF16 = BOM_UTF16_BE

    # UTF-32, native endianness
    BOM_UTF32 = BOM_UTF32_BE
65 66 67 68 69 70

# Old broken names (don't use in new code)
BOM32_LE = BOM_UTF16_LE
BOM32_BE = BOM_UTF16_BE
BOM64_LE = BOM_UTF32_LE
BOM64_BE = BOM_UTF32_BE
71 72 73 74


### Codec base classes (defining the API)

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
class CodecInfo(tuple):

    def __new__(cls, encode, decode, streamreader=None, streamwriter=None,
        incrementalencoder=None, incrementaldecoder=None, name=None):
        self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
        self.name = name
        self.encode = encode
        self.decode = decode
        self.incrementalencoder = incrementalencoder
        self.incrementaldecoder = incrementaldecoder
        self.streamwriter = streamwriter
        self.streamreader = streamreader
        return self

    def __repr__(self):
90 91 92
        return "<%s.%s object for encoding %s at 0x%x>" % \
                (self.__class__.__module__, self.__class__.__name__,
                 self.name, id(self))
93

94 95 96 97
class Codec:

    """ Defines the interface for stateless encoders/decoders.

98
        The .encode()/.decode() methods may use different error
99
        handling schemes by providing the errors argument. These
100
        string values are predefined:
101

Guido van Rossum's avatar
Guido van Rossum committed
102
         'strict' - raise a ValueError error (or a subclass)
103 104 105
         'ignore' - ignore the character and continue with the next
         'replace' - replace with a suitable replacement character;
                    Python will use the official U+FFFD REPLACEMENT
106 107 108 109 110 111 112 113
                    CHARACTER for the builtin Unicode codecs on
                    decoding and '?' on encoding.
         'xmlcharrefreplace' - Replace with the appropriate XML
                               character reference (only for encoding).
         'backslashreplace'  - Replace with backslashed escape sequences
                               (only for encoding).

        The set of allowed values can be extended via register_error.
114 115

    """
116
    def encode(self, input, errors='strict'):
117

118
        """ Encodes the object input and returns a tuple (output
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
            object, length consumed).

            errors defines the error handling to apply. It defaults to
            'strict' handling.

            The method may not store state in the Codec instance. Use
            StreamCodec for codecs which have to keep state in order to
            make encoding/decoding efficient.

            The encoder must be able to handle zero length input and
            return an empty object of the output object type in this
            situation.

        """
        raise NotImplementedError

135
    def decode(self, input, errors='strict'):
136 137 138 139 140 141 142

        """ Decodes the object input and returns a tuple (output
            object, length consumed).

            input must be an object which provides the bf_getreadbuf
            buffer slot. Python strings, buffer objects and memory
            mapped files are examples of objects providing this slot.
143

144 145 146 147 148 149 150 151 152 153 154
            errors defines the error handling to apply. It defaults to
            'strict' handling.

            The method may not store state in the Codec instance. Use
            StreamCodec for codecs which have to keep state in order to
            make encoding/decoding efficient.

            The decoder must be able to handle zero length input and
            return an empty object of the output object type in this
            situation.

155
        """
156 157
        raise NotImplementedError

158 159
class IncrementalEncoder(object):
    """
160 161 162
    An IncrementalEncoder encodes an input in multiple steps. The input can
    be passed piece by piece to the encode() method. The IncrementalEncoder
    remembers the state of the encoding process between calls to encode().
163 164 165
    """
    def __init__(self, errors='strict'):
        """
166
        Creates an IncrementalEncoder instance.
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

        The IncrementalEncoder may use different error handling schemes by
        providing the errors keyword argument. See the module docstring
        for a list of possible values.
        """
        self.errors = errors
        self.buffer = ""

    def encode(self, input, final=False):
        """
        Encodes input and returns the resulting object.
        """
        raise NotImplementedError

    def reset(self):
        """
        Resets the encoder to the initial state.
        """

186 187 188 189 190 191 192 193 194 195 196 197
    def getstate(self):
        """
        Return the current state of the encoder.
        """
        return 0

    def setstate(self, state):
        """
        Set the current state of the encoder. state must have been
        returned by getstate().
        """

198 199 200 201 202 203 204 205
class BufferedIncrementalEncoder(IncrementalEncoder):
    """
    This subclass of IncrementalEncoder can be used as the baseclass for an
    incremental encoder if the encoder must keep some of the output in a
    buffer between calls to encode().
    """
    def __init__(self, errors='strict'):
        IncrementalEncoder.__init__(self, errors)
206 207
        # unencoded input that is kept between calls to encode()
        self.buffer = ""
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

    def _buffer_encode(self, input, errors, final):
        # Overwrite this method in subclasses: It must encode input
        # and return an (output, length consumed) tuple
        raise NotImplementedError

    def encode(self, input, final=False):
        # encode input (taking the buffer into account)
        data = self.buffer + input
        (result, consumed) = self._buffer_encode(data, self.errors, final)
        # keep unencoded input until the next call
        self.buffer = data[consumed:]
        return result

    def reset(self):
        IncrementalEncoder.reset(self)
        self.buffer = ""

226 227 228 229 230 231
    def getstate(self):
        return self.buffer or 0

    def setstate(self, state):
        self.buffer = state or ""

232 233
class IncrementalDecoder(object):
    """
234 235
    An IncrementalDecoder decodes an input in multiple steps. The input can
    be passed piece by piece to the decode() method. The IncrementalDecoder
236 237 238 239
    remembers the state of the decoding process between calls to decode().
    """
    def __init__(self, errors='strict'):
        """
240
        Create a IncrementalDecoder instance.
241 242 243 244 245 246 247 248 249

        The IncrementalDecoder may use different error handling schemes by
        providing the errors keyword argument. See the module docstring
        for a list of possible values.
        """
        self.errors = errors

    def decode(self, input, final=False):
        """
250
        Decode input and returns the resulting object.
251 252 253 254 255
        """
        raise NotImplementedError

    def reset(self):
        """
256
        Reset the decoder to the initial state.
257 258
        """

259 260
    def getstate(self):
        """
261 262 263 264 265 266 267 268 269
        Return the current state of the decoder.

        This must be a (buffered_input, additional_state_info) tuple.
        buffered_input must be a bytes object containing bytes that
        were passed to decode() that have not yet been converted.
        additional_state_info must be a non-negative integer
        representing the state of the decoder WITHOUT yet having
        processed the contents of buffered_input.  In the initial state
        and after reset(), getstate() must return (b"", 0).
270
        """
271
        return (b"", 0)
272 273 274

    def setstate(self, state):
        """
275 276 277 278
        Set the current state of the decoder.

        state must have been returned by getstate().  The effect of
        setstate((b"", 0)) must be equivalent to reset().
279 280
        """

281 282 283
class BufferedIncrementalDecoder(IncrementalDecoder):
    """
    This subclass of IncrementalDecoder can be used as the baseclass for an
284 285
    incremental decoder if the decoder must be able to handle incomplete
    byte sequences.
286 287 288
    """
    def __init__(self, errors='strict'):
        IncrementalDecoder.__init__(self, errors)
289
        # undecoded input that is kept between calls to decode()
290
        self.buffer = b""
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

    def _buffer_decode(self, input, errors, final):
        # Overwrite this method in subclasses: It must decode input
        # and return an (output, length consumed) tuple
        raise NotImplementedError

    def decode(self, input, final=False):
        # decode input (taking the buffer into account)
        data = self.buffer + input
        (result, consumed) = self._buffer_decode(data, self.errors, final)
        # keep undecoded input until the next call
        self.buffer = data[consumed:]
        return result

    def reset(self):
        IncrementalDecoder.reset(self)
307
        self.buffer = b""
308

309 310 311 312 313 314 315 316
    def getstate(self):
        # additional state info is always 0
        return (self.buffer, 0)

    def setstate(self, state):
        # ignore additional state info
        self.buffer = state[0]

317 318
#
# The StreamWriter and StreamReader class provide generic working
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
319
# interfaces which can be used to implement new encoding submodules
320 321
# very easily. See encodings/utf_8.py for an example on how this is
# done.
322
#
323 324 325

class StreamWriter(Codec):

326
    def __init__(self, stream, errors='strict'):
327 328 329 330 331 332

        """ Creates a StreamWriter instance.

            stream must be a file-like object open for writing
            (binary) data.

333
            The StreamWriter may use different error handling
334
            schemes by providing the errors keyword argument. These
335
            parameters are predefined:
336 337 338 339

             'strict' - raise a ValueError (or a subclass)
             'ignore' - ignore the character and continue with the next
             'replace'- replace with a suitable replacement character
340 341 342 343
             'xmlcharrefreplace' - Replace with the appropriate XML
                                   character reference.
             'backslashreplace'  - Replace with backslashed escape
                                   sequences (only for encoding).
344

345 346
            The set of allowed parameter values can be extended via
            register_error.
347 348 349 350
        """
        self.stream = stream
        self.errors = errors

Guido van Rossum's avatar
Guido van Rossum committed
351
    def write(self, object):
352 353 354

        """ Writes the object's contents encoded to self.stream.
        """
355
        data, consumed = self.encode(object, self.errors)
356 357
        self.stream.write(data)

Guido van Rossum's avatar
Guido van Rossum committed
358 359 360 361 362 363
    def writelines(self, list):

        """ Writes the concatenated list of strings to the stream
            using .write().
        """
        self.write(''.join(list))
364

365 366 367 368 369 370 371 372 373 374 375 376
    def reset(self):

        """ Flushes and resets the codec buffers used for keeping state.

            Calling this method should ensure that the data on the
            output is put into a clean state, that allows appending
            of new fresh data without having to rescan the whole
            stream to recover state.

        """
        pass

377 378 379 380 381
    def seek(self, offset, whence=0):
        self.stream.seek(offset, whence)
        if whence == 0 and offset == 0:
            self.reset()

382
    def __getattr__(self, name,
383 384 385 386
                    getattr=getattr):

        """ Inherit all other methods from the underlying stream.
        """
387
        return getattr(self.stream, name)
388

389 390 391 392 393 394
    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

395 396 397 398
###

class StreamReader(Codec):

399 400
    charbuffertype = str

401
    def __init__(self, stream, errors='strict'):
402 403 404 405 406 407

        """ Creates a StreamReader instance.

            stream must be a file-like object open for reading
            (binary) data.

408
            The StreamReader may use different error handling
409
            schemes by providing the errors keyword argument. These
410
            parameters are predefined:
411 412 413 414 415

             'strict' - raise a ValueError (or a subclass)
             'ignore' - ignore the character and continue with the next
             'replace'- replace with a suitable replacement character;

416 417
            The set of allowed parameter values can be extended via
            register_error.
418 419 420
        """
        self.stream = stream
        self.errors = errors
421
        self.bytebuffer = b""
422 423
        self._empty_charbuffer = self.charbuffertype()
        self.charbuffer = self._empty_charbuffer
424
        self.linebuffer = None
425

426 427 428
    def decode(self, input, errors='strict'):
        raise NotImplementedError

429
    def read(self, size=-1, chars=-1, firstline=False):
430 431 432 433

        """ Decodes data from the stream self.stream and returns the
            resulting object.

434 435 436 437 438
            chars indicates the number of characters to read from the
            stream. read() will never return more than chars
            characters, but it might return less, if there are not enough
            characters available.

439 440 441 442 443 444 445
            size indicates the approximate maximum number of bytes to
            read from the stream for decoding purposes. The decoder
            can modify this setting as appropriate. The default value
            -1 indicates to read and decode as much as possible.  size
            is intended to prevent having to decode huge files in one
            step.

446 447 448 449 450
            If firstline is true, and a UnicodeDecodeError happens
            after the first line terminator in the input only the first line
            will be returned, the rest of the input will be kept until the
            next call to read().

451 452 453 454 455 456
            The method should use a greedy read strategy meaning that
            it should read as much data as is allowed within the
            definition of the encoding and the given size, e.g.  if
            optional encoding endings or state markers are available
            on the stream, these should be read too.
        """
457 458
        # If we have lines cached, first merge them back into characters
        if self.linebuffer:
459
            self.charbuffer = self._empty_charbuffer.join(self.linebuffer)
460
            self.linebuffer = None
Tim Peters's avatar
Tim Peters committed
461

462 463 464 465
        # read until we get the required number of characters (if available)
        while True:
            # can the request can be satisfied from the character buffer?
            if chars < 0:
466 467 468 469
                if size < 0:
                    if self.charbuffer:
                        break
                elif len(self.charbuffer) >= size:
470
                    break
471
            else:
472 473 474 475 476 477 478
                if len(self.charbuffer) >= chars:
                    break
            # we need more data
            if size < 0:
                newdata = self.stream.read()
            else:
                newdata = self.stream.read(size)
479
            # decode bytes (those remaining from the last call included)
480
            data = self.bytebuffer + newdata
481 482
            try:
                newchars, decodedbytes = self.decode(data, self.errors)
483
            except UnicodeDecodeError as exc:
484
                if firstline:
485 486
                    newchars, decodedbytes = \
                        self.decode(data[:exc.start], self.errors)
487
                    lines = newchars.splitlines(keepends=True)
488 489 490 491
                    if len(lines)<=1:
                        raise
                else:
                    raise
492 493 494
            # keep undecoded bytes until the next call
            self.bytebuffer = data[decodedbytes:]
            # put new characters in the character buffer
495
            self.charbuffer += newchars
496 497
            # there was no data available
            if not newdata:
498 499 500 501
                break
        if chars < 0:
            # Return everything we've got
            result = self.charbuffer
502
            self.charbuffer = self._empty_charbuffer
503 504 505 506
        else:
            # Return the first chars characters
            result = self.charbuffer[:chars]
            self.charbuffer = self.charbuffer[chars:]
507 508 509
        return result

    def readline(self, size=None, keepends=True):
Guido van Rossum's avatar
Guido van Rossum committed
510 511 512 513

        """ Read one line from the input stream and return the
            decoded data.

514 515
            size, if given, is passed as size argument to the
            read() method.
516

Guido van Rossum's avatar
Guido van Rossum committed
517
        """
518 519 520 521 522 523 524 525 526 527 528
        # If we have lines cached from an earlier read, return
        # them unconditionally
        if self.linebuffer:
            line = self.linebuffer[0]
            del self.linebuffer[0]
            if len(self.linebuffer) == 1:
                # revert to charbuffer mode; we might need more data
                # next time
                self.charbuffer = self.linebuffer[0]
                self.linebuffer = None
            if not keepends:
529
                line = line.splitlines(keepends=False)[0]
530
            return line
Tim Peters's avatar
Tim Peters committed
531

532
        readsize = size or 72
533
        line = self._empty_charbuffer
534
        # If size is given, we call read() only once
535
        while True:
536
            data = self.read(readsize, firstline=True)
537
            if data:
Walter Dörwald's avatar
Walter Dörwald committed
538 539
                # If we're at a "\r" read one extra character (which might
                # be a "\n") to get a proper line ending. If the stream is
540
                # temporarily exhausted we return the wrong line ending.
541 542
                if (isinstance(data, str) and data.endswith("\r")) or \
                   (isinstance(data, bytes) and data.endswith(b"\r")):
543 544
                    data += self.read(size=1, chars=1)

545
            line += data
546
            lines = line.splitlines(keepends=True)
547
            if lines:
548 549 550 551 552 553 554 555 556 557 558 559 560 561
                if len(lines) > 1:
                    # More than one line result; the first line is a full line
                    # to return
                    line = lines[0]
                    del lines[0]
                    if len(lines) > 1:
                        # cache the remaining lines
                        lines[-1] += self.charbuffer
                        self.linebuffer = lines
                        self.charbuffer = None
                    else:
                        # only one remaining line, put it back into charbuffer
                        self.charbuffer = lines[0] + self.charbuffer
                    if not keepends:
562
                        line = line.splitlines(keepends=False)[0]
563
                    break
564
                line0withend = lines[0]
565
                line0withoutend = lines[0].splitlines(keepends=False)[0]
566 567
                if line0withend != line0withoutend: # We really have a line end
                    # Put the rest back together and keep it until the next call
568 569
                    self.charbuffer = self._empty_charbuffer.join(lines[1:]) + \
                                      self.charbuffer
570 571 572 573
                    if keepends:
                        line = line0withend
                    else:
                        line = line0withoutend
574
                    break
575
            # we didn't get anything or this was our only try
576
            if not data or size is not None:
577
                if line and not keepends:
578
                    line = line.splitlines(keepends=False)[0]
579
                break
580
            if readsize < 8000:
581 582
                readsize *= 2
        return line
583 584

    def readlines(self, sizehint=None, keepends=True):
Guido van Rossum's avatar
Guido van Rossum committed
585 586 587 588 589 590

        """ Read all lines available on the input stream
            and return them as list of lines.

            Line breaks are implemented using the codec's decoder
            method and are included in the list entries.
591

592 593
            sizehint, if given, is ignored since there is no efficient
            way to finding the true end-of-line.
Guido van Rossum's avatar
Guido van Rossum committed
594 595

        """
596
        data = self.read()
597
        return data.splitlines(keepends)
598 599 600 601 602 603

    def reset(self):

        """ Resets the codec buffers used for keeping state.

            Note that no stream repositioning should take place.
604
            This method is primarily intended to be able to recover
605 606 607
            from decoding errors.

        """
608
        self.bytebuffer = b""
609
        self.charbuffer = self._empty_charbuffer
610
        self.linebuffer = None
611

612
    def seek(self, offset, whence=0):
613 614 615 616 617
        """ Set the input stream's current position.

            Resets the codec buffers used for keeping state.
        """
        self.stream.seek(offset, whence)
618
        self.reset()
619

620
    def __next__(self):
621 622 623 624 625 626 627 628 629 630

        """ Return the next decoded line from the input stream."""
        line = self.readline()
        if line:
            return line
        raise StopIteration

    def __iter__(self):
        return self

631
    def __getattr__(self, name,
632 633 634 635
                    getattr=getattr):

        """ Inherit all other methods from the underlying stream.
        """
636
        return getattr(self.stream, name)
637

638 639 640 641 642 643
    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

644 645 646 647
###

class StreamReaderWriter:

648 649 650 651
    """ StreamReaderWriter instances allow wrapping streams which
        work in both read and write modes.

        The design is such that one can use the factory functions
652
        returned by the codec.lookup() function to construct the
653 654 655
        instance.

    """
Guido van Rossum's avatar
Guido van Rossum committed
656 657 658
    # Optional attributes set by the file wrappers below
    encoding = 'unknown'

659
    def __init__(self, stream, Reader, Writer, errors='strict'):
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

        """ Creates a StreamReaderWriter instance.

            stream must be a Stream-like object.

            Reader, Writer must be factory functions or classes
            providing the StreamReader, StreamWriter interface resp.

            Error handling is done in the same way as defined for the
            StreamWriter/Readers.

        """
        self.stream = stream
        self.reader = Reader(stream, errors)
        self.writer = Writer(stream, errors)
        self.errors = errors

677
    def read(self, size=-1):
678 679 680

        return self.reader.read(size)

Guido van Rossum's avatar
Guido van Rossum committed
681
    def readline(self, size=None):
Guido van Rossum's avatar
Guido van Rossum committed
682 683 684

        return self.reader.readline(size)

Guido van Rossum's avatar
Guido van Rossum committed
685
    def readlines(self, sizehint=None):
Guido van Rossum's avatar
Guido van Rossum committed
686 687 688

        return self.reader.readlines(sizehint)

689
    def __next__(self):
690 691

        """ Return the next decoded line from the input stream."""
692
        return next(self.reader)
693 694 695 696

    def __iter__(self):
        return self

697
    def write(self, data):
698 699 700

        return self.writer.write(data)

701
    def writelines(self, list):
Guido van Rossum's avatar
Guido van Rossum committed
702 703 704

        return self.writer.writelines(list)

705 706 707 708 709
    def reset(self):

        self.reader.reset()
        self.writer.reset()

710
    def seek(self, offset, whence=0):
711 712 713 714
        self.stream.seek(offset, whence)
        self.reader.reset()
        if whence == 0 and offset == 0:
            self.writer.reset()
715

716
    def __getattr__(self, name,
717 718 719 720
                    getattr=getattr):

        """ Inherit all other methods from the underlying stream.
        """
721
        return getattr(self.stream, name)
722

723 724 725 726 727 728 729 730
    # these are needed to make "with codecs.open(...)" work properly

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

731 732 733 734
###

class StreamRecoder:

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
    """ StreamRecoder instances provide a frontend - backend
        view of encoding data.

        They use the complete set of APIs returned by the
        codecs.lookup() function to implement their task.

        Data written to the stream is first decoded into an
        intermediate format (which is dependent on the given codec
        combination) and then written to the stream using an instance
        of the provided Writer class.

        In the other direction, data is read from the stream using a
        Reader instance and then return encoded data to the caller.

    """
Guido van Rossum's avatar
Guido van Rossum committed
750 751 752 753
    # Optional attributes set by the file wrappers below
    data_encoding = 'unknown'
    file_encoding = 'unknown'

754 755
    def __init__(self, stream, encode, decode, Reader, Writer,
                 errors='strict'):
756 757 758

        """ Creates a StreamRecoder instance which implements a two-way
            conversion: encode and decode work on the frontend (the
759
            input to .read() and output of .write()) while
760
            Reader and Writer work on the backend (reading and
761
            writing to the stream).
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

            You can use these objects to do transparent direct
            recodings from e.g. latin-1 to utf-8 and back.

            stream must be a file-like object.

            encode, decode must adhere to the Codec interface, Reader,
            Writer must be factory functions or classes providing the
            StreamReader, StreamWriter interface resp.

            encode and decode are needed for the frontend translation,
            Reader and Writer for the backend translation. Unicode is
            used as intermediate encoding.

            Error handling is done in the same way as defined for the
            StreamWriter/Readers.

        """
        self.stream = stream
        self.encode = encode
        self.decode = decode
        self.reader = Reader(stream, errors)
        self.writer = Writer(stream, errors)
        self.errors = errors

787
    def read(self, size=-1):
788 789 790 791 792

        data = self.reader.read(size)
        data, bytesencoded = self.encode(data, self.errors)
        return data

793
    def readline(self, size=None):
Guido van Rossum's avatar
Guido van Rossum committed
794 795 796 797 798 799 800 801

        if size is None:
            data = self.reader.readline()
        else:
            data = self.reader.readline(size)
        data, bytesencoded = self.encode(data, self.errors)
        return data

802
    def readlines(self, sizehint=None):
Guido van Rossum's avatar
Guido van Rossum committed
803

804
        data = self.reader.read()
Guido van Rossum's avatar
Guido van Rossum committed
805
        data, bytesencoded = self.encode(data, self.errors)
806
        return data.splitlines(keepends=True)
Guido van Rossum's avatar
Guido van Rossum committed
807

808
    def __next__(self):
809 810

        """ Return the next decoded line from the input stream."""
811
        data = next(self.reader)
812 813
        data, bytesencoded = self.encode(data, self.errors)
        return data
814 815 816 817

    def __iter__(self):
        return self

818
    def write(self, data):
819 820 821 822

        data, bytesdecoded = self.decode(data, self.errors)
        return self.writer.write(data)

823
    def writelines(self, list):
Guido van Rossum's avatar
Guido van Rossum committed
824 825 826 827

        data = ''.join(list)
        data, bytesdecoded = self.decode(data, self.errors)
        return self.writer.write(data)
828 829 830 831 832 833

    def reset(self):

        self.reader.reset()
        self.writer.reset()

834
    def __getattr__(self, name,
835 836 837 838
                    getattr=getattr):

        """ Inherit all other methods from the underlying stream.
        """
839
        return getattr(self.stream, name)
840

841 842 843 844 845 846
    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

847 848
### Shortcuts

849
def open(filename, mode='rb', encoding=None, errors='strict', buffering=1):
850 851 852 853 854 855

    """ Open an encoded file using the given mode and return
        a wrapped version providing transparent encoding/decoding.

        Note: The wrapped version will only accept the object format
        defined by the codecs, i.e. Unicode objects for most builtin
Skip Montanaro's avatar
Skip Montanaro committed
856
        codecs. Output is also codec dependent and will usually be
857 858
        Unicode as well.

859
        Files are always opened in binary mode, even if no binary mode
Walter Dörwald's avatar
Walter Dörwald committed
860
        was specified. This is done to avoid data loss due to encodings
861 862 863
        using 8-bit values. The default file mode is 'rb' meaning to
        open the file in binary read mode.

864
        encoding specifies the encoding which is to be used for the
Walter Dörwald's avatar
Walter Dörwald committed
865
        file.
866 867 868 869 870 871 872 873

        errors may be given to define the error handling. It defaults
        to 'strict' which causes ValueErrors to be raised in case an
        encoding error occurs.

        buffering has the same meaning as for the builtin open() API.
        It defaults to line buffered.

874 875 876 877 878
        The returned wrapped file object provides an extra attribute
        .encoding which allows querying the used encoding. This
        attribute is only available if an encoding was specified as
        parameter.

879 880 881 882 883
    """
    if encoding is not None and \
       'b' not in mode:
        # Force opening of the file in binary mode
        mode = mode + 'b'
884
    file = builtins.open(filename, mode, buffering)
885 886
    if encoding is None:
        return file
887 888
    info = lookup(encoding)
    srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
Guido van Rossum's avatar
Guido van Rossum committed
889 890 891
    # Add attributes to simplify introspection
    srw.encoding = encoding
    return srw
892

Guido van Rossum's avatar
Guido van Rossum committed
893
def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
894 895 896 897 898

    """ Return a wrapped version of file which provides transparent
        encoding translation.

        Strings written to the wrapped file are interpreted according
Guido van Rossum's avatar
Guido van Rossum committed
899 900 901 902 903 904
        to the given data_encoding and then written to the original
        file as string using file_encoding. The intermediate encoding
        will usually be Unicode but depends on the specified codecs.

        Strings are read from the file using file_encoding and then
        passed back to the caller as string using data_encoding.
905

Guido van Rossum's avatar
Guido van Rossum committed
906
        If file_encoding is not given, it defaults to data_encoding.
907 908 909 910 911

        errors may be given to define the error handling. It defaults
        to 'strict' which causes ValueErrors to be raised in case an
        encoding error occurs.

912 913 914 915 916
        The returned wrapped file object provides two extra attributes
        .data_encoding and .file_encoding which reflect the given
        parameters of the same name. The attributes can be used for
        introspection by Python programs.

917
    """
Guido van Rossum's avatar
Guido van Rossum committed
918 919
    if file_encoding is None:
        file_encoding = data_encoding
920 921 922 923
    data_info = lookup(data_encoding)
    file_info = lookup(file_encoding)
    sr = StreamRecoder(file, data_info.encode, data_info.decode,
                       file_info.streamreader, file_info.streamwriter, errors)
Guido van Rossum's avatar
Guido van Rossum committed
924 925 926 927
    # Add attributes to simplify introspection
    sr.data_encoding = data_encoding
    sr.file_encoding = file_encoding
    return sr
928

929 930 931 932 933 934 935 936 937 938
### Helpers for codec lookup

def getencoder(encoding):

    """ Lookup up the codec for the given encoding and return
        its encoder function.

        Raises a LookupError in case the encoding cannot be found.

    """
939
    return lookup(encoding).encode
940 941 942 943 944 945 946 947 948

def getdecoder(encoding):

    """ Lookup up the codec for the given encoding and return
        its decoder function.

        Raises a LookupError in case the encoding cannot be found.

    """
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    return lookup(encoding).decode

def getincrementalencoder(encoding):

    """ Lookup up the codec for the given encoding and return
        its IncrementalEncoder class or factory function.

        Raises a LookupError in case the encoding cannot be found
        or the codecs doesn't provide an incremental encoder.

    """
    encoder = lookup(encoding).incrementalencoder
    if encoder is None:
        raise LookupError(encoding)
    return encoder

def getincrementaldecoder(encoding):

    """ Lookup up the codec for the given encoding and return
        its IncrementalDecoder class or factory function.

        Raises a LookupError in case the encoding cannot be found
        or the codecs doesn't provide an incremental decoder.

    """
    decoder = lookup(encoding).incrementaldecoder
    if decoder is None:
        raise LookupError(encoding)
    return decoder
978 979 980 981 982 983 984 985 986

def getreader(encoding):

    """ Lookup up the codec for the given encoding and return
        its StreamReader class or factory function.

        Raises a LookupError in case the encoding cannot be found.

    """
987
    return lookup(encoding).streamreader
988 989 990 991 992 993 994 995 996

def getwriter(encoding):

    """ Lookup up the codec for the given encoding and return
        its StreamWriter class or factory function.

        Raises a LookupError in case the encoding cannot be found.

    """
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    return lookup(encoding).streamwriter

def iterencode(iterator, encoding, errors='strict', **kwargs):
    """
    Encoding iterator.

    Encodes the input strings from the iterator using a IncrementalEncoder.

    errors and kwargs are passed through to the IncrementalEncoder
    constructor.
    """
    encoder = getincrementalencoder(encoding)(errors, **kwargs)
    for input in iterator:
        output = encoder.encode(input)
        if output:
            yield output
    output = encoder.encode("", True)
    if output:
        yield output

def iterdecode(iterator, encoding, errors='strict', **kwargs):
    """
    Decoding iterator.

    Decodes the input strings from the iterator using a IncrementalDecoder.

    errors and kwargs are passed through to the IncrementalDecoder
    constructor.
    """
    decoder = getincrementaldecoder(encoding)(errors, **kwargs)
    for input in iterator:
        output = decoder.decode(input)
        if output:
            yield output
1031
    output = decoder.decode(b"", True)
1032 1033
    if output:
        yield output
1034

1035 1036 1037 1038 1039 1040 1041 1042
### Helpers for charmap-based codecs

def make_identity_dict(rng):

    """ make_identity_dict(rng) -> dict

        Return a dictionary where elements of the rng sequence are
        mapped to themselves.
Tim Peters's avatar
Tim Peters committed
1043

1044 1045 1046 1047 1048 1049
    """
    res = {}
    for i in rng:
        res[i]=i
    return res

1050 1051 1052 1053
def make_encoding_map(decoding_map):

    """ Creates an encoding map from a decoding map.

Walter Dörwald's avatar
Walter Dörwald committed
1054
        If a target mapping in the decoding map occurs multiple
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        times, then that target is mapped to None (undefined mapping),
        causing an exception when encountered by the charmap codec
        during translation.

        One example where this happens is cp875.py which decodes
        multiple character to \u001a.

    """
    m = {}
    for k,v in decoding_map.items():
1065
        if not v in m:
1066 1067 1068 1069
            m[v] = k
        else:
            m[v] = None
    return m
Tim Peters's avatar
Tim Peters committed
1070

1071 1072
### error handlers

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
try:
    strict_errors = lookup_error("strict")
    ignore_errors = lookup_error("ignore")
    replace_errors = lookup_error("replace")
    xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace")
    backslashreplace_errors = lookup_error("backslashreplace")
except LookupError:
    # In --disable-unicode builds, these error handler are missing
    strict_errors = None
    ignore_errors = None
    replace_errors = None
    xmlcharrefreplace_errors = None
    backslashreplace_errors = None
1086

1087 1088 1089 1090 1091 1092
# Tell modulefinder that using codecs probably needs the encodings
# package
_false = 0
if _false:
    import encodings

1093
### Tests
1094

1095 1096
if __name__ == '__main__':

Guido van Rossum's avatar
Guido van Rossum committed
1097 1098
    # Make stdout translate Latin-1 output into UTF-8 output
    sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
1099

Guido van Rossum's avatar
Guido van Rossum committed
1100 1101
    # Have stdin translate Latin-1 input into UTF-8 input
    sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')