Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
PickleTools.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 from types import *
3 
4 def _bytehex2(num, ord=ord, chr=chr, ord_0=ord('0'), ord_a=ord('a')):
5  if num<10:
6  return chr(num+ord_0)
7  else:
8  return chr(num+ord_a-10)
9 
10 def _bytehex(num, int=int, divmod=divmod, bytehex2=_bytehex2):
11  q,r=divmod(int(num),16)
12  return bytehex2(q%16)+bytehex2(r)
13 
14 bytehex = map(_bytehex, xrange(256))
15 
16 # '\\' is always forbidden
17 def addSlashes(m,forbidden="#!|\\?\"\'\r\n",extended_forbidden=1, bytehex=bytehex):
18  rv = []
19  rva = rv.append
20  for i, m_i in enumerate(m):
21  quote = (extended_forbidden and ord(m_i)>=128) \
22  or (m_i == '\\') \
23  or (m_i in forbidden)
24  if quote:
25  if not rv and i: rva( m[:i] )
26  rva( "\\" )
27  rva( bytehex[ord(m_i)%256] )
28  elif rv:
29  rva( m_i )
30  return rv and "".join(rv) or m
31 
32 def _hexbyte2(c, ord=ord, ord_0=ord('0'), ord_9=ord('9'), ord_a=ord('a')):
33  ord_c = ord(c)
34  if ( ord_c>=ord_0 and ord_c<=ord_9 ):
35  return ord_c - ord_0
36  else:
37  return 10 + ord_c - ord_a
38 
39 def _hexbyte(s, hexbyte2=_hexbyte2):
40  return ( hexbyte2(s[0])*16+hexbyte2(s[1]) ) % 256
41 
42 def stripSlashes(m, hexbyte=_hexbyte, chr=chr):
43  if '\\' not in m:
44  return m
45  rv = []
46  rva = rv.append
47  i = 0
48  l = len(m)
49  while (i<l):
50  if (m[i]=='\\') and (i+2<l):
51  rva( chr( hexbyte(m[i+1:i+3]) ) )
52  i += 3
53  else:
54  rva( m[i] )
55  i += 1
56  return "".join(rv)
57 
58 def encodeMap(m, str=str):
59  if type(m) is DictionaryType:
60  rv = []
61  rva = rv.append
62  _addSlashes = addSlashes
63  _encodeMap = encodeMap
64  for k,v in m.iteritems():
65  #recursive, in case there are nested maps
66  rva( _addSlashes(str(k)) + "#" + _encodeMap(v) )
67  rv = "|".join(rv)
68  del rva
69  else:
70  rv = addSlashes(str(m))
71  return addSlashes(rv)
72 
73 def decodeMap(m, len=len):
74  m = stripSlashes(m)
75  ilist = m.split('|')
76  if len(ilist)==1:
77  ipair = ilist[0].split('#')
78  if len(ipair)==1:
79  return stripSlashes(ipair[0])
80  elif len(ipair)>=2:
81  return { stripSlashes(ipair[0]) : decodeMap(ipair[1]) }
82  else:
83  return ''
84  else:
85  rv = {}
86  _stripSlashes = stripSlashes
87  _decodeMap = decodeMap
88  for ipair in ilist:
89  ipair = ipair.split('#')
90  if len(ipair)>=2:
91  rv[_stripSlashes(ipair[0])] = decodeMap(ipair[1])
92  return rv