-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathcPickle.java
More file actions
2292 lines (1984 loc) · 77.3 KB
/
cPickle.java
File metadata and controls
2292 lines (1984 loc) · 77.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c)2019 Jython Developers
/*
* Copyright 1998 Finn Bock.
*
* This program contains material copyrighted by:
* Copyright (c) 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
* The Netherlands.
*/
// Licensed to the PSF under a Contributor Agreement
/* note about impl:
instanceof vs. CPython type(.) is .
*/
package org.python.modules;
import java.math.BigInteger;
import java.util.Map;
import org.python.core.ClassDictInit;
import org.python.core.Py;
import org.python.core.PyBoolean;
import org.python.core.PyBuiltinCallable;
import org.python.core.PyClass;
import org.python.core.PyDictionary;
import org.python.core.PyException;
import org.python.core.PyFile;
import org.python.core.PyFloat;
import org.python.core.PyFunction;
import org.python.core.PyInstance;
import org.python.core.PyInteger;
import org.python.core.PyList;
import org.python.core.PyLong;
import org.python.core.PyModule;
import org.python.core.PyNone;
import org.python.core.PyObject;
import org.python.core.PyReflectedFunction;
import org.python.core.PySequence;
import org.python.core.PyString;
import org.python.core.PyStringMap;
import org.python.core.PyTuple;
import org.python.core.PyType;
import org.python.core.PyUnicode;
import org.python.core.__builtin__;
import org.python.core.codecs;
import org.python.core.exceptions;
import org.python.core.imp;
import org.python.util.Generic;
/**
*
* From the python documentation:
* <p>
* The <tt>cPickle.java</tt> module implements a basic but powerful algorithm
* for ``pickling'' (a.k.a. serializing, marshalling or flattening) nearly
* arbitrary Python objects. This is the act of converting objects to a
* stream of bytes (and back: ``unpickling'').
* This is a more primitive notion than
* persistency -- although <tt>cPickle.java</tt> reads and writes file
* objects, it does not handle the issue of naming persistent objects, nor
* the (even more complicated) area of concurrent access to persistent
* objects. The <tt>cPickle.java</tt> module can transform a complex object
* into a byte stream and it can transform the byte stream into an object
* with the same internal structure. The most obvious thing to do with these
* byte streams is to write them onto a file, but it is also conceivable
* to send them across a network or store them in a database. The module
* <tt>shelve</tt> provides a simple interface to pickle and unpickle
* objects on ``dbm''-style database files.
* <P>
* <b>Note:</b> The <tt>cPickle.java</tt> have the same interface as the
* standard module <tt>pickle</tt>except that <tt>Pickler</tt> and
* <tt>Unpickler</tt> are factory functions, not classes (so they cannot be
* used as base classes for inheritance).
* This limitation is similar for the original cPickle.c version.
*
* <P>
* Unlike the built-in module <tt>marshal</tt>, <tt>cPickle.java</tt> handles
* the following correctly:
* <P>
*
* <UL><LI>recursive objects (objects containing references to themselves)
*
* <P>
*
* <LI>object sharing (references to the same object in different places)
*
* <P>
*
* <LI>user-defined classes and their instances
*
* <P>
*
* </UL>
*
* <P>
* The data format used by <tt>cPickle.java</tt> is Python-specific. This has
* the advantage that there are no restrictions imposed by external
* standards such as XDR (which can't represent pointer sharing); however
* it means that non-Python programs may not be able to reconstruct
* pickled Python objects.
*
* <P>
* By default, the <tt>cPickle.java</tt> data format uses a printable ASCII
* representation. This is slightly more voluminous than a binary
* representation. The big advantage of using printable ASCII (and of
* some other characteristics of <tt>cPickle.java</tt>'s representation) is
* that for debugging or recovery purposes it is possible for a human to read
* the pickled file with a standard text editor.
*
* <P>
* A binary format, which is slightly more efficient, can be chosen by
* specifying a nonzero (true) value for the <i>bin</i> argument to the
* <tt>Pickler</tt> constructor or the <tt>dump()</tt> and <tt>dumps()</tt>
* functions. The binary format is not the default because of backwards
* compatibility with the Python 1.4 pickle module. In a future version,
* the default may change to binary.
*
* <P>
* The <tt>cPickle.java</tt> module doesn't handle code objects.
* <P>
* For the benefit of persistency modules written using <tt>cPickle.java</tt>,
* it supports the notion of a reference to an object outside the pickled
* data stream. Such objects are referenced by a name, which is an
* arbitrary string of printable ASCII characters. The resolution of
* such names is not defined by the <tt>cPickle.java</tt> module -- the
* persistent object module will have to implement a method
* <tt>persistent_load()</tt>. To write references to persistent objects,
* the persistent module must define a method <tt>persistent_id()</tt> which
* returns either <tt>None</tt> or the persistent ID of the object.
*
* <P>
* There are some restrictions on the pickling of class instances.
*
* <P>
* First of all, the class must be defined at the top level in a module.
* Furthermore, all its instance variables must be picklable.
*
* <P>
*
* <P>
* When a pickled class instance is unpickled, its <tt>__init__()</tt> method
* is normally <i>not</i> invoked. <b>Note:</b> This is a deviation
* from previous versions of this module; the change was introduced in
* Python 1.5b2. The reason for the change is that in many cases it is
* desirable to have a constructor that requires arguments; it is a
* (minor) nuisance to have to provide a <tt>__getinitargs__()</tt> method.
*
* <P>
* If it is desirable that the <tt>__init__()</tt> method be called on
* unpickling, a class can define a method <tt>__getinitargs__()</tt>,
* which should return a <i>tuple</i> containing the arguments to be
* passed to the class constructor (<tt>__init__()</tt>). This method is
* called at pickle time; the tuple it returns is incorporated in the
* pickle for the instance.
* <P>
* Classes can further influence how their instances are pickled -- if the
* class defines the method <tt>__getstate__()</tt>, it is called and the
* return state is pickled as the contents for the instance, and if the class
* defines the method <tt>__setstate__()</tt>, it is called with the
* unpickled state. (Note that these methods can also be used to
* implement copying class instances.) If there is no
* <tt>__getstate__()</tt> method, the instance's <tt>__dict__</tt> is
* pickled. If there is no <tt>__setstate__()</tt> method, the pickled
* object must be a dictionary and its items are assigned to the new
* instance's dictionary. (If a class defines both <tt>__getstate__()</tt>
* and <tt>__setstate__()</tt>, the state object needn't be a dictionary
* -- these methods can do what they want.) This protocol is also used
* by the shallow and deep copying operations defined in the <tt>copy</tt>
* module.
* <P>
* Note that when class instances are pickled, their class's code and
* data are not pickled along with them. Only the instance data are
* pickled. This is done on purpose, so you can fix bugs in a class or
* add methods and still load objects that were created with an earlier
* version of the class. If you plan to have long-lived objects that
* will see many versions of a class, it may be worthwhile to put a version
* number in the objects so that suitable conversions can be made by the
* class's <tt>__setstate__()</tt> method.
*
* <P>
* When a class itself is pickled, only its name is pickled -- the class
* definition is not pickled, but re-imported by the unpickling process.
* Therefore, the restriction that the class must be defined at the top
* level in a module applies to pickled classes as well.
*
* <P>
*
* <P>
* The interface can be summarized as follows.
*
* <P>
* To pickle an object <tt>x</tt> onto a file <tt>f</tt>, open for writing:
*
* <P>
* <dl><dd><pre>
* p = pickle.Pickler(f)
* p.dump(x)
* </pre></dl>
*
* <P>
* A shorthand for this is:
*
* <P>
* <dl><dd><pre>
* pickle.dump(x, f)
* </pre></dl>
*
* <P>
* To unpickle an object <tt>x</tt> from a file <tt>f</tt>, open for reading:
*
* <P>
* <dl><dd><pre>
* u = pickle.Unpickler(f)
* x = u.load()
* </pre></dl>
*
* <P>
* A shorthand is:
*
* <P>
* <dl><dd><pre>
* x = pickle.load(f)
* </pre></dl>
*
* <P>
* The <tt>Pickler</tt> class only calls the method <tt>f.write()</tt> with a
* string argument. The <tt>Unpickler</tt> calls the methods
* <tt>f.read()</tt> (with an integer argument) and <tt>f.readline()</tt>
* (without argument), both returning a string. It is explicitly allowed to
* pass non-file objects here, as long as they have the right methods.
*
* <P>
* The constructor for the <tt>Pickler</tt> class has an optional second
* argument, <i>bin</i>. If this is present and nonzero, the binary
* pickle format is used; if it is zero or absent, the (less efficient,
* but backwards compatible) text pickle format is used. The
* <tt>Unpickler</tt> class does not have an argument to distinguish
* between binary and text pickle formats; it accepts either format.
*
* <P>
* The following types can be pickled:
*
* <UL><LI><tt>None</tt>
*
* <P>
*
* <LI>integers, long integers, floating point numbers
*
* <P>
*
* <LI>strings
*
* <P>
*
* <LI>tuples, lists and dictionaries containing only picklable objects
*
* <P>
*
* <LI>classes that are defined at the top level in a module
*
* <P>
*
* <LI>instances of such classes whose <tt>__dict__</tt> or
* <tt>__setstate__()</tt> is picklable
*
* <P>
*
* </UL>
*
* <P>
* Attempts to pickle unpicklable objects will raise the
* <tt>PicklingError</tt> exception; when this happens, an unspecified
* number of bytes may have been written to the file.
*
* <P>
* It is possible to make multiple calls to the <tt>dump()</tt> method of
* the same <tt>Pickler</tt> instance. These must then be matched to the
* same number of calls to the <tt>load()</tt> method of the
* corresponding <tt>Unpickler</tt> instance. If the same object is
* pickled by multiple <tt>dump()</tt> calls, the <tt>load()</tt> will all
* yield references to the same object. <i>Warning</i>: this is intended
* for pickling multiple objects without intervening modifications to the
* objects or their parts. If you modify an object and then pickle it
* again using the same <tt>Pickler</tt> instance, the object is not
* pickled again -- a reference to it is pickled and the
* <tt>Unpickler</tt> will return the old value, not the modified one.
* (There are two problems here: (a) detecting changes, and (b)
* marshalling a minimal set of changes. I have no answers. Garbage
* Collection may also become a problem here.)
*
* <P>
* Apart from the <tt>Pickler</tt> and <tt>Unpickler</tt> classes, the
* module defines the following functions, and an exception:
* <dl>
* <dt><b><tt>dump</tt></b> (object, file[, bin])</dt>
* <dd>
* Write a pickled representation of <i>obect</i> to the open file object
* <i>file</i>. This is equivalent to
* "<tt>Pickler(<i>file</i>, <i>bin</i>).dump(<i>object</i>)</tt>".
* If the optional <i>bin</i> argument is present and nonzero, the binary
* pickle format is used; if it is zero or absent, the (less efficient)
* text pickle format is used.
* </dd>
*
* <dt><b><tt>load</tt></b> (file)</dt>
* <dd>
* Read a pickled object from the open file object <i>file</i>. This is
* equivalent to "<tt>Unpickler(<i>file</i>).load()</tt>".
* </dd>
*
* <dt><b><tt>dumps</tt></b> (object[, bin])</dt>
* <dd>
* Return the pickled representation of the object as a string, instead
* of writing it to a file. If the optional <i>bin</i> argument is
* present and nonzero, the binary pickle format is used; if it is zero
* or absent, the (less efficient) text pickle format is used.
* </dd>
*
* <dt><b><tt>loads</tt></b> (string)</dt>
* <dd>
* Read a pickled object from a string instead of a file. Characters in
* the string past the pickled object's representation are ignored.
* </dd>
*
* <dt><b><tt>PicklingError</tt></b></dt>
* <dd>
* This exception is raised when an unpicklable object is passed to
* <tt>Pickler.dump()</tt>.
* </dd>
* </dl>
*
* For the complete documentation on the pickle module, please see the
* "Python Library Reference"
* <p><hr><p>
*
* The module is based on both original pickle.py and the cPickle.c
* version, except that all mistakes and errors are my own.
* <p>
* @author Finn Bock, bckfnn@pipmail.dknet.dk
* @version cPickle.java,v 1.30 1999/05/15 17:40:12 fb Exp
*/
public class cPickle implements ClassDictInit {
/**
* The doc string
*/
public static String __doc__ =
"Java implementation and optimization of the Python pickle module\n";
/**
* The program version.
*/
public static String __version__ = "1.30";
/**
* File format version we write.
*/
public static final String format_version = "2.0";
/**
* Old format versions we can read.
*/
public static final String[] compatible_formats =
new String[] { "1.0", "1.1", "1.2", "1.3", "2.0" };
/**
* Highest protocol version supported.
*/
public static final int HIGHEST_PROTOCOL = 2;
public static String[] __depends__ = new String[] {
"copy_reg",
};
public static PyObject PickleError;
public static PyObject PicklingError;
public static PyObject UnpickleableError;
public static PyObject UnpicklingError;
public static PyObject BadPickleGet;
final static char MARK = '(';
final static char STOP = '.';
final static char POP = '0';
final static char POP_MARK = '1';
final static char DUP = '2';
final static char FLOAT = 'F';
final static char INT = 'I';
final static char BININT = 'J';
final static char BININT1 = 'K';
final static char LONG = 'L';
final static char BININT2 = 'M';
final static char NONE = 'N';
final static char PERSID = 'P';
final static char BINPERSID = 'Q';
final static char REDUCE = 'R';
final static char STRING = 'S';
final static char BINSTRING = 'T';
final static char SHORT_BINSTRING = 'U';
final static char UNICODE = 'V';
final static char BINUNICODE = 'X';
final static char APPEND = 'a';
final static char BUILD = 'b';
final static char GLOBAL = 'c';
final static char DICT = 'd';
final static char EMPTY_DICT = '}';
final static char APPENDS = 'e';
final static char GET = 'g';
final static char BINGET = 'h';
final static char INST = 'i';
final static char LONG_BINGET = 'j';
final static char LIST = 'l';
final static char EMPTY_LIST = ']';
final static char OBJ = 'o';
final static char PUT = 'p';
final static char BINPUT = 'q';
final static char LONG_BINPUT = 'r';
final static char SETITEM = 's';
final static char TUPLE = 't';
final static char EMPTY_TUPLE = ')';
final static char SETITEMS = 'u';
final static char BINFLOAT = 'G';
final static char PROTO = 0x80;
final static char NEWOBJ = 0x81;
final static char EXT1 = 0x82;
final static char EXT2 = 0x83;
final static char EXT4 = 0x84;
final static char TUPLE1 = 0x85;
final static char TUPLE2 = 0x86;
final static char TUPLE3 = 0x87;
final static char NEWTRUE = 0x88;
final static char NEWFALSE = 0x89;
final static char LONG1 = 0x8A;
final static char LONG4 = 0x8B;
private static PyDictionary dispatch_table;
private static PyDictionary extension_registry;
private static PyDictionary inverted_registry;
private static PyType BuiltinCallableType = PyType.fromClass(PyBuiltinCallable.class);
private static PyType ReflectedFunctionType = PyType.fromClass(PyReflectedFunction.class);
private static PyType ClassType = PyType.fromClass(PyClass.class);
private static PyType TypeType = PyType.fromClass(PyType.class);
private static PyType DictionaryType = PyType.fromClass(PyDictionary.class);
private static PyType StringMapType = PyType.fromClass(PyStringMap.class);
private static PyType FloatType = PyType.fromClass(PyFloat.class);
private static PyType FunctionType = PyType.fromClass(PyFunction.class);
private static PyType InstanceType = PyType.fromClass(PyInstance.class);
private static PyType IntType = PyType.fromClass(PyInteger.class);
private static PyType ListType = PyType.fromClass(PyList.class);
private static PyType LongType = PyType.fromClass(PyLong.class);
private static PyType NoneType = PyType.fromClass(PyNone.class);
private static PyType StringType = PyType.fromClass(PyString.class);
private static PyType UnicodeType = PyType.fromClass(PyUnicode.class);
private static PyType TupleType = PyType.fromClass(PyTuple.class);
private static PyType FileType = PyType.fromClass(PyFile.class);
private static PyType BoolType = PyType.fromClass(PyBoolean.class);
private static PyObject dict;
private static final int BATCHSIZE = 1024;
/**
* Initialization when module is imported.
*/
public static void classDictInit(PyObject dict) {
cPickle.dict = dict;
// XXX: Hack for JPython 1.0.1. By default __builtin__ is not in
// sys.modules.
imp.importName("__builtin__", true);
PyModule copyreg = (PyModule)importModule("copy_reg");
dispatch_table = (PyDictionary)copyreg.__getattr__("dispatch_table");
extension_registry = (PyDictionary)copyreg.__getattr__("_extension_registry");
inverted_registry = (PyDictionary)copyreg.__getattr__("_inverted_registry");
PickleError = Py.makeClass("PickleError", Py.Exception, _PickleError());
PicklingError = Py.makeClass("PicklingError", PickleError, exceptionNamespace());
UnpickleableError = Py.makeClass("UnpickleableError", PicklingError, _UnpickleableError());
UnpicklingError = Py.makeClass("UnpicklingError", PickleError, exceptionNamespace());
BadPickleGet = Py.makeClass("BadPickleGet", UnpicklingError, exceptionNamespace());
}
public static PyObject exceptionNamespace() {
PyObject dict = new PyStringMap();
dict.__setitem__("__module__", new PyString("cPickle"));
return dict;
}
public static PyObject _PickleError() {
dict = exceptionNamespace();
dict.__setitem__("__str__", getJavaFunc("__str__", "_PickleError__str__"));
return dict;
}
public static PyString _PickleError__str__(PyObject self, PyObject[] args, String[] kwargs) {
PyObject selfArgs = self.__getattr__("args");
if (selfArgs.__len__() > 0 && selfArgs.__getitem__(0).__len__() > 0) {
return selfArgs.__getitem__(0).__str__();
} else {
return new PyString("(what)");
}
}
public static PyObject _UnpickleableError() {
dict = exceptionNamespace();
dict.__setitem__("__str__", getJavaFunc("__str__", "_UnpickleableError__str__"));
return dict;
}
public static PyString _UnpickleableError__str__(PyObject self, PyObject[] args,
String[] kwargs) {
PyObject selfArgs = self.__getattr__("args");
PyObject a = selfArgs.__len__() > 0 ? selfArgs.__getitem__(0) : new PyString("(what)");
return new PyString("Cannot pickle %s objects").__mod__(a).__str__();
}
/**
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method. The data will be written as text.
* @return a new Pickler instance.
*/
public static Pickler Pickler(PyObject file) {
return new Pickler(file, 0);
}
/**
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method.
* @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3)
* @return a new Pickler instance.
*/
public static Pickler Pickler(PyObject file, int protocol) {
return new Pickler(file, protocol);
}
/**
* Returns a unpickler instance.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>read</i> and <i>readline</i> method.
* @return a new Unpickler instance.
*/
public static Unpickler Unpickler(PyObject file) {
return new Unpickler(file);
}
/**
* Shorthand function which pickles the object on the file.
* @param object a data object which should be pickled.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method. The data will be written as
* text.
*/
public static void dump(PyObject object, PyObject file) {
dump(object, file, 0);
}
/**
* Shorthand function which pickles the object on the file.
* @param object a data object which should be pickled.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>write</i> method.
* @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3)
*/
public static void dump(PyObject object, PyObject file, int protocol) {
new Pickler(file, protocol).dump(object);
}
/**
* Shorthand function which pickles and returns the string representation.
* @param object a data object which should be pickled.
* @return a string representing the pickled object.
*/
public static PyString dumps(PyObject object) {
return dumps(object, 0);
}
/**
* Shorthand function which pickles and returns the string representation.
* @param object a data object which should be pickled.
* @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3)
* @return a string representing the pickled object.
*/
public static PyString dumps(PyObject object, int protocol) {
cStringIO.StringIO file = cStringIO.StringIO();
dump(object, file, protocol);
return file.getvalue();
}
/**
* Shorthand function which unpickles a object from the file and returns
* the new object.
* @param file a file-like object, can be a cStringIO.StringIO,
* a PyFile or any python object which implements a
* <i>read</i> and <i>readline</i> method.
* @return a new object.
*/
public static Object load(PyObject file) {
try {
return new Unpickler(file).load();
}
catch (ArrayIndexOutOfBoundsException e) {
// invalid data, bad stack
throw Py.IndexError(e.getMessage());
} catch (StringIndexOutOfBoundsException e) {
// short data
throw Py.EOFError(e.getMessage());
}
}
/**
* Shorthand function which unpickles a object from the string and
* returns the new object.
* @param str a strings which must contain a pickled object
* representation.
* @return a new object.
*/
public static Object loads(PyObject str) {
cStringIO.StringIO file = cStringIO.StringIO(str.toString());
return load(file);
}
// Factory for creating PyIOFile representation.
/**
* The Pickler object
* @see cPickle#Pickler(PyObject)
* @see cPickle#Pickler(PyObject,int)
*/
static public class Pickler {
private PyIOFile file;
private int protocol;
/**
* The undocumented attribute fast of the C version of cPickle disables
* memoization. Since having memoization on won't break anything, having
* this dummy setter for fast here won't break any code expecting it to
* do something. However without it code that sets fast fails(ie
* test_cpickle.py), so it's worth having.
*/
public boolean fast = false;
private PickleMemo memo = new PickleMemo();
/**
* To write references to persistent objects, the persistent module
* must assign a method to persistent_id which returns either None
* or the persistent ID of the object.
* For the benefit of persistency modules written using pickle,
* it supports the notion of a reference to an object outside
* the pickled data stream.
* Such objects are referenced by a name, which is an arbitrary
* string of printable ASCII characters.
*/
public PyObject persistent_id = null;
/**
* Hmm, not documented, perhaps it shouldn't be public? XXX: fixme.
*/
public PyObject inst_persistent_id = null;
public Pickler(PyObject file, int protocol) {
this.file = PyIOFileFactory.createIOFile(file);
this.protocol = protocol;
}
/**
* Write a pickled representation of the object.
* @param object The object which will be pickled.
*/
public void dump(PyObject object) {
if (protocol >= 2) {
file.write(PROTO);
file.write((char) protocol);
}
save(object);
file.write(STOP);
file.flush();
}
private static final int get_id(PyObject o) {
// we don't pickle Java instances so we don't have to consider that case
return System.identityHashCode(o);
}
// Save name as in pickle.py but semantics are slightly changed.
private void put(int i) {
if (protocol > 0) {
if (i < 256) {
file.write(BINPUT);
file.write((char)i);
return;
}
file.write(LONG_BINPUT);
file.write((char)( i & 0xFF));
file.write((char)((i >>> 8) & 0xFF));
file.write((char)((i >>> 16) & 0xFF));
file.write((char)((i >>> 24) & 0xFF));
return;
}
file.write(PUT);
file.write(String.valueOf(i));
file.write("\n");
}
// Same name as in pickle.py but semantics are slightly changed.
private void get(int i) {
if (protocol > 0) {
if (i < 256) {
file.write(BINGET);
file.write((char)i);
return;
}
file.write(LONG_BINGET);
file.write((char)( i & 0xFF));
file.write((char)((i >>> 8) & 0xFF));
file.write((char)((i >>> 16) & 0xFF));
file.write((char)((i >>> 24) & 0xFF));
return;
}
file.write(GET);
file.write(String.valueOf(i));
file.write("\n");
}
private void save(PyObject object) {
save(object, false);
}
private void save(PyObject object, boolean pers_save) {
if (!pers_save && persistent_id != null && save_pers(object, persistent_id)) {
return;
}
int d = get_id(object);
PyType t = object.getType();
if (t == TupleType && object.__len__() == 0) {
if (protocol > 0) {
save_empty_tuple(object);
} else {
save_tuple(object);
}
return;
}
int m = getMemoPosition(d, object);
if (m >= 0) {
get(m);
return;
}
if (save_type(object, t)) {
return;
}
if (!pers_save && inst_persistent_id != null && save_pers(object, inst_persistent_id)) {
return;
}
if (Py.isSubClass(t, PyType.TYPE)) {
save_global(object);
return;
}
PyObject tup = null;
PyObject reduce = dispatch_table.__finditem__(t);
if (reduce == null) {
reduce = object.__findattr__("__reduce_ex__");
if (reduce != null) {
tup = reduce.__call__(Py.newInteger(protocol));
} else {
reduce = object.__findattr__("__reduce__");
if (reduce == null) {
throw new PyException(UnpickleableError, object);
}
tup = reduce.__call__();
}
} else {
tup = reduce.__call__(object);
}
if (tup instanceof PyString) {
save_global(object, tup);
return;
}
if (!(tup instanceof PyTuple)) {
throw new PyException(PicklingError,
"Value returned by " + reduce.__repr__() +
" must be a tuple");
}
int l = tup.__len__();
if (l < 2 || l > 5) {
throw new PyException(PicklingError,
"tuple returned by " + reduce.__repr__() +
" must contain two to five elements");
}
PyObject callable = tup.__finditem__(0);
PyObject arg_tup = tup.__finditem__(1);
PyObject state = (l > 2) ? tup.__finditem__(2) : Py.None;
PyObject listitems = (l > 3) ? tup.__finditem__(3) : Py.None;
PyObject dictitems = (l > 4) ? tup.__finditem__(4) : Py.None;
if (!(arg_tup instanceof PyTuple) && arg_tup != Py.None) {
throw new PyException(PicklingError,
"Second element of tupe returned by " +
reduce.__repr__() + " must be a tuple");
}
save_reduce(callable, arg_tup, state, listitems, dictitems, object);
}
final private boolean save_pers(PyObject object, PyObject pers_func) {
PyObject pid = pers_func.__call__(object);
if (pid == Py.None) {
return false;
}
if (protocol == 0) {
if (!Py.isInstance(pid, PyString.TYPE)) {
throw new PyException(PicklingError, "persistent id must be string");
}
file.write(PERSID);
file.write(pid.toString());
file.write("\n");
} else {
save(pid, true);
file.write(BINPERSID);
}
return true;
}
final private void save_reduce(PyObject callable, PyObject arg_tup,
PyObject state, PyObject listitems, PyObject dictitems,
PyObject object)
{
PyObject callableName = callable.__findattr__("__name__");
if(protocol >= 2 && callableName != null
&& "__newobj__".equals(callableName.toString())) {
PyObject cls = arg_tup.__finditem__(0);
if(cls.__findattr__("__new__") == null) {
throw new PyException(PicklingError,
"args[0] from __newobj__ args has no __new__");
}
// TODO: check class
save(cls);
save(arg_tup.__getslice__(Py.One, Py.None));
file.write(NEWOBJ);
} else {
save(callable);
save(arg_tup);
file.write(REDUCE);
}
// Memoize
put(putMemo(get_id(object), object));
if (listitems != Py.None) {
batch_appends(listitems);
}
if (dictitems != Py.None) {
batch_setitems(dictitems);
}
if (state != Py.None) {
save(state);
file.write(BUILD);
}
}
final private boolean save_type(PyObject object, PyType type) {
//System.out.println("save_type " + object + " " + cls);
if (type == NoneType) {
save_none(object);
} else if (type == StringType) {
save_string(object);
} else if (type == UnicodeType) {
save_unicode(object);
} else if (type == IntType) {
save_int(object);
} else if (type == LongType) {
save_long(object);
} else if (type == FloatType) {
save_float(object);
} else if (type == TupleType) {
save_tuple(object);
} else if (type == ListType) {
save_list(object);
} else if (type == DictionaryType || type == StringMapType) {
save_dict(object);
} else if (type == InstanceType) {
save_inst((PyInstance)object);
} else if (type == ClassType) {
save_global(object);
} else if (type == TypeType) {
save_global(object);
} else if (type == FunctionType) {
save_global(object);
} else if (type == BuiltinCallableType) {
save_global(object);
} else if (type == ReflectedFunctionType) {
save_global(object);
} else if (type == BoolType) {
save_bool(object);
} else {
return false;
}
return true;
}
final private void save_none(PyObject object) {
file.write(NONE);
}
final private void save_int(PyObject object) {
if (protocol > 0) {
int l = ((PyInteger)object).getValue();
char i1 = (char)( l & 0xFF);
char i2 = (char)((l >>> 8 ) & 0xFF);
char i3 = (char)((l >>> 16) & 0xFF);
char i4 = (char)((l >>> 24) & 0xFF);
if (i3 == '\0' && i4 == '\0') {
if (i2 == '\0') {
file.write(BININT1);
file.write(i1);
return;
}
file.write(BININT2);
file.write(i1);
file.write(i2);
return;
}
file.write(BININT);
file.write(i1);
file.write(i2);
file.write(i3);
file.write(i4);
} else {
file.write(INT);
file.write(object.toString());
file.write("\n");
}
}
private void save_bool(PyObject object) {
int value = ((PyBoolean)object).getValue();
if(protocol >= 2) {
file.write(value != 0 ? NEWTRUE : NEWFALSE);
} else {
file.write(INT);
file.write(value != 0 ? "01" : "00");
file.write("\n");
}
}