pickle.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import json
  2. from c import struct
  3. import builtins
  4. _BASIC_TYPES = [int, float, str, bool, type(None)]
  5. _MOD_T_SEP = "@"
  6. def _find_class(path: str):
  7. if _MOD_T_SEP not in path:
  8. return builtins.__dict__[path]
  9. modpath, name = path.split(_MOD_T_SEP)
  10. return __import__(modpath).__dict__[name]
  11. class _Pickler:
  12. def __init__(self, obj) -> None:
  13. self.obj = obj
  14. self.raw_memo = {} # id -> int
  15. self.memo = [] # int -> object
  16. @staticmethod
  17. def _type_id(t: type):
  18. assert type(t) is type
  19. name = t.__name__
  20. mod = t.__module__
  21. if mod is not None:
  22. name = mod.__path__ + _MOD_T_SEP + name
  23. return name
  24. def wrap(self, o):
  25. o_t = type(o)
  26. if o_t in _BASIC_TYPES:
  27. return o
  28. if o_t is type:
  29. return ["type", self._type_id(o)]
  30. index = self.raw_memo.get(id(o), None)
  31. if index is not None:
  32. return [index]
  33. ret = []
  34. index = len(self.memo)
  35. self.memo.append(ret)
  36. self.raw_memo[id(o)] = index
  37. if o_t is tuple:
  38. ret.append("tuple")
  39. ret.append([self.wrap(i) for i in o])
  40. return [index]
  41. if o_t is bytes:
  42. ret.append("bytes")
  43. ret.append([o[j] for j in range(len(o))])
  44. return [index]
  45. if o_t is list:
  46. ret.append("list")
  47. ret.append([self.wrap(i) for i in o])
  48. return [index]
  49. if o_t is dict:
  50. ret.append("dict")
  51. ret.append([[self.wrap(k), self.wrap(v)] for k,v in o.items()])
  52. return [index]
  53. _0 = self._type_id(o_t)
  54. if getattr(o_t, '__struct__', False):
  55. ret.append(_0)
  56. ret.append(o.tostruct().hex())
  57. return [index]
  58. if hasattr(o, "__getnewargs__"):
  59. _1 = o.__getnewargs__() # an iterable
  60. _1 = [self.wrap(i) for i in _1]
  61. else:
  62. _1 = None
  63. if o.__dict__ is None:
  64. _2 = None
  65. else:
  66. _2 = {k: self.wrap(v) for k,v in o.__dict__.items()}
  67. ret.append(_0) # type id
  68. ret.append(_1) # newargs
  69. ret.append(_2) # state
  70. return [index]
  71. def run_pipe(self):
  72. o = self.wrap(self.obj)
  73. return [o, self.memo]
  74. class _Unpickler:
  75. def __init__(self, obj, memo: list) -> None:
  76. self.obj = obj
  77. self.memo = memo
  78. self._unwrapped = [None] * len(memo)
  79. def tag(self, index, o):
  80. assert self._unwrapped[index] is None
  81. self._unwrapped[index] = o
  82. def unwrap(self, o, index=None):
  83. if type(o) in _BASIC_TYPES:
  84. return o
  85. assert type(o) is list
  86. if o[0] == "type":
  87. return _find_class(o[1])
  88. # reference
  89. if type(o[0]) is int:
  90. assert index is None # index should be None
  91. index = o[0]
  92. if self._unwrapped[index] is None:
  93. o = self.memo[index]
  94. assert type(o) is list
  95. assert type(o[0]) is str
  96. self.unwrap(o, index)
  97. assert self._unwrapped[index] is not None
  98. return self._unwrapped[index]
  99. # concrete reference type
  100. if o[0] == "tuple":
  101. ret = tuple([self.unwrap(i) for i in o[1]])
  102. self.tag(index, ret)
  103. return ret
  104. if o[0] == "bytes":
  105. ret = bytes(o[1])
  106. self.tag(index, ret)
  107. return ret
  108. if o[0] == "list":
  109. ret = []
  110. self.tag(index, ret)
  111. for i in o[1]:
  112. ret.append(self.unwrap(i))
  113. return ret
  114. if o[0] == "dict":
  115. ret = {}
  116. self.tag(index, ret)
  117. for k,v in o[1]:
  118. ret[self.unwrap(k)] = self.unwrap(v)
  119. return ret
  120. # generic object
  121. cls = _find_class(o[0])
  122. if getattr(cls, '__struct__', False):
  123. inst = cls.fromstruct(struct.fromhex(o[1]))
  124. self.tag(index, inst)
  125. return inst
  126. else:
  127. _, newargs, state = o
  128. # create uninitialized instance
  129. new_f = getattr(cls, "__new__")
  130. if newargs is not None:
  131. newargs = [self.unwrap(i) for i in newargs]
  132. inst = new_f(cls, *newargs)
  133. else:
  134. inst = new_f(cls)
  135. self.tag(index, inst)
  136. # restore state
  137. if state is not None:
  138. for k,v in state.items():
  139. setattr(inst, k, self.unwrap(v))
  140. return inst
  141. def run_pipe(self):
  142. return self.unwrap(self.obj)
  143. def _wrap(o):
  144. return _Pickler(o).run_pipe()
  145. def _unwrap(packed: list):
  146. return _Unpickler(*packed).run_pipe()
  147. def dumps(o) -> bytes:
  148. o = _wrap(o)
  149. return json.dumps(o).encode()
  150. def loads(b) -> object:
  151. assert type(b) is bytes
  152. o = json.loads(b.decode())
  153. return _unwrap(o)