pickle.py 4.6 KB

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