Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pickle_2.py 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. """Create portable serialized representations of Python objects.
  2. See module cPickle for a (much) faster implementation.
  3. See module copy_reg for a mechanism for registering custom picklers.
  4. See module pickletools source for extensive comments.
  5. Classes:
  6. Pickler
  7. Unpickler
  8. Functions:
  9. dump(object, file)
  10. dumps(object) -> string
  11. load(file) -> object
  12. loads(string) -> object
  13. Misc variables:
  14. __version__
  15. format_version
  16. compatible_formats
  17. """
  18. __version__ = "$Revision: 72223 $" # Code version
  19. from types import *
  20. from copy_reg import dispatch_table
  21. from copy_reg import _extension_registry, _inverted_registry, _extension_cache
  22. import marshal
  23. import sys
  24. import struct
  25. import re
  26. __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
  27. "Unpickler", "dump", "dumps", "load", "loads"]
  28. # These are purely informational; no code uses these.
  29. format_version = "3.0" # File format version we write
  30. compatible_formats = ["1.0", # Original protocol 0
  31. "1.1", # Protocol 0 with INST added
  32. "1.2", # Original protocol 1
  33. "1.3", # Protocol 1 with BINFLOAT added
  34. "2.0", # Protocol 2
  35. "3.0", # Protocol 3
  36. ] # Old format versions we can read
  37. # Keep in synch with cPickle. This is the highest protocol number we
  38. # know how to read.
  39. HIGHEST_PROTOCOL = 3
  40. DEFAULT_PROTOCOL = 3
  41. # Why use struct.pack() for pickling but marshal.loads() for
  42. # unpickling? struct.pack() is 40% faster than marshal.dumps(), but
  43. # marshal.loads() is twice as fast as struct.unpack()!
  44. mloads = marshal.loads
  45. class PickleError(Exception):
  46. """A common base class for the other pickling exceptions."""
  47. pass
  48. class PicklingError(PickleError):
  49. """This exception is raised when an unpicklable object is passed to the
  50. dump() method.
  51. """
  52. pass
  53. class UnpicklingError(PickleError):
  54. """This exception is raised when there is a problem unpickling an object,
  55. such as a security violation.
  56. Note that other exceptions may also be raised during unpickling, including
  57. (but not necessarily limited to) AttributeError, EOFError, ImportError,
  58. and IndexError.
  59. """
  60. pass
  61. # An instance of _Stop is raised by Unpickler.load_stop() in response to
  62. # the STOP opcode, passing the object that is the result of unpickling.
  63. class _Stop(Exception):
  64. def __init__(self, value):
  65. self.value = value
  66. # Jython has PyStringMap; it's a dict subclass with string keys
  67. try:
  68. from org.python.core import PyStringMap
  69. except ImportError:
  70. PyStringMap = None
  71. # UnicodeType may or may not be exported (normally imported from types)
  72. try:
  73. UnicodeType
  74. except NameError:
  75. UnicodeType = None
  76. # Pickle opcodes. See pickletools.py for extensive docs. The listing
  77. # here is in kind-of alphabetical order of 1-character pickle code.
  78. # pickletools groups them by purpose.
  79. MARK = '(' # push special markobject on stack
  80. STOP = '.' # every pickle ends with STOP
  81. POP = '0' # discard topmost stack item
  82. POP_MARK = '1' # discard stack top through topmost markobject
  83. DUP = '2' # duplicate top stack item
  84. FLOAT = 'F' # push float object; decimal string argument
  85. INT = 'I' # push integer or bool; decimal string argument
  86. BININT = 'J' # push four-byte signed int
  87. BININT1 = 'K' # push 1-byte unsigned int
  88. LONG = 'L' # push long; decimal string argument
  89. BININT2 = 'M' # push 2-byte unsigned int
  90. NONE = 'N' # push None
  91. PERSID = 'P' # push persistent object; id is taken from string arg
  92. BINPERSID = 'Q' # " " " ; " " " " stack
  93. REDUCE = 'R' # apply callable to argtuple, both on stack
  94. STRING = 'S' # push string; NL-terminated string argument
  95. BINSTRING = 'T' # push string; counted binary string argument
  96. SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
  97. UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
  98. BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
  99. APPEND = 'a' # append stack top to list below it
  100. BUILD = 'b' # call __setstate__ or __dict__.update()
  101. GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
  102. DICT = 'd' # build a dict from stack items
  103. EMPTY_DICT = '}' # push empty dict
  104. APPENDS = 'e' # extend list on stack by topmost stack slice
  105. GET = 'g' # push item from memo on stack; index is string arg
  106. BINGET = 'h' # " " " " " " ; " " 1-byte arg
  107. INST = 'i' # build & push class instance
  108. LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
  109. LIST = 'l' # build list from topmost stack items
  110. EMPTY_LIST = ']' # push empty list
  111. OBJ = 'o' # build & push class instance
  112. PUT = 'p' # store stack top in memo; index is string arg
  113. BINPUT = 'q' # " " " " " ; " " 1-byte arg
  114. LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
  115. SETITEM = 's' # add key+value pair to dict
  116. TUPLE = 't' # build tuple from topmost stack items
  117. EMPTY_TUPLE = ')' # push empty tuple
  118. SETITEMS = 'u' # modify dict by adding topmost key+value pairs
  119. BINFLOAT = 'G' # push float; arg is 8-byte float encoding
  120. TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
  121. FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
  122. # Protocol 2
  123. PROTO = '\x80' # identify pickle protocol
  124. NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
  125. EXT1 = '\x82' # push object from extension registry; 1-byte index
  126. EXT2 = '\x83' # ditto, but 2-byte index
  127. EXT4 = '\x84' # ditto, but 4-byte index
  128. TUPLE1 = '\x85' # build 1-tuple from stack top
  129. TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
  130. TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
  131. NEWTRUE = '\x88' # push True
  132. NEWFALSE = '\x89' # push False
  133. LONG1 = '\x8a' # push long from < 256 bytes
  134. LONG4 = '\x8b' # push really big long
  135. # Protocol 3
  136. BINBYTES = 'B'
  137. SHORT_BINBYTES = 'C'
  138. from zodbpickle import binary as BinaryType
  139. _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
  140. __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
  141. del x
  142. # Pickling machinery
  143. class Pickler:
  144. def __init__(self, file, protocol=None):
  145. """This takes a file-like object for writing a pickle data stream.
  146. The optional protocol argument tells the pickler to use the
  147. given protocol; supported protocols are 0, 1, 2. The default
  148. protocol is 0, to be backwards compatible. (Protocol 0 is the
  149. only protocol that can be written to a file opened in text
  150. mode and read back successfully. When using a protocol higher
  151. than 0, make sure the file is opened in binary mode, both when
  152. pickling and unpickling.)
  153. Protocol 1 is more efficient than protocol 0; protocol 2 is
  154. more efficient than protocol 1.
  155. Specifying a negative protocol version selects the highest
  156. protocol version supported. The higher the protocol used, the
  157. more recent the version of Python needed to read the pickle
  158. produced.
  159. The file parameter must have a write() method that accepts a single
  160. string argument. It can thus be an open file object, a StringIO
  161. object, or any other custom object that meets this interface.
  162. """
  163. if protocol is None:
  164. protocol = DEFAULT_PROTOCOL
  165. if protocol < 0:
  166. protocol = HIGHEST_PROTOCOL
  167. elif not 0 <= protocol <= HIGHEST_PROTOCOL:
  168. raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
  169. self.write = file.write
  170. self.memo = {}
  171. self.proto = int(protocol)
  172. self.bin = protocol >= 1
  173. self.fast = 0
  174. def clear_memo(self):
  175. """Clears the pickler's "memo".
  176. The memo is the data structure that remembers which objects the
  177. pickler has already seen, so that shared or recursive objects are
  178. pickled by reference and not by value. This method is useful when
  179. re-using picklers.
  180. """
  181. self.memo.clear()
  182. def dump(self, obj):
  183. """Write a pickled representation of obj to the open file."""
  184. if self.proto >= 2:
  185. self.write(PROTO + chr(self.proto))
  186. self.save(obj)
  187. self.write(STOP)
  188. def memoize(self, obj):
  189. """Store an object in the memo."""
  190. # The Pickler memo is a dictionary mapping object ids to 2-tuples
  191. # that contain the Unpickler memo key and the object being memoized.
  192. # The memo key is written to the pickle and will become
  193. # the key in the Unpickler's memo. The object is stored in the
  194. # Pickler memo so that transient objects are kept alive during
  195. # pickling.
  196. # The use of the Unpickler memo length as the memo key is just a
  197. # convention. The only requirement is that the memo values be unique.
  198. # But there appears no advantage to any other scheme, and this
  199. # scheme allows the Unpickler memo to be implemented as a plain (but
  200. # growable) array, indexed by memo key.
  201. if self.fast:
  202. return
  203. assert id(obj) not in self.memo
  204. memo_len = len(self.memo)
  205. self.write(self.put(memo_len))
  206. self.memo[id(obj)] = memo_len, obj
  207. # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
  208. def put(self, i, pack=struct.pack):
  209. if self.bin:
  210. if i < 256:
  211. return BINPUT + chr(i)
  212. else:
  213. return LONG_BINPUT + pack("<i", i)
  214. return PUT + repr(i) + '\n'
  215. # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
  216. def get(self, i, pack=struct.pack):
  217. if self.bin:
  218. if i < 256:
  219. return BINGET + chr(i)
  220. else:
  221. return LONG_BINGET + pack("<i", i)
  222. return GET + repr(i) + '\n'
  223. def save(self, obj):
  224. # Check for persistent id (defined by a subclass)
  225. pid = self.persistent_id(obj)
  226. if pid:
  227. self.save_pers(pid)
  228. return
  229. # Check the memo
  230. x = self.memo.get(id(obj))
  231. if x:
  232. self.write(self.get(x[0]))
  233. return
  234. # Check the type dispatch table
  235. t = type(obj)
  236. f = self.dispatch.get(t)
  237. if f:
  238. f(self, obj) # Call unbound method with explicit self
  239. return
  240. # Check copy_reg.dispatch_table
  241. reduce = dispatch_table.get(t)
  242. if reduce:
  243. rv = reduce(obj)
  244. else:
  245. # Check for a class with a custom metaclass; treat as regular class
  246. try:
  247. issc = issubclass(t, TypeType)
  248. except TypeError: # t is not a class (old Boost; see SF #502085)
  249. issc = 0
  250. if issc:
  251. self.save_global(obj)
  252. return
  253. # Check for a __reduce_ex__ method, fall back to __reduce__
  254. reduce = getattr(obj, "__reduce_ex__", None)
  255. if reduce:
  256. rv = reduce(self.proto)
  257. else:
  258. reduce = getattr(obj, "__reduce__", None)
  259. if reduce:
  260. rv = reduce()
  261. else:
  262. raise PicklingError("Can't pickle %r object: %r" %
  263. (t.__name__, obj))
  264. # Check for string returned by reduce(), meaning "save as global"
  265. if type(rv) is StringType:
  266. self.save_global(obj, rv)
  267. return
  268. # Assert that reduce() returned a tuple
  269. if type(rv) is not TupleType:
  270. raise PicklingError("%s must return string or tuple" % reduce)
  271. # Assert that it returned an appropriately sized tuple
  272. l = len(rv)
  273. if not (2 <= l <= 5):
  274. raise PicklingError("Tuple returned by %s must have "
  275. "two to five elements" % reduce)
  276. # Save the reduce() output and finally memoize the object
  277. self.save_reduce(obj=obj, *rv)
  278. def persistent_id(self, obj):
  279. # This exists so a subclass can override it
  280. return None
  281. def save_pers(self, pid):
  282. # Save a persistent id reference
  283. if self.bin:
  284. self.save(pid)
  285. self.write(BINPERSID)
  286. else:
  287. self.write(PERSID + str(pid) + '\n')
  288. def save_reduce(self, func, args, state=None,
  289. listitems=None, dictitems=None, obj=None):
  290. # This API is called by some subclasses
  291. # Assert that args is a tuple or None
  292. if not isinstance(args, TupleType):
  293. raise PicklingError("args from reduce() should be a tuple")
  294. # Assert that func is callable
  295. if not hasattr(func, '__call__'):
  296. raise PicklingError("func from reduce should be callable")
  297. save = self.save
  298. write = self.write
  299. # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
  300. if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
  301. # A __reduce__ implementation can direct protocol 2 to
  302. # use the more efficient NEWOBJ opcode, while still
  303. # allowing protocol 0 and 1 to work normally. For this to
  304. # work, the function returned by __reduce__ should be
  305. # called __newobj__, and its first argument should be a
  306. # new-style class. The implementation for __newobj__
  307. # should be as follows, although pickle has no way to
  308. # verify this:
  309. #
  310. # def __newobj__(cls, *args):
  311. # return cls.__new__(cls, *args)
  312. #
  313. # Protocols 0 and 1 will pickle a reference to __newobj__,
  314. # while protocol 2 (and above) will pickle a reference to
  315. # cls, the remaining args tuple, and the NEWOBJ code,
  316. # which calls cls.__new__(cls, *args) at unpickling time
  317. # (see load_newobj below). If __reduce__ returns a
  318. # three-tuple, the state from the third tuple item will be
  319. # pickled regardless of the protocol, calling __setstate__
  320. # at unpickling time (see load_build below).
  321. #
  322. # Note that no standard __newobj__ implementation exists;
  323. # you have to provide your own. This is to enforce
  324. # compatibility with Python 2.2 (pickles written using
  325. # protocol 0 or 1 in Python 2.3 should be unpicklable by
  326. # Python 2.2).
  327. cls = args[0]
  328. if not hasattr(cls, "__new__"):
  329. raise PicklingError(
  330. "args[0] from __newobj__ args has no __new__")
  331. if obj is not None and cls is not obj.__class__:
  332. raise PicklingError(
  333. "args[0] from __newobj__ args has the wrong class")
  334. args = args[1:]
  335. save(cls)
  336. save(args)
  337. write(NEWOBJ)
  338. else:
  339. save(func)
  340. save(args)
  341. write(REDUCE)
  342. if obj is not None:
  343. self.memoize(obj)
  344. # More new special cases (that work with older protocols as
  345. # well): when __reduce__ returns a tuple with 4 or 5 items,
  346. # the 4th and 5th item should be iterators that provide list
  347. # items and dict items (as (key, value) tuples), or None.
  348. if listitems is not None:
  349. self._batch_appends(listitems)
  350. if dictitems is not None:
  351. self._batch_setitems(dictitems)
  352. if state is not None:
  353. save(state)
  354. write(BUILD)
  355. # Methods below this point are dispatched through the dispatch table
  356. dispatch = {}
  357. def save_none(self, obj):
  358. self.write(NONE)
  359. dispatch[NoneType] = save_none
  360. def save_bool(self, obj):
  361. if self.proto >= 2:
  362. self.write(obj and NEWTRUE or NEWFALSE)
  363. else:
  364. self.write(obj and TRUE or FALSE)
  365. dispatch[bool] = save_bool
  366. def save_int(self, obj, pack=struct.pack):
  367. if self.bin:
  368. # If the int is small enough to fit in a signed 4-byte 2's-comp
  369. # format, we can store it more efficiently than the general
  370. # case.
  371. # First one- and two-byte unsigned ints:
  372. if obj >= 0:
  373. if obj <= 0xff:
  374. self.write(BININT1 + chr(obj))
  375. return
  376. if obj <= 0xffff:
  377. self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
  378. return
  379. # Next check for 4-byte signed ints:
  380. high_bits = obj >> 31 # note that Python shift sign-extends
  381. if high_bits == 0 or high_bits == -1:
  382. # All high bits are copies of bit 2**31, so the value
  383. # fits in a 4-byte signed int.
  384. self.write(BININT + pack("<i", obj))
  385. return
  386. # Text pickle, or int too big to fit in signed 4-byte format.
  387. self.write(INT + repr(obj) + '\n')
  388. dispatch[IntType] = save_int
  389. def save_long(self, obj, pack=struct.pack):
  390. if self.proto >= 2:
  391. bytes = encode_long(obj)
  392. n = len(bytes)
  393. if n < 256:
  394. self.write(LONG1 + chr(n) + bytes)
  395. else:
  396. self.write(LONG4 + pack("<i", n) + bytes)
  397. return
  398. self.write(LONG + repr(obj) + '\n')
  399. dispatch[LongType] = save_long
  400. def save_float(self, obj, pack=struct.pack):
  401. if self.bin:
  402. self.write(BINFLOAT + pack('>d', obj))
  403. else:
  404. self.write(FLOAT + repr(obj) + '\n')
  405. dispatch[FloatType] = save_float
  406. def save_string(self, obj, pack=struct.pack):
  407. if self.bin:
  408. n = len(obj)
  409. if n < 256:
  410. self.write(SHORT_BINSTRING + chr(n) + obj)
  411. else:
  412. self.write(BINSTRING + pack("<i", n) + obj)
  413. else:
  414. self.write(STRING + repr(obj) + '\n')
  415. self.memoize(obj)
  416. dispatch[StringType] = save_string
  417. def save_unicode(self, obj, pack=struct.pack):
  418. if self.bin:
  419. encoding = obj.encode('utf-8')
  420. n = len(encoding)
  421. self.write(BINUNICODE + pack("<i", n) + encoding)
  422. else:
  423. obj = obj.replace("\\", "\\u005c")
  424. obj = obj.replace("\n", "\\u000a")
  425. self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
  426. self.memoize(obj)
  427. dispatch[UnicodeType] = save_unicode
  428. if StringType is UnicodeType:
  429. # This is true for Jython
  430. def save_string(self, obj, pack=struct.pack):
  431. unicode = obj.isunicode()
  432. if self.bin:
  433. if unicode:
  434. obj = obj.encode("utf-8")
  435. l = len(obj)
  436. if l < 256 and not unicode:
  437. self.write(SHORT_BINSTRING + chr(l) + obj)
  438. else:
  439. s = pack("<i", l)
  440. if unicode:
  441. self.write(BINUNICODE + s + obj)
  442. else:
  443. self.write(BINSTRING + s + obj)
  444. else:
  445. if unicode:
  446. obj = obj.replace("\\", "\\u005c")
  447. obj = obj.replace("\n", "\\u000a")
  448. obj = obj.encode('raw-unicode-escape')
  449. self.write(UNICODE + obj + '\n')
  450. else:
  451. self.write(STRING + repr(obj) + '\n')
  452. self.memoize(obj)
  453. dispatch[StringType] = save_string
  454. def save_tuple(self, obj):
  455. write = self.write
  456. proto = self.proto
  457. n = len(obj)
  458. if n == 0:
  459. if proto:
  460. write(EMPTY_TUPLE)
  461. else:
  462. write(MARK + TUPLE)
  463. return
  464. save = self.save
  465. memo = self.memo
  466. if n <= 3 and proto >= 2:
  467. for element in obj:
  468. save(element)
  469. # Subtle. Same as in the big comment below.
  470. if id(obj) in memo:
  471. get = self.get(memo[id(obj)][0])
  472. write(POP * n + get)
  473. else:
  474. write(_tuplesize2code[n])
  475. self.memoize(obj)
  476. return
  477. # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
  478. # has more than 3 elements.
  479. write(MARK)
  480. for element in obj:
  481. save(element)
  482. if id(obj) in memo:
  483. # Subtle. d was not in memo when we entered save_tuple(), so
  484. # the process of saving the tuple's elements must have saved
  485. # the tuple itself: the tuple is recursive. The proper action
  486. # now is to throw away everything we put on the stack, and
  487. # simply GET the tuple (it's already constructed). This check
  488. # could have been done in the "for element" loop instead, but
  489. # recursive tuples are a rare thing.
  490. get = self.get(memo[id(obj)][0])
  491. if proto:
  492. write(POP_MARK + get)
  493. else: # proto 0 -- POP_MARK not available
  494. write(POP * (n+1) + get)
  495. return
  496. # No recursion.
  497. self.write(TUPLE)
  498. self.memoize(obj)
  499. dispatch[TupleType] = save_tuple
  500. # save_empty_tuple() isn't used by anything in Python 2.3. However, I
  501. # found a Pickler subclass in Zope3 that calls it, so it's not harmless
  502. # to remove it.
  503. def save_empty_tuple(self, obj):
  504. self.write(EMPTY_TUPLE)
  505. def save_list(self, obj):
  506. write = self.write
  507. if self.bin:
  508. write(EMPTY_LIST)
  509. else: # proto 0 -- can't use EMPTY_LIST
  510. write(MARK + LIST)
  511. self.memoize(obj)
  512. self._batch_appends(iter(obj))
  513. dispatch[ListType] = save_list
  514. # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
  515. # out of synch, though.
  516. _BATCHSIZE = 1000
  517. def _batch_appends(self, items):
  518. # Helper to batch up APPENDS sequences
  519. save = self.save
  520. write = self.write
  521. if not self.bin:
  522. for x in items:
  523. save(x)
  524. write(APPEND)
  525. return
  526. r = xrange(self._BATCHSIZE)
  527. while items is not None:
  528. tmp = []
  529. for i in r:
  530. try:
  531. x = items.next()
  532. tmp.append(x)
  533. except StopIteration:
  534. items = None
  535. break
  536. n = len(tmp)
  537. if n > 1:
  538. write(MARK)
  539. for x in tmp:
  540. save(x)
  541. write(APPENDS)
  542. elif n:
  543. save(tmp[0])
  544. write(APPEND)
  545. # else tmp is empty, and we're done
  546. def save_dict(self, obj):
  547. write = self.write
  548. if self.bin:
  549. write(EMPTY_DICT)
  550. else: # proto 0 -- can't use EMPTY_DICT
  551. write(MARK + DICT)
  552. self.memoize(obj)
  553. self._batch_setitems(obj.iteritems())
  554. dispatch[DictionaryType] = save_dict
  555. if not PyStringMap is None:
  556. dispatch[PyStringMap] = save_dict
  557. def _batch_setitems(self, items):
  558. # Helper to batch up SETITEMS sequences; proto >= 1 only
  559. save = self.save
  560. write = self.write
  561. if not self.bin:
  562. for k, v in items:
  563. save(k)
  564. save(v)
  565. write(SETITEM)
  566. return
  567. r = xrange(self._BATCHSIZE)
  568. while items is not None:
  569. tmp = []
  570. for i in r:
  571. try:
  572. tmp.append(items.next())
  573. except StopIteration:
  574. items = None
  575. break
  576. n = len(tmp)
  577. if n > 1:
  578. write(MARK)
  579. for k, v in tmp:
  580. save(k)
  581. save(v)
  582. write(SETITEMS)
  583. elif n:
  584. k, v = tmp[0]
  585. save(k)
  586. save(v)
  587. write(SETITEM)
  588. # else tmp is empty, and we're done
  589. def save_binary(self, obj, pack=struct.pack):
  590. if self.proto >= 3:
  591. n = len(obj)
  592. if n < 256:
  593. self.write(SHORT_BINBYTES + chr(n) + obj)
  594. else:
  595. self.write(BINBYTES + pack("<i", n) + obj)
  596. self.memoize(obj)
  597. else:
  598. self.save_string(obj)
  599. dispatch[BinaryType] = save_binary
  600. def save_inst(self, obj):
  601. cls = obj.__class__
  602. if cls is BinaryType:
  603. return self.save_binary(obj)
  604. memo = self.memo
  605. write = self.write
  606. save = self.save
  607. if hasattr(obj, '__getinitargs__'):
  608. args = obj.__getinitargs__()
  609. len(args) # XXX Assert it's a sequence
  610. _keep_alive(args, memo)
  611. else:
  612. args = ()
  613. write(MARK)
  614. if self.bin:
  615. save(cls)
  616. for arg in args:
  617. save(arg)
  618. write(OBJ)
  619. else:
  620. for arg in args:
  621. save(arg)
  622. write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
  623. self.memoize(obj)
  624. try:
  625. getstate = obj.__getstate__
  626. except AttributeError:
  627. stuff = obj.__dict__
  628. else:
  629. stuff = getstate()
  630. _keep_alive(stuff, memo)
  631. save(stuff)
  632. write(BUILD)
  633. dispatch[InstanceType] = save_inst
  634. def save_global(self, obj, name=None, pack=struct.pack):
  635. write = self.write
  636. memo = self.memo
  637. if name is None:
  638. name = obj.__name__
  639. module = getattr(obj, "__module__", None)
  640. if module is None:
  641. module = whichmodule(obj, name)
  642. try:
  643. __import__(module)
  644. mod = sys.modules[module]
  645. klass = getattr(mod, name)
  646. except (ImportError, KeyError, AttributeError):
  647. raise PicklingError(
  648. "Can't pickle %r: it's not found as %s.%s" %
  649. (obj, module, name))
  650. else:
  651. if klass is not obj:
  652. raise PicklingError(
  653. "Can't pickle %r: it's not the same object as %s.%s" %
  654. (obj, module, name))
  655. if self.proto >= 2:
  656. code = _extension_registry.get((module, name))
  657. if code:
  658. assert code > 0
  659. if code <= 0xff:
  660. write(EXT1 + chr(code))
  661. elif code <= 0xffff:
  662. write("%c%c%c" % (EXT2, code&0xff, code>>8))
  663. else:
  664. write(EXT4 + pack("<i", code))
  665. return
  666. write(GLOBAL + module + '\n' + name + '\n')
  667. self.memoize(obj)
  668. dispatch[ClassType] = save_global
  669. dispatch[FunctionType] = save_global
  670. dispatch[BuiltinFunctionType] = save_global
  671. dispatch[TypeType] = save_global
  672. # Pickling helpers
  673. def _keep_alive(x, memo):
  674. """Keeps a reference to the object x in the memo.
  675. Because we remember objects by their id, we have
  676. to assure that possibly temporary objects are kept
  677. alive by referencing them.
  678. We store a reference at the id of the memo, which should
  679. normally not be used unless someone tries to deepcopy
  680. the memo itself...
  681. """
  682. try:
  683. memo[id(memo)].append(x)
  684. except KeyError:
  685. # aha, this is the first one :-)
  686. memo[id(memo)]=[x]
  687. # A cache for whichmodule(), mapping a function object to the name of
  688. # the module in which the function was found.
  689. classmap = {} # called classmap for backwards compatibility
  690. def whichmodule(func, funcname):
  691. """Figure out the module in which a function occurs.
  692. Search sys.modules for the module.
  693. Cache in classmap.
  694. Return a module name.
  695. If the function cannot be found, return "__main__".
  696. """
  697. # Python functions should always get an __module__ from their globals.
  698. mod = getattr(func, "__module__", None)
  699. if mod is not None:
  700. return mod
  701. if func in classmap:
  702. return classmap[func]
  703. for name, module in sys.modules.items():
  704. if module is None:
  705. continue # skip dummy package entries
  706. if name != '__main__' and getattr(module, funcname, None) is func:
  707. break
  708. else:
  709. name = '__main__'
  710. classmap[func] = name
  711. return name
  712. # Unpickling machinery
  713. class Unpickler:
  714. def __init__(self, file):
  715. """This takes a file-like object for reading a pickle data stream.
  716. The protocol version of the pickle is detected automatically, so no
  717. proto argument is needed.
  718. The file-like object must have two methods, a read() method that
  719. takes an integer argument, and a readline() method that requires no
  720. arguments. Both methods should return a string. Thus file-like
  721. object can be a file object opened for reading, a StringIO object,
  722. or any other custom object that meets this interface.
  723. """
  724. self.readline = file.readline
  725. self.read = file.read
  726. self.memo = {}
  727. def load(self):
  728. """Read a pickled object representation from the open file.
  729. Return the reconstituted object hierarchy specified in the file.
  730. """
  731. self.mark = object() # any new unique object
  732. self.stack = []
  733. self.append = self.stack.append
  734. read = self.read
  735. dispatch = self.dispatch
  736. try:
  737. while 1:
  738. key = read(1)
  739. dispatch[key](self)
  740. except _Stop, stopinst:
  741. return stopinst.value
  742. def noload(self):
  743. """Read a pickled object representation from the open file.
  744. If the object was an intrinsic type such as a literal list, dict
  745. or tuple, return it. Otherwise (if the object was an instance),
  746. return nothing useful.
  747. """
  748. self.mark = object() # any new unique object
  749. self.stack = []
  750. self.append = self.stack.append
  751. read = self.read
  752. dispatch = self.nl_dispatch
  753. try:
  754. while 1:
  755. key = read(1)
  756. dispatch[key](self)
  757. except _Stop, stopinst:
  758. return stopinst.value
  759. # Return largest index k such that self.stack[k] is self.mark.
  760. # If the stack doesn't contain a mark, eventually raises IndexError.
  761. # This could be sped by maintaining another stack, of indices at which
  762. # the mark appears. For that matter, the latter stack would suffice,
  763. # and we wouldn't need to push mark objects on self.stack at all.
  764. # Doing so is probably a good thing, though, since if the pickle is
  765. # corrupt (or hostile) we may get a clue from finding self.mark embedded
  766. # in unpickled objects.
  767. def marker(self):
  768. stack = self.stack
  769. mark = self.mark
  770. k = len(stack)-1
  771. while stack[k] is not mark: k = k-1
  772. return k
  773. dispatch = {}
  774. def load_eof(self):
  775. raise EOFError
  776. dispatch[''] = load_eof
  777. def load_proto(self):
  778. proto = ord(self.read(1))
  779. if not 0 <= proto <= HIGHEST_PROTOCOL:
  780. raise ValueError, "unsupported pickle protocol: %d" % proto
  781. dispatch[PROTO] = load_proto
  782. def load_persid(self):
  783. pid = self.readline()[:-1]
  784. self.append(self.persistent_load(pid))
  785. dispatch[PERSID] = load_persid
  786. def load_binpersid(self):
  787. pid = self.stack.pop()
  788. self.append(self.persistent_load(pid))
  789. dispatch[BINPERSID] = load_binpersid
  790. def load_none(self):
  791. self.append(None)
  792. dispatch[NONE] = load_none
  793. def load_false(self):
  794. self.append(False)
  795. dispatch[NEWFALSE] = load_false
  796. def load_true(self):
  797. self.append(True)
  798. dispatch[NEWTRUE] = load_true
  799. def load_int(self):
  800. data = self.readline()
  801. if data == FALSE[1:]:
  802. val = False
  803. elif data == TRUE[1:]:
  804. val = True
  805. else:
  806. try:
  807. val = int(data)
  808. except ValueError:
  809. val = long(data)
  810. self.append(val)
  811. dispatch[INT] = load_int
  812. def load_binint(self):
  813. self.append(mloads('i' + self.read(4)))
  814. dispatch[BININT] = load_binint
  815. def load_binint1(self):
  816. self.append(ord(self.read(1)))
  817. dispatch[BININT1] = load_binint1
  818. def load_binint2(self):
  819. self.append(mloads('i' + self.read(2) + '\000\000'))
  820. dispatch[BININT2] = load_binint2
  821. def load_long(self):
  822. self.append(long(self.readline()[:-1], 0))
  823. dispatch[LONG] = load_long
  824. def load_long1(self):
  825. n = ord(self.read(1))
  826. bytes = self.read(n)
  827. self.append(decode_long(bytes))
  828. dispatch[LONG1] = load_long1
  829. def load_long4(self):
  830. n = mloads('i' + self.read(4))
  831. bytes = self.read(n)
  832. self.append(decode_long(bytes))
  833. dispatch[LONG4] = load_long4
  834. def load_float(self):
  835. self.append(float(self.readline()[:-1]))
  836. dispatch[FLOAT] = load_float
  837. def load_binfloat(self, unpack=struct.unpack):
  838. self.append(unpack('>d', self.read(8))[0])
  839. dispatch[BINFLOAT] = load_binfloat
  840. def load_string(self):
  841. rep = self.readline()[:-1]
  842. for q in "\"'": # double or single quote
  843. if rep.startswith(q):
  844. if len(rep) < 2 or not rep.endswith(q):
  845. raise ValueError, "insecure string pickle"
  846. rep = rep[len(q):-len(q)]
  847. break
  848. else:
  849. raise ValueError, "insecure string pickle"
  850. self.append(rep.decode("string-escape"))
  851. dispatch[STRING] = load_string
  852. def load_binstring(self):
  853. len = mloads('i' + self.read(4))
  854. self.append(self.read(len))
  855. dispatch[BINSTRING] = load_binstring
  856. def load_binbytes(self):
  857. len = mloads('i' + self.read(4))
  858. self.append(BinaryType(self.read(len)))
  859. dispatch[BINBYTES] = load_binbytes
  860. def load_unicode(self):
  861. self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
  862. dispatch[UNICODE] = load_unicode
  863. def load_binunicode(self):
  864. len = mloads('i' + self.read(4))
  865. self.append(unicode(self.read(len),'utf-8'))
  866. dispatch[BINUNICODE] = load_binunicode
  867. def load_short_binstring(self):
  868. len = ord(self.read(1))
  869. self.append(self.read(len))
  870. dispatch[SHORT_BINSTRING] = load_short_binstring
  871. def load_short_binbytes(self):
  872. len = ord(self.read(1))
  873. self.append(BinaryType(self.read(len)))
  874. dispatch[SHORT_BINBYTES] = load_short_binbytes
  875. def load_tuple(self):
  876. k = self.marker()
  877. self.stack[k:] = [tuple(self.stack[k+1:])]
  878. dispatch[TUPLE] = load_tuple
  879. def load_empty_tuple(self):
  880. self.stack.append(())
  881. dispatch[EMPTY_TUPLE] = load_empty_tuple
  882. def load_tuple1(self):
  883. self.stack[-1] = (self.stack[-1],)
  884. dispatch[TUPLE1] = load_tuple1
  885. def load_tuple2(self):
  886. self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
  887. dispatch[TUPLE2] = load_tuple2
  888. def load_tuple3(self):
  889. self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
  890. dispatch[TUPLE3] = load_tuple3
  891. def load_empty_list(self):
  892. self.stack.append([])
  893. dispatch[EMPTY_LIST] = load_empty_list
  894. def load_empty_dictionary(self):
  895. self.stack.append({})
  896. dispatch[EMPTY_DICT] = load_empty_dictionary
  897. def load_list(self):
  898. k = self.marker()
  899. self.stack[k:] = [self.stack[k+1:]]
  900. dispatch[LIST] = load_list
  901. def load_dict(self):
  902. k = self.marker()
  903. d = {}
  904. items = self.stack[k+1:]
  905. for i in range(0, len(items), 2):
  906. key = items[i]
  907. value = items[i+1]
  908. d[key] = value
  909. self.stack[k:] = [d]
  910. dispatch[DICT] = load_dict
  911. # INST and OBJ differ only in how they get a class object. It's not
  912. # only sensible to do the rest in a common routine, the two routines
  913. # previously diverged and grew different bugs.
  914. # klass is the class to instantiate, and k points to the topmost mark
  915. # object, following which are the arguments for klass.__init__.
  916. def _instantiate(self, klass, k):
  917. args = tuple(self.stack[k+1:])
  918. del self.stack[k:]
  919. instantiated = 0
  920. if (not args and
  921. type(klass) is ClassType and
  922. not hasattr(klass, "__getinitargs__")):
  923. try:
  924. value = _EmptyClass()
  925. value.__class__ = klass
  926. instantiated = 1
  927. except RuntimeError:
  928. # In restricted execution, assignment to inst.__class__ is
  929. # prohibited
  930. pass
  931. if not instantiated:
  932. try:
  933. value = klass(*args)
  934. except TypeError, err:
  935. raise TypeError, "in constructor for %s: %s" % (
  936. klass.__name__, str(err)), sys.exc_info()[2]
  937. self.append(value)
  938. def load_inst(self):
  939. module = self.readline()[:-1]
  940. name = self.readline()[:-1]
  941. klass = self.find_class(module, name)
  942. self._instantiate(klass, self.marker())
  943. dispatch[INST] = load_inst
  944. def load_obj(self):
  945. # Stack is ... markobject classobject arg1 arg2 ...
  946. k = self.marker()
  947. klass = self.stack.pop(k+1)
  948. self._instantiate(klass, k)
  949. dispatch[OBJ] = load_obj
  950. def load_newobj(self):
  951. args = self.stack.pop()
  952. cls = self.stack[-1]
  953. obj = cls.__new__(cls, *args)
  954. self.stack[-1] = obj
  955. dispatch[NEWOBJ] = load_newobj
  956. def load_global(self):
  957. module = self.readline()[:-1]
  958. name = self.readline()[:-1]
  959. klass = self.find_class(module, name)
  960. self.append(klass)
  961. dispatch[GLOBAL] = load_global
  962. def load_ext1(self):
  963. code = ord(self.read(1))
  964. self.get_extension(code)
  965. dispatch[EXT1] = load_ext1
  966. def load_ext2(self):
  967. code = mloads('i' + self.read(2) + '\000\000')
  968. self.get_extension(code)
  969. dispatch[EXT2] = load_ext2
  970. def load_ext4(self):
  971. code = mloads('i' + self.read(4))
  972. self.get_extension(code)
  973. dispatch[EXT4] = load_ext4
  974. def get_extension(self, code):
  975. nil = []
  976. obj = _extension_cache.get(code, nil)
  977. if obj is not nil:
  978. self.append(obj)
  979. return
  980. key = _inverted_registry.get(code)
  981. if not key:
  982. raise ValueError("unregistered extension code %d" % code)
  983. obj = self.find_class(*key)
  984. _extension_cache[code] = obj
  985. self.append(obj)
  986. def find_class(self, module, name):
  987. # Subclasses may override this
  988. __import__(module)
  989. mod = sys.modules[module]
  990. klass = getattr(mod, name)
  991. return klass
  992. def load_reduce(self):
  993. stack = self.stack
  994. args = stack.pop()
  995. func = stack[-1]
  996. value = func(*args)
  997. stack[-1] = value
  998. dispatch[REDUCE] = load_reduce
  999. def load_pop(self):
  1000. del self.stack[-1]
  1001. dispatch[POP] = load_pop
  1002. def load_pop_mark(self):
  1003. k = self.marker()
  1004. del self.stack[k:]
  1005. dispatch[POP_MARK] = load_pop_mark
  1006. def load_dup(self):
  1007. self.append(self.stack[-1])
  1008. dispatch[DUP] = load_dup
  1009. def load_get(self):
  1010. self.append(self.memo[self.readline()[:-1]])
  1011. dispatch[GET] = load_get
  1012. def load_binget(self):
  1013. i = ord(self.read(1))
  1014. self.append(self.memo[repr(i)])
  1015. dispatch[BINGET] = load_binget
  1016. def load_long_binget(self):
  1017. i = mloads('i' + self.read(4))
  1018. self.append(self.memo[repr(i)])
  1019. dispatch[LONG_BINGET] = load_long_binget
  1020. def load_put(self):
  1021. self.memo[self.readline()[:-1]] = self.stack[-1]
  1022. dispatch[PUT] = load_put
  1023. def load_binput(self):
  1024. i = ord(self.read(1))
  1025. self.memo[repr(i)] = self.stack[-1]
  1026. dispatch[BINPUT] = load_binput
  1027. def load_long_binput(self):
  1028. i = mloads('i' + self.read(4))
  1029. self.memo[repr(i)] = self.stack[-1]
  1030. dispatch[LONG_BINPUT] = load_long_binput
  1031. def load_append(self):
  1032. stack = self.stack
  1033. value = stack.pop()
  1034. list = stack[-1]
  1035. list.append(value)
  1036. dispatch[APPEND] = load_append
  1037. def load_appends(self):
  1038. stack = self.stack
  1039. mark = self.marker()
  1040. list = stack[mark - 1]
  1041. list.extend(stack[mark + 1:])
  1042. del stack[mark:]
  1043. dispatch[APPENDS] = load_appends
  1044. def load_setitem(self):
  1045. stack = self.stack
  1046. value = stack.pop()
  1047. key = stack.pop()
  1048. dict = stack[-1]
  1049. dict[key] = value
  1050. dispatch[SETITEM] = load_setitem
  1051. def load_setitems(self):
  1052. stack = self.stack
  1053. mark = self.marker()
  1054. dict = stack[mark - 1]
  1055. for i in range(mark + 1, len(stack), 2):
  1056. dict[stack[i]] = stack[i + 1]
  1057. del stack[mark:]
  1058. dispatch[SETITEMS] = load_setitems
  1059. def load_build(self):
  1060. stack = self.stack
  1061. state = stack.pop()
  1062. inst = stack[-1]
  1063. setstate = getattr(inst, "__setstate__", None)
  1064. if setstate:
  1065. setstate(state)
  1066. return
  1067. slotstate = None
  1068. if isinstance(state, tuple) and len(state) == 2:
  1069. state, slotstate = state
  1070. if state:
  1071. try:
  1072. d = inst.__dict__
  1073. try:
  1074. for k, v in state.iteritems():
  1075. d[intern(k)] = v
  1076. # keys in state don't have to be strings
  1077. # don't blow up, but don't go out of our way
  1078. except TypeError:
  1079. d.update(state)
  1080. except RuntimeError:
  1081. # XXX In restricted execution, the instance's __dict__
  1082. # is not accessible. Use the old way of unpickling
  1083. # the instance variables. This is a semantic
  1084. # difference when unpickling in restricted
  1085. # vs. unrestricted modes.
  1086. # Note, however, that cPickle has never tried to do the
  1087. # .update() business, and always uses
  1088. # PyObject_SetItem(inst.__dict__, key, value) in a
  1089. # loop over state.items().
  1090. for k, v in state.items():
  1091. setattr(inst, k, v)
  1092. if slotstate:
  1093. for k, v in slotstate.items():
  1094. setattr(inst, k, v)
  1095. dispatch[BUILD] = load_build
  1096. def load_mark(self):
  1097. self.append(self.mark)
  1098. dispatch[MARK] = load_mark
  1099. def load_stop(self):
  1100. value = self.stack.pop()
  1101. raise _Stop(value)
  1102. dispatch[STOP] = load_stop
  1103. nl_dispatch = dispatch.copy()
  1104. def noload_obj(self):
  1105. # Stack is ... markobject classobject arg1 arg2 ...
  1106. k = self.marker()
  1107. klass = self.stack.pop(k+1)
  1108. nl_dispatch[OBJ[0]] = noload_obj
  1109. def noload_inst(self):
  1110. self.readline() # skip module
  1111. self.readline()[:-1] # skip name
  1112. k = self.marker()
  1113. klass = self.stack.pop(k+1)
  1114. self.append(None)
  1115. nl_dispatch[INST[0]] = noload_inst
  1116. def noload_newobj(self):
  1117. self.stack.pop() # skip args
  1118. self.stack.pop() # skip cls
  1119. self.stack.append(None)
  1120. nl_dispatch[NEWOBJ[0]] = noload_newobj
  1121. def noload_global(self):
  1122. self.readline() # skip module
  1123. self.readline()[:-1] # skip name
  1124. self.append(None)
  1125. nl_dispatch[GLOBAL[0]] = noload_global
  1126. def noload_append(self):
  1127. if self.stack[-2] is not None:
  1128. self.load_append()
  1129. else:
  1130. self.stack.pop()
  1131. nl_dispatch[APPEND[0]] = noload_append
  1132. def noload_appends(self):
  1133. stack = self.stack
  1134. mark = self.marker()
  1135. list = stack[mark - 1]
  1136. if list is not None:
  1137. list.extend(stack[mark + 1:])
  1138. del self.stack[mark:]
  1139. nl_dispatch[APPENDS[0]] = noload_appends
  1140. def noload_setitem(self):
  1141. if self.stack[-3] is not None:
  1142. self.load_setitem()
  1143. else:
  1144. self.stack.pop() # skip value
  1145. self.stack.pop() # skip key
  1146. nl_dispatch[SETITEM[0]] = noload_setitem
  1147. def noload_setitems(self):
  1148. stack = self.stack
  1149. mark = self.marker()
  1150. dict = stack[mark - 1]
  1151. if dict is not None:
  1152. for i in range(mark + 1, len(stack), 2):
  1153. dict[stack[i]] = stack[i + 1]
  1154. del stack[mark:]
  1155. nl_dispatch[SETITEMS[0]] = noload_setitems
  1156. def noload_reduce(self):
  1157. self.stack.pop() # skip args
  1158. self.stack.pop() # skip func
  1159. self.stack.append(None)
  1160. nl_dispatch[REDUCE[0]] = noload_reduce
  1161. def noload_build(self):
  1162. state = self.stack.pop()
  1163. nl_dispatch[BUILD[0]] = noload_build
  1164. def noload_ext1(self):
  1165. code = ord(self.read(1))
  1166. self.get_extension(code)
  1167. self.stack.pop()
  1168. self.stack.append(None)
  1169. nl_dispatch[EXT1[0]] = noload_ext1
  1170. def noload_ext2(self):
  1171. code = mloads(b'i' + self.read(2) + b'\000\000')
  1172. self.get_extension(code)
  1173. self.stack.pop()
  1174. self.stack.append(None)
  1175. nl_dispatch[EXT2[0]] = noload_ext2
  1176. def noload_ext4(self):
  1177. code = mloads(b'i' + self.read(4))
  1178. self.get_extension(code)
  1179. self.stack.pop()
  1180. self.stack.append(None)
  1181. nl_dispatch[EXT4[0]] = noload_ext4
  1182. # Helper class for load_inst/load_obj
  1183. class _EmptyClass:
  1184. pass
  1185. # Encode/decode longs in linear time.
  1186. import binascii as _binascii
  1187. def encode_long(x):
  1188. r"""Encode a long to a two's complement little-endian binary string.
  1189. Note that 0L is a special case, returning an empty string, to save a
  1190. byte in the LONG1 pickling context.
  1191. >>> encode_long(0L)
  1192. ''
  1193. >>> encode_long(255L)
  1194. '\xff\x00'
  1195. >>> encode_long(32767L)
  1196. '\xff\x7f'
  1197. >>> encode_long(-256L)
  1198. '\x00\xff'
  1199. >>> encode_long(-32768L)
  1200. '\x00\x80'
  1201. >>> encode_long(-128L)
  1202. '\x80'
  1203. >>> encode_long(127L)
  1204. '\x7f'
  1205. >>>
  1206. """
  1207. if x == 0:
  1208. return ''
  1209. if x > 0:
  1210. ashex = hex(x)
  1211. assert ashex.startswith("0x")
  1212. njunkchars = 2 + ashex.endswith('L')
  1213. nibbles = len(ashex) - njunkchars
  1214. if nibbles & 1:
  1215. # need an even # of nibbles for unhexlify
  1216. ashex = "0x0" + ashex[2:]
  1217. elif int(ashex[2], 16) >= 8:
  1218. # "looks negative", so need a byte of sign bits
  1219. ashex = "0x00" + ashex[2:]
  1220. else:
  1221. # Build the 256's-complement: (1L << nbytes) + x. The trick is
  1222. # to find the number of bytes in linear time (although that should
  1223. # really be a constant-time task).
  1224. ashex = hex(-x)
  1225. assert ashex.startswith("0x")
  1226. njunkchars = 2 + ashex.endswith('L')
  1227. nibbles = len(ashex) - njunkchars
  1228. if nibbles & 1:
  1229. # Extend to a full byte.
  1230. nibbles += 1
  1231. nbits = nibbles * 4
  1232. x += 1L << nbits
  1233. assert x > 0
  1234. ashex = hex(x)
  1235. njunkchars = 2 + ashex.endswith('L')
  1236. newnibbles = len(ashex) - njunkchars
  1237. if newnibbles < nibbles:
  1238. ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
  1239. if int(ashex[2], 16) < 8:
  1240. # "looks positive", so need a byte of sign bits
  1241. ashex = "0xff" + ashex[2:]
  1242. if ashex.endswith('L'):
  1243. ashex = ashex[2:-1]
  1244. else:
  1245. ashex = ashex[2:]
  1246. assert len(ashex) & 1 == 0, (x, ashex)
  1247. binary = _binascii.unhexlify(ashex)
  1248. return binary[::-1]
  1249. def decode_long(data):
  1250. r"""Decode a long from a two's complement little-endian binary string.
  1251. >>> decode_long('')
  1252. 0L
  1253. >>> decode_long("\xff\x00")
  1254. 255L
  1255. >>> decode_long("\xff\x7f")
  1256. 32767L
  1257. >>> decode_long("\x00\xff")
  1258. -256L
  1259. >>> decode_long("\x00\x80")
  1260. -32768L
  1261. >>> decode_long("\x80")
  1262. -128L
  1263. >>> decode_long("\x7f")
  1264. 127L
  1265. """
  1266. nbytes = len(data)
  1267. if nbytes == 0:
  1268. return 0L
  1269. ashex = _binascii.hexlify(data[::-1])
  1270. n = long(ashex, 16) # quadratic time before Python 2.3; linear now
  1271. if data[-1] >= '\x80':
  1272. n -= 1L << (nbytes * 8)
  1273. return n
  1274. # Shorthands
  1275. try:
  1276. from cStringIO import StringIO
  1277. except ImportError:
  1278. from StringIO import StringIO
  1279. def dump(obj, file, protocol=None):
  1280. Pickler(file, protocol).dump(obj)
  1281. def dumps(obj, protocol=None):
  1282. file = StringIO()
  1283. Pickler(file, protocol).dump(obj)
  1284. return file.getvalue()
  1285. def load(file):
  1286. return Unpickler(file).load()
  1287. def loads(str):
  1288. file = StringIO(str)
  1289. return Unpickler(file).load()
  1290. # Doctest
  1291. def _test():
  1292. import doctest
  1293. return doctest.testmod()
  1294. if __name__ == "__main__":
  1295. _test()