home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / digsby_setup.exe / lib / util / auxencodings.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-02-26  |  10.0 KB  |  328 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from peak.util.imports import lazyModule
  5. import sys
  6. import warnings
  7. import locale
  8. collections = lazyModule('collections')
  9. urllib2 = lazyModule('urllib2')
  10. codecs = lazyModule('codecs')
  11. StringIO = lazyModule('StringIO')
  12. zipfile = lazyModule('zipfile')
  13. gzip = lazyModule('gzip')
  14. htmlentitydefs = lazyModule('htmlentitydefs')
  15. HAVE_LZMA = False
  16. ENCODE_LZMA = False
  17. __simplechars_enc = {
  18.     ord('<'): 'lt',
  19.     ord('>'): 'gt',
  20.     ord('"'): 'quot',
  21.     ord('&'): 'amp' }
  22. __simplechars_dec = dict((lambda .0: for k, v in .0:
  23. (v, unichr(k)))(__simplechars_enc.items()))
  24. __simplechars_dec['apos'] = unichr(ord("'"))
  25. _encodings = [
  26.     locale.getpreferredencoding(),
  27.     'ISO-8859-1',
  28.     sys.getfilesystemencoding(),
  29.     sys.getdefaultencoding()]
  30.  
  31. def register_codec(name, encode, decode):
  32.     
  33.     def _search(n):
  34.         if n == name:
  35.             return codecs.CodecInfo(name = name, encode = encode, decode = decode)
  36.         
  37.  
  38.     codecs.register(_search)
  39.  
  40.  
  41. def fuzzydecode(s, encoding = None, errors = 'strict'):
  42.     if isinstance(s, unicode):
  43.         warnings.warn('decoding unicode is not supported!')
  44.         return s
  45.     
  46.     encodings = list(_encodings)
  47.     if isinstance(encoding, basestring):
  48.         encodings.insert(0, encoding)
  49.     elif encoding is None:
  50.         pass
  51.     else:
  52.         encodings = list(encoding) + encodings
  53.     for e in encodings:
  54.         
  55.         try:
  56.             res = s.decode(e, errors)
  57.         except (UnicodeDecodeError, LookupError):
  58.             _ex = None
  59.             continue
  60.  
  61.         return res
  62.     
  63.     return s.decode(encoding, 'replace')
  64.  
  65.  
  66. def fuzzyencode(s, errors = 'strict'):
  67.     raise NotImplementedError
  68.  
  69.  
  70. def _xml_encode(input, errors = 'simple'):
  71.     simple = 'simple' in errors
  72.     origtype = type(input)
  73.     if simple:
  74.         chars = __simplechars_enc
  75.     else:
  76.         chars = htmlentitydefs.codepoint2name
  77.     res = []
  78.     append = res.append
  79.     for ch in input:
  80.         och = ord(ch)
  81.         if och in chars:
  82.             append('&%s;' % chars[och])
  83.             continue
  84.         append(ch)
  85.     
  86.     return (origtype(''.join(res)), len(input))
  87.  
  88.  
  89. def _xml_decode(input, errors = 'strict'):
  90.     data = collections.deque(input)
  91.     res = []
  92.     append = res.append
  93.     popleft = data.popleft
  94.     extendleft = data.extendleft
  95.     name2codepoint = htmlentitydefs.name2codepoint
  96.     while data:
  97.         ch = popleft()
  98.         if ch == '&':
  99.             curtoken = ''
  100.             is_ref = False
  101.             is_num = False
  102.             is_hex = False
  103.             while len(curtoken) < 10 and data:
  104.                 nch = popleft()
  105.                 if nch == '#':
  106.                     is_num = True
  107.                 
  108.                 if is_num and len(curtoken) == 1 and nch == 'x':
  109.                     is_hex = True
  110.                 
  111.                 if nch == ';':
  112.                     is_ref = True
  113.                     break
  114.                 
  115.                 curtoken += nch
  116.             if not is_ref:
  117.                 extendleft(reversed(curtoken))
  118.                 append('&')
  119.                 continue
  120.             elif is_num:
  121.                 curtoken = curtoken[1:]
  122.                 if is_hex:
  123.                     curtoken = curtoken[1:]
  124.                     och = int(curtoken, 16)
  125.                 else:
  126.                     och = int(curtoken, 10)
  127.                 append(unichr(och))
  128.             elif curtoken in name2codepoint:
  129.                 append(unichr(name2codepoint[curtoken]))
  130.             elif curtoken in __simplechars_dec:
  131.                 append(__simplechars_dec[curtoken])
  132.             else:
  133.                 append('&%s;' % curtoken)
  134.         is_ref
  135.         append(ch)
  136.     return (u''.join(res), len(input))
  137.  
  138. register_codec('xml', _xml_encode, _xml_decode)
  139.  
  140. def _pk_decode(input, errors = 'strict'):
  141.     li = len(input)
  142.     input = StringIO.StringIO(input)
  143.     z = zipfile.ZipFile(input, mode = 'rb')
  144.     zi = z.filelist[0]
  145.     return (z.read(zi.filename), li)
  146.  
  147.  
  148. def _pk_encode(input, errors = 'strict'):
  149.     li = len(input)
  150.     s = StringIO.StringIO()
  151.     z = zipfile.ZipFile(s, mode = 'wb', compression = zipfile.ZIP_DEFLATED)
  152.     z.writestr('file', input)
  153.     z.close()
  154.     return (s.getvalue(), li)
  155.  
  156.  
  157. def _gzip_decode(input, errors = 'strict'):
  158.     li = len(input)
  159.     input = StringIO.StringIO(input)
  160.     g = gzip.GzipFile(mode = 'rb', fileobj = input)
  161.     return (g.read(), li)
  162.  
  163.  
  164. def _gzip_encode(input, errors = 'strict'):
  165.     li = len(input)
  166.     s = StringIO.StringIO()
  167.     g = gzip.GzipFile(mode = 'wb', fileobj = s)
  168.     g.write(input)
  169.     g.close()
  170.     return (s.getvalue(), li)
  171.  
  172.  
  173. def _fuzzyzip_decode(input, errors = 'strict'):
  174.     magic_num = input[:2]
  175.     if magic_num == 'PK':
  176.         return _pk_decode(input, errors = 'strict')
  177.     elif magic_num == 'BZ':
  178.         return (input.decode('bz2'), len(input))
  179.     elif magic_num == '\x1f\x8b':
  180.         return _gzip_decode(input, errors = 'strict')
  181.     elif HAVE_LZMA:
  182.         
  183.         try:
  184.             return (pylzma.decompress(input), len(input))
  185.         except Exception:
  186.             pass
  187.         except:
  188.             None<EXCEPTION MATCH>Exception
  189.         
  190.  
  191.     None<EXCEPTION MATCH>Exception
  192.     return (input.decode('zip'), len(input))
  193.  
  194.  
  195. def _fuzzyzip_encode(input, errors = 'strict'):
  196.     li = len(input)
  197.     funcs = [
  198.         ((lambda : input.encode('bz2')),),
  199.         (lambda : input.encode('zlib'))]
  200.     if ENCODE_LZMA and HAVE_LZMA:
  201.         (funcs.append,)((lambda : pylzma.compress(input)))
  202.     
  203.     shortest_val = None
  204.     shortest_len = -1
  205.     for func in funcs:
  206.         newval = func()
  207.         newlen = len(newval)
  208.         if shortest_len < 0 or newlen < shortest_len:
  209.             shortest_len = newlen
  210.             shortest_val = newval
  211.             continue
  212.     
  213.     return (shortest_val, li)
  214.  
  215.  
  216. def search(name):
  217.     if name == 'z' or name == 'fuzzyzip':
  218.         name = 'fuzzyzip'
  219.         return codecs.CodecInfo(name = 'fuzzyzip', encode = _fuzzyzip_encode, decode = _fuzzyzip_decode)
  220.     
  221.  
  222. codecs.register(search)
  223. del search
  224.  
  225. def search(name):
  226.     if name.startswith('fuzzy'):
  227.         if name == 'fuzzyzip':
  228.             return None
  229.         
  230.         if not name[len('fuzzy'):]:
  231.             pass
  232.         encoding = None
  233.     elif name.endswith('?'):
  234.         if not name[:-1]:
  235.             pass
  236.         encoding = None
  237.     else:
  238.         return None
  239.     name = 'fuzzy'
  240.     encode = fuzzyencode
  241.     
  242.     def decode(s, errors = ('strict',)):
  243.         if encoding:
  244.             encs = filter(bool, encoding.split('-'))
  245.         else:
  246.             encs = None
  247.         return (fuzzydecode(s, encs, errors), len(s))
  248.  
  249.     return codecs.CodecInfo(name = name, encode = encode, decode = decode)
  250.  
  251. codecs.register(search)
  252. del search
  253. __locale_encoding = locale.getpreferredencoding()
  254. register_codec('locale', (lambda s, errors = 'strict': (s.encode(__locale_encoding), len(s))), (lambda s, errors = 'strict': (s.decode(__locale_encoding), len(s))))
  255. __filesysencoding = sys.getfilesystemencoding()
  256.  
  257. def _filesys_encode(s, errors = 'strict'):
  258.     if isinstance(s, str):
  259.         return (s, len(s))
  260.     else:
  261.         return (s.encode(__filesysencoding), len(s))
  262.  
  263.  
  264. def _filesys_decode(s, errors = 'strict'):
  265.     if isinstance(s, unicode):
  266.         return (s, len(s))
  267.     else:
  268.         return (s.decode(__filesysencoding), len(s))
  269.  
  270. register_codec('filesys', _filesys_encode, _filesys_decode)
  271. del _filesys_encode
  272. del _filesys_decode
  273.  
  274. def _url_encode(input, errors = 'strict'):
  275.     return (urllib2.quote(input), len(input))
  276.  
  277.  
  278. def _url_decode(input, errors = 'strict'):
  279.     return (urllib2.unquote(input), len(input))
  280.  
  281. register_codec('url', _url_encode, _url_decode)
  282. __all__ = []
  283. if __name__ == '__main__':
  284.     
  285.     def gen_rand_str(length = 5000):
  286.         randint = randint
  287.         randchoice = choice
  288.         import random
  289.         ascii_letters = ascii_letters
  290.         import string
  291.         ents = list(__simplechars_dec)
  292.         data = []
  293.         append = data.append
  294.         for x in xrange(length):
  295.             r = randint(0, 10)
  296.             if r == 0:
  297.                 append('&%s;' % randchoice(ents))
  298.             elif r == 1:
  299.                 append('&%d;' % randint(0, 65535))
  300.             elif r == 2:
  301.                 append('&%x;' % randint(0, 65535))
  302.             
  303.             if r > 3:
  304.                 append(randchoice(ascii_letters))
  305.                 continue
  306.         
  307.         return ''.join(data)
  308.  
  309.     strings = [ gen_rand_str() for x in xrange(100) ]
  310.     results1 = []
  311.     results2 = []
  312.     from time import clock
  313.     
  314.     def timeit(func):
  315.         before = clock()
  316.         func()
  317.         return clock() - before
  318.  
  319.     
  320.     def foo(encoding, res):
  321.         for s in strings:
  322.             res.append(s.decode(encoding))
  323.         
  324.  
  325.     print 'xml', timeit((lambda : foo('xml', results1)))
  326.     print 'xml2', timeit((lambda : foo('xml2', results2)))
  327.  
  328.