home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / codecs.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  23.7 KB  |  593 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. ''' codecs -- Python Codec Registry, API and helpers.
  5.  
  6.  
  7. Written by Marc-Andre Lemburg (mal@lemburg.com).
  8.  
  9. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  10.  
  11. '''
  12. import struct
  13. import __builtin__
  14.  
  15. try:
  16.     from _codecs import *
  17. except ImportError:
  18.     why = None
  19.     raise SystemError, 'Failed to load the builtin codecs: %s' % why
  20.  
  21. __all__ = [
  22.     'register',
  23.     'lookup',
  24.     'open',
  25.     'EncodedFile',
  26.     'BOM',
  27.     'BOM_BE',
  28.     'BOM_LE',
  29.     'BOM32_BE',
  30.     'BOM32_LE',
  31.     'BOM64_BE',
  32.     'BOM64_LE']
  33. BOM = struct.pack('=H', 65279)
  34. BOM_BE = BOM32_BE = '\xfe\xff'
  35. BOM_LE = BOM32_LE = '\xff\xfe'
  36. BOM64_BE = '\x00\x00\xfe\xff'
  37. BOM64_LE = '\xff\xfe\x00\x00'
  38.  
  39. class Codec:
  40.     """ Defines the interface for stateless encoders/decoders.
  41.  
  42.         The .encode()/.decode() methods may implement different error
  43.         handling schemes by providing the errors argument. These
  44.         string values are defined:
  45.  
  46.          'strict' - raise a ValueError error (or a subclass)
  47.          'ignore' - ignore the character and continue with the next
  48.          'replace' - replace with a suitable replacement character;
  49.                     Python will use the official U+FFFD REPLACEMENT
  50.                     CHARACTER for the builtin Unicode codecs.
  51.  
  52.     """
  53.     
  54.     def encode(self, input, errors = 'strict'):
  55.         """ Encodes the object input and returns a tuple (output
  56.             object, length consumed).
  57.  
  58.             errors defines the error handling to apply. It defaults to
  59.             'strict' handling.
  60.  
  61.             The method may not store state in the Codec instance. Use
  62.             StreamCodec for codecs which have to keep state in order to
  63.             make encoding/decoding efficient.
  64.  
  65.             The encoder must be able to handle zero length input and
  66.             return an empty object of the output object type in this
  67.             situation.
  68.  
  69.         """
  70.         raise NotImplementedError
  71.  
  72.     
  73.     def decode(self, input, errors = 'strict'):
  74.         """ Decodes the object input and returns a tuple (output
  75.             object, length consumed).
  76.  
  77.             input must be an object which provides the bf_getreadbuf
  78.             buffer slot. Python strings, buffer objects and memory
  79.             mapped files are examples of objects providing this slot.
  80.  
  81.             errors defines the error handling to apply. It defaults to
  82.             'strict' handling.
  83.  
  84.             The method may not store state in the Codec instance. Use
  85.             StreamCodec for codecs which have to keep state in order to
  86.             make encoding/decoding efficient.
  87.  
  88.             The decoder must be able to handle zero length input and
  89.             return an empty object of the output object type in this
  90.             situation.
  91.  
  92.         """
  93.         raise NotImplementedError
  94.  
  95.  
  96.  
  97. class StreamWriter(Codec):
  98.     
  99.     def __init__(self, stream, errors = 'strict'):
  100.         """ Creates a StreamWriter instance.
  101.  
  102.             stream must be a file-like object open for writing
  103.             (binary) data.
  104.  
  105.             The StreamWriter may implement different error handling
  106.             schemes by providing the errors keyword argument. These
  107.             parameters are defined:
  108.  
  109.              'strict' - raise a ValueError (or a subclass)
  110.              'ignore' - ignore the character and continue with the next
  111.              'replace'- replace with a suitable replacement character
  112.  
  113.         """
  114.         self.stream = stream
  115.         self.errors = errors
  116.  
  117.     
  118.     def write(self, object):
  119.         """ Writes the object's contents encoded to self.stream.
  120.         """
  121.         (data, consumed) = self.encode(object, self.errors)
  122.         self.stream.write(data)
  123.  
  124.     
  125.     def writelines(self, list):
  126.         ''' Writes the concatenated list of strings to the stream
  127.             using .write().
  128.         '''
  129.         self.write(''.join(list))
  130.  
  131.     
  132.     def reset(self):
  133.         ''' Flushes and resets the codec buffers used for keeping state.
  134.  
  135.             Calling this method should ensure that the data on the
  136.             output is put into a clean state, that allows appending
  137.             of new fresh data without having to rescan the whole
  138.             stream to recover state.
  139.  
  140.         '''
  141.         pass
  142.  
  143.     
  144.     def __getattr__(self, name, getattr = getattr):
  145.         ''' Inherit all other methods from the underlying stream.
  146.         '''
  147.         return getattr(self.stream, name)
  148.  
  149.  
  150.  
  151. class StreamReader(Codec):
  152.     
  153.     def __init__(self, stream, errors = 'strict'):
  154.         """ Creates a StreamReader instance.
  155.  
  156.             stream must be a file-like object open for reading
  157.             (binary) data.
  158.  
  159.             The StreamReader may implement different error handling
  160.             schemes by providing the errors keyword argument. These
  161.             parameters are defined:
  162.  
  163.              'strict' - raise a ValueError (or a subclass)
  164.              'ignore' - ignore the character and continue with the next
  165.              'replace'- replace with a suitable replacement character;
  166.  
  167.         """
  168.         self.stream = stream
  169.         self.errors = errors
  170.  
  171.     
  172.     def read(self, size = -1):
  173.         ''' Decodes data from the stream self.stream and returns the
  174.             resulting object.
  175.  
  176.             size indicates the approximate maximum number of bytes to
  177.             read from the stream for decoding purposes. The decoder
  178.             can modify this setting as appropriate. The default value
  179.             -1 indicates to read and decode as much as possible.  size
  180.             is intended to prevent having to decode huge files in one
  181.             step.
  182.  
  183.             The method should use a greedy read strategy meaning that
  184.             it should read as much data as is allowed within the
  185.             definition of the encoding and the given size, e.g.  if
  186.             optional encoding endings or state markers are available
  187.             on the stream, these should be read too.
  188.  
  189.         '''
  190.         if size < 0:
  191.             return self.decode(self.stream.read(), self.errors)[0]
  192.         
  193.         read = self.stream.read
  194.         decode = self.decode
  195.         data = read(size)
  196.         i = 0
  197.         while 1:
  198.             
  199.             try:
  200.                 (object, decodedbytes) = decode(data, self.errors)
  201.             except ValueError:
  202.                 why = None
  203.                 i = i + 1
  204.                 newdata = read(1)
  205.                 if not newdata or i > 10:
  206.                     raise 
  207.                 
  208.                 data = data + newdata
  209.  
  210.             return object
  211.  
  212.     
  213.     def readline(self, size = None):
  214.         """ Read one line from the input stream and return the
  215.             decoded data.
  216.  
  217.             Note: Unlike the .readlines() method, this method inherits
  218.             the line breaking knowledge from the underlying stream's
  219.             .readline() method -- there is currently no support for
  220.             line breaking using the codec decoder due to lack of line
  221.             buffering. Sublcasses should however, if possible, try to
  222.             implement this method using their own knowledge of line
  223.             breaking.
  224.  
  225.             size, if given, is passed as size argument to the stream's
  226.             .readline() method.
  227.  
  228.         """
  229.         if size is None:
  230.             line = self.stream.readline()
  231.         else:
  232.             line = self.stream.readline(size)
  233.         return self.decode(line, self.errors)[0]
  234.  
  235.     
  236.     def readlines(self, sizehint = 0):
  237.         """ Read all lines available on the input stream
  238.             and return them as list of lines.
  239.  
  240.             Line breaks are implemented using the codec's decoder
  241.             method and are included in the list entries.
  242.  
  243.             sizehint, if given, is passed as size argument to the
  244.             stream's .read() method.
  245.  
  246.         """
  247.         if sizehint is None:
  248.             data = self.stream.read()
  249.         else:
  250.             data = self.stream.read(sizehint)
  251.         return self.decode(data, self.errors)[0].splitlines(1)
  252.  
  253.     
  254.     def reset(self):
  255.         ''' Resets the codec buffers used for keeping state.
  256.  
  257.             Note that no stream repositioning should take place.
  258.             This method is primarily intended to be able to recover
  259.             from decoding errors.
  260.  
  261.         '''
  262.         pass
  263.  
  264.     
  265.     def __getattr__(self, name, getattr = getattr):
  266.         ''' Inherit all other methods from the underlying stream.
  267.         '''
  268.         return getattr(self.stream, name)
  269.  
  270.  
  271.  
  272. class StreamReaderWriter:
  273.     ''' StreamReaderWriter instances allow wrapping streams which
  274.         work in both read and write modes.
  275.  
  276.         The design is such that one can use the factory functions
  277.         returned by the codec.lookup() function to construct the
  278.         instance.
  279.  
  280.     '''
  281.     encoding = 'unknown'
  282.     
  283.     def __init__(self, stream, Reader, Writer, errors = 'strict'):
  284.         ''' Creates a StreamReaderWriter instance.
  285.  
  286.             stream must be a Stream-like object.
  287.  
  288.             Reader, Writer must be factory functions or classes
  289.             providing the StreamReader, StreamWriter interface resp.
  290.  
  291.             Error handling is done in the same way as defined for the
  292.             StreamWriter/Readers.
  293.  
  294.         '''
  295.         self.stream = stream
  296.         self.reader = Reader(stream, errors)
  297.         self.writer = Writer(stream, errors)
  298.         self.errors = errors
  299.  
  300.     
  301.     def read(self, size = -1):
  302.         return self.reader.read(size)
  303.  
  304.     
  305.     def readline(self, size = None):
  306.         return self.reader.readline(size)
  307.  
  308.     
  309.     def readlines(self, sizehint = None):
  310.         return self.reader.readlines(sizehint)
  311.  
  312.     
  313.     def write(self, data):
  314.         return self.writer.write(data)
  315.  
  316.     
  317.     def writelines(self, list):
  318.         return self.writer.writelines(list)
  319.  
  320.     
  321.     def reset(self):
  322.         self.reader.reset()
  323.         self.writer.reset()
  324.  
  325.     
  326.     def __getattr__(self, name, getattr = getattr):
  327.         ''' Inherit all other methods from the underlying stream.
  328.         '''
  329.         return getattr(self.stream, name)
  330.  
  331.  
  332.  
  333. class StreamRecoder:
  334.     ''' StreamRecoder instances provide a frontend - backend
  335.         view of encoding data.
  336.  
  337.         They use the complete set of APIs returned by the
  338.         codecs.lookup() function to implement their task.
  339.  
  340.         Data written to the stream is first decoded into an
  341.         intermediate format (which is dependent on the given codec
  342.         combination) and then written to the stream using an instance
  343.         of the provided Writer class.
  344.  
  345.         In the other direction, data is read from the stream using a
  346.         Reader instance and then return encoded data to the caller.
  347.  
  348.     '''
  349.     data_encoding = 'unknown'
  350.     file_encoding = 'unknown'
  351.     
  352.     def __init__(self, stream, encode, decode, Reader, Writer, errors = 'strict'):
  353.         ''' Creates a StreamRecoder instance which implements a two-way
  354.             conversion: encode and decode work on the frontend (the
  355.             input to .read() and output of .write()) while
  356.             Reader and Writer work on the backend (reading and
  357.             writing to the stream).
  358.  
  359.             You can use these objects to do transparent direct
  360.             recodings from e.g. latin-1 to utf-8 and back.
  361.  
  362.             stream must be a file-like object.
  363.  
  364.             encode, decode must adhere to the Codec interface, Reader,
  365.             Writer must be factory functions or classes providing the
  366.             StreamReader, StreamWriter interface resp.
  367.  
  368.             encode and decode are needed for the frontend translation,
  369.             Reader and Writer for the backend translation. Unicode is
  370.             used as intermediate encoding.
  371.  
  372.             Error handling is done in the same way as defined for the
  373.             StreamWriter/Readers.
  374.  
  375.         '''
  376.         self.stream = stream
  377.         self.encode = encode
  378.         self.decode = decode
  379.         self.reader = Reader(stream, errors)
  380.         self.writer = Writer(stream, errors)
  381.         self.errors = errors
  382.  
  383.     
  384.     def read(self, size = -1):
  385.         data = self.reader.read(size)
  386.         (data, bytesencoded) = self.encode(data, self.errors)
  387.         return data
  388.  
  389.     
  390.     def readline(self, size = None):
  391.         if size is None:
  392.             data = self.reader.readline()
  393.         else:
  394.             data = self.reader.readline(size)
  395.         (data, bytesencoded) = self.encode(data, self.errors)
  396.         return data
  397.  
  398.     
  399.     def readlines(self, sizehint = None):
  400.         if sizehint is None:
  401.             data = self.reader.read()
  402.         else:
  403.             data = self.reader.read(sizehint)
  404.         (data, bytesencoded) = self.encode(data, self.errors)
  405.         return data.splitlines(1)
  406.  
  407.     
  408.     def write(self, data):
  409.         (data, bytesdecoded) = self.decode(data, self.errors)
  410.         return self.writer.write(data)
  411.  
  412.     
  413.     def writelines(self, list):
  414.         data = ''.join(list)
  415.         (data, bytesdecoded) = self.decode(data, self.errors)
  416.         return self.writer.write(data)
  417.  
  418.     
  419.     def reset(self):
  420.         self.reader.reset()
  421.         self.writer.reset()
  422.  
  423.     
  424.     def __getattr__(self, name, getattr = getattr):
  425.         ''' Inherit all other methods from the underlying stream.
  426.         '''
  427.         return getattr(self.stream, name)
  428.  
  429.  
  430.  
  431. def open(filename, mode = 'rb', encoding = None, errors = 'strict', buffering = 1):
  432.     """ Open an encoded file using the given mode and return
  433.         a wrapped version providing transparent encoding/decoding.
  434.  
  435.         Note: The wrapped version will only accept the object format
  436.         defined by the codecs, i.e. Unicode objects for most builtin
  437.         codecs. Output is also codec dependent and will usually by
  438.         Unicode as well.
  439.  
  440.         Files are always opened in binary mode, even if no binary mode
  441.         was specified. Thisis done to avoid data loss due to encodings
  442.         using 8-bit values. The default file mode is 'rb' meaning to
  443.         open the file in binary read mode.
  444.  
  445.         encoding specifies the encoding which is to be used for the
  446.         the file.
  447.  
  448.         errors may be given to define the error handling. It defaults
  449.         to 'strict' which causes ValueErrors to be raised in case an
  450.         encoding error occurs.
  451.  
  452.         buffering has the same meaning as for the builtin open() API.
  453.         It defaults to line buffered.
  454.  
  455.         The returned wrapped file object provides an extra attribute
  456.         .encoding which allows querying the used encoding. This
  457.         attribute is only available if an encoding was specified as
  458.         parameter.
  459.  
  460.     """
  461.     if encoding is not None and 'b' not in mode:
  462.         mode = mode + 'b'
  463.     
  464.     file = __builtin__.open(filename, mode, buffering)
  465.     if encoding is None:
  466.         return file
  467.     
  468.     (e, d, sr, sw) = lookup(encoding)
  469.     srw = StreamReaderWriter(file, sr, sw, errors)
  470.     srw.encoding = encoding
  471.     return srw
  472.  
  473.  
  474. def EncodedFile(file, data_encoding, file_encoding = None, errors = 'strict'):
  475.     """ Return a wrapped version of file which provides transparent
  476.         encoding translation.
  477.  
  478.         Strings written to the wrapped file are interpreted according
  479.         to the given data_encoding and then written to the original
  480.         file as string using file_encoding. The intermediate encoding
  481.         will usually be Unicode but depends on the specified codecs.
  482.  
  483.         Strings are read from the file using file_encoding and then
  484.         passed back to the caller as string using data_encoding.
  485.  
  486.         If file_encoding is not given, it defaults to data_encoding.
  487.  
  488.         errors may be given to define the error handling. It defaults
  489.         to 'strict' which causes ValueErrors to be raised in case an
  490.         encoding error occurs.
  491.  
  492.         The returned wrapped file object provides two extra attributes
  493.         .data_encoding and .file_encoding which reflect the given
  494.         parameters of the same name. The attributes can be used for
  495.         introspection by Python programs.
  496.  
  497.     """
  498.     if file_encoding is None:
  499.         file_encoding = data_encoding
  500.     
  501.     (encode, decode) = lookup(data_encoding)[:2]
  502.     (Reader, Writer) = lookup(file_encoding)[2:]
  503.     sr = StreamRecoder(file, encode, decode, Reader, Writer, errors)
  504.     sr.data_encoding = data_encoding
  505.     sr.file_encoding = file_encoding
  506.     return sr
  507.  
  508.  
  509. def getencoder(encoding):
  510.     ''' Lookup up the codec for the given encoding and return
  511.         its encoder function.
  512.  
  513.         Raises a LookupError in case the encoding cannot be found.
  514.  
  515.     '''
  516.     return lookup(encoding)[0]
  517.  
  518.  
  519. def getdecoder(encoding):
  520.     ''' Lookup up the codec for the given encoding and return
  521.         its decoder function.
  522.  
  523.         Raises a LookupError in case the encoding cannot be found.
  524.  
  525.     '''
  526.     return lookup(encoding)[1]
  527.  
  528.  
  529. def getreader(encoding):
  530.     ''' Lookup up the codec for the given encoding and return
  531.         its StreamReader class or factory function.
  532.  
  533.         Raises a LookupError in case the encoding cannot be found.
  534.  
  535.     '''
  536.     return lookup(encoding)[2]
  537.  
  538.  
  539. def getwriter(encoding):
  540.     ''' Lookup up the codec for the given encoding and return
  541.         its StreamWriter class or factory function.
  542.  
  543.         Raises a LookupError in case the encoding cannot be found.
  544.  
  545.     '''
  546.     return lookup(encoding)[3]
  547.  
  548.  
  549. def make_identity_dict(rng):
  550.     ''' make_identity_dict(rng) -> dict
  551.  
  552.         Return a dictionary where elements of the rng sequence are
  553.         mapped to themselves.
  554.  
  555.     '''
  556.     res = { }
  557.     for i in rng:
  558.         res[i] = i
  559.     
  560.     return res
  561.  
  562.  
  563. def make_encoding_map(decoding_map):
  564.     ''' Creates an encoding map from a decoding map.
  565.  
  566.         If a target mapping in the decoding map occurrs multiple
  567.         times, then that target is mapped to None (undefined mapping),
  568.         causing an exception when encountered by the charmap codec
  569.         during translation.
  570.  
  571.         One example where this happens is cp875.py which decodes
  572.         multiple character to \\u001a.
  573.  
  574.     '''
  575.     m = { }
  576.     for k, v in decoding_map.items():
  577.         if not m.has_key(v):
  578.             m[v] = k
  579.         else:
  580.             m[v] = None
  581.     
  582.     return m
  583.  
  584. _false = 0
  585. if _false:
  586.     import encodings
  587.  
  588. if __name__ == '__main__':
  589.     import sys
  590.     sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  591.     sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
  592.  
  593.