home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / util / auxencodings.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  12.9 KB  |  420 lines

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