pickle.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import json
  2. import builtins
  3. _BASIC_TYPES = [int, float, str, bool, type(None)]
  4. def _find_class(path: str):
  5. if "." not in path:
  6. g = globals()
  7. if path in g:
  8. return g[path]
  9. return builtins.__dict__[path]
  10. modname, name = path.split(".")
  11. return __import__(modname).__dict__[name]
  12. def _find__new__(cls):
  13. while cls is not None:
  14. d = cls.__dict__
  15. if "__new__" in d:
  16. return d["__new__"]
  17. cls = cls.__base__
  18. assert False
  19. class _Pickler:
  20. def __init__(self, obj) -> None:
  21. self.obj = obj
  22. self.raw_memo = {} # id -> int
  23. self.memo = [] # int -> object
  24. def wrap(self, o):
  25. if type(o) in _BASIC_TYPES:
  26. return 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 = o.__class__.__name__
  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. # reference
  82. if type(o[0]) is int:
  83. assert index is None # index should be None
  84. index = o[0]
  85. if self._unwrapped[index] is None:
  86. o = self.memo[index]
  87. assert type(o) is list
  88. assert type(o[0]) is str
  89. self.unwrap(o, index)
  90. assert self._unwrapped[index] is not None
  91. return self._unwrapped[index]
  92. # concrete reference type
  93. if o[0] == "tuple":
  94. ret = tuple([self.unwrap(i) for i in o[1]])
  95. self.tag(index, ret)
  96. return ret
  97. if o[0] == "bytes":
  98. ret = bytes(o[1])
  99. self.tag(index, ret)
  100. return ret
  101. if o[0] == "list":
  102. ret = []
  103. self.tag(index, ret)
  104. for i in o[1]:
  105. ret.append(self.unwrap(i))
  106. return ret
  107. if o[0] == "dict":
  108. ret = {}
  109. self.tag(index, ret)
  110. for k,v in o[1]:
  111. ret[self.unwrap(k)] = self.unwrap(v)
  112. return ret
  113. # generic object
  114. cls, newargs, state = o
  115. cls = _find_class(o[0])
  116. # create uninitialized instance
  117. new_f = _find__new__(cls)
  118. if newargs is not None:
  119. newargs = [self.unwrap(i) for i in newargs]
  120. inst = new_f(cls, *newargs)
  121. else:
  122. inst = new_f(cls)
  123. self.tag(index, inst)
  124. # restore state
  125. if state is not None:
  126. for k,v in state.items():
  127. setattr(inst, k, self.unwrap(v))
  128. return inst
  129. def run_pipe(self):
  130. return self.unwrap(self.obj)
  131. def _wrap(o):
  132. return _Pickler(o).run_pipe()
  133. def _unwrap(packed: list):
  134. return _Unpickler(*packed).run_pipe()
  135. def dumps(o) -> bytes:
  136. o = _wrap(o)
  137. return json.dumps(o).encode()
  138. def loads(b) -> object:
  139. assert type(b) is bytes
  140. o = json.loads(b.decode())
  141. return _unwrap(o)