home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / cPickle.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  106.8 KB  |  4,564 lines

  1. /*
  2.  * cPickle.c,v 1.71 1999/07/11 13:30:34 jim Exp
  3.  * 
  4.  * Copyright (c) 1996-1998, Digital Creations, Fredericksburg, VA, USA.  
  5.  * All rights reserved.
  6.  * 
  7.  * Redistribution and use in source and binary forms, with or without
  8.  * modification, are permitted provided that the following conditions are
  9.  * met:
  10.  * 
  11.  *   o Redistributions of source code must retain the above copyright
  12.  *     notice, this list of conditions, and the disclaimer that follows.
  13.  * 
  14.  *   o Redistributions in binary form must reproduce the above copyright
  15.  *     notice, this list of conditions, and the following disclaimer in
  16.  *     the documentation and/or other materials provided with the
  17.  *     distribution.
  18.  * 
  19.  *   o Neither the name of Digital Creations nor the names of its
  20.  *     contributors may be used to endorse or promote products derived
  21.  *     from this software without specific prior written permission.
  22.  * 
  23.  * 
  24.  * THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS AND CONTRIBUTORS *AS
  25.  * IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  26.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  27.  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL
  28.  * CREATIONS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  30.  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  31.  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  32.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  33.  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  34.  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  35.  * DAMAGE.
  36.  * 
  37.  # 
  38.  # If you have questions regarding this software, contact:
  39.  #
  40.  #   Digital Creations, L.C.
  41.  #   910 Princess Ann Street
  42.  #   Fredericksburge, Virginia  22401
  43.  #
  44.  #   info@digicool.com
  45.  #
  46.  #   (540) 371-6909
  47.  */
  48.  
  49. static char cPickle_module_documentation[] = 
  50. "C implementation and optimization of the Python pickle module\n"
  51. "\n"
  52. "cPickle.c,v 1.71 1999/07/11 13:30:34 jim Exp\n"
  53. ;
  54.  
  55. #include "Python.h"
  56. #include "cStringIO.h"
  57.  
  58. #ifndef Py_eval_input
  59. #include <graminit.h>
  60. #define Py_eval_input eval_input
  61. #endif /* Py_eval_input */
  62.  
  63. #include <errno.h>
  64.  
  65. #define UNLESS(E) if (!(E))
  66.  
  67. #define DEL_LIST_SLICE(list, from, to) (PyList_SetSlice(list, from, to, NULL))
  68.  
  69. #define WRITE_BUF_SIZE 256
  70.  
  71.  
  72. #define MARK        '('
  73. #define STOP        '.'
  74. #define POP         '0'
  75. #define POP_MARK    '1'
  76. #define DUP         '2'
  77. #define FLOAT       'F'
  78. #define BINFLOAT    'G'
  79. #define INT         'I'
  80. #define BININT      'J'
  81. #define BININT1     'K'
  82. #define LONG        'L'
  83. #define BININT2     'M'
  84. #define NONE        'N'
  85. #define PERSID      'P'
  86. #define BINPERSID   'Q'
  87. #define REDUCE      'R'
  88. #define STRING      'S'
  89. #define BINSTRING   'T'
  90. #define SHORT_BINSTRING 'U'
  91. #define UNICODE     'V'
  92. #define BINUNICODE  'X'
  93. #define APPEND      'a'
  94. #define BUILD       'b'
  95. #define GLOBAL      'c'
  96. #define DICT        'd'
  97. #define EMPTY_DICT  '}'
  98. #define APPENDS     'e'
  99. #define GET         'g'
  100. #define BINGET      'h'
  101. #define INST        'i'
  102. #define LONG_BINGET 'j'
  103. #define LIST        'l'
  104. #define EMPTY_LIST  ']'
  105. #define OBJ         'o'
  106. #define PUT         'p'
  107. #define BINPUT      'q'
  108. #define LONG_BINPUT 'r'
  109. #define SETITEM     's'
  110. #define TUPLE       't'
  111. #define EMPTY_TUPLE ')'
  112. #define SETITEMS    'u'
  113.  
  114. static char MARKv = MARK;
  115.  
  116. /* atol function from string module */
  117. static PyObject *atol_func;
  118.  
  119. static PyObject *PickleError;
  120. static PyObject *PicklingError;
  121. static PyObject *UnpickleableError;
  122. static PyObject *UnpicklingError;
  123. static PyObject *BadPickleGet;
  124.  
  125.  
  126. static PyObject *dispatch_table;
  127. static PyObject *safe_constructors;
  128. static PyObject *empty_tuple;
  129.  
  130. static PyObject *__class___str, *__getinitargs___str, *__dict___str,
  131.   *__getstate___str, *__setstate___str, *__name___str, *__reduce___str,
  132.   *write_str, *__safe_for_unpickling___str, *append_str,
  133.   *read_str, *readline_str, *__main___str, *__basicnew___str,
  134.   *copy_reg_str, *dispatch_table_str, *safe_constructors_str, *empty_str;
  135.  
  136. #ifndef PyList_SET_ITEM
  137. #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v))
  138. #endif
  139. #ifndef PyList_GET_SIZE
  140. #define PyList_GET_SIZE(op)    (((PyListObject *)(op))->ob_size)
  141. #endif
  142. #ifndef PyTuple_SET_ITEM
  143. #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = (v))
  144. #endif
  145. #ifndef PyTuple_GET_SIZE
  146. #define PyTuple_GET_SIZE(op)    (((PyTupleObject *)(op))->ob_size)
  147. #endif
  148. #ifndef PyString_GET_SIZE
  149. #define PyString_GET_SIZE(op)    (((PyStringObject *)(op))->ob_size)
  150. #endif
  151.  
  152. /*************************************************************************
  153.  Internal Data type for pickle data.                                     */
  154.  
  155. typedef struct {
  156.      PyObject_HEAD
  157.      int length, size;
  158.      PyObject **data;
  159. } Pdata;
  160.  
  161. static void 
  162. Pdata_dealloc(Pdata *self) {
  163.     int i;
  164.     PyObject **p;
  165.  
  166.     for (i=self->length, p=self->data; --i >= 0; p++) Py_DECREF(*p);
  167.  
  168.     if (self->data) free(self->data);
  169.  
  170.     PyObject_Del(self);
  171. }
  172.  
  173. static PyTypeObject PdataType = {
  174.     PyObject_HEAD_INIT(NULL) 0, "Pdata", sizeof(Pdata), 0,
  175.     (destructor)Pdata_dealloc,
  176.     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
  177. };
  178.  
  179. #define Pdata_Check(O) ((O)->ob_type == &PdataType)
  180.  
  181. static PyObject *
  182. Pdata_New(void) {
  183.     Pdata *self;
  184.  
  185.     UNLESS (self = PyObject_New(Pdata, &PdataType)) return NULL;
  186.     self->size=8;
  187.     self->length=0;
  188.     self->data=malloc(self->size * sizeof(PyObject*));
  189.     if (self->data) return (PyObject*)self;
  190.     Py_DECREF(self);
  191.     return PyErr_NoMemory();
  192. }
  193.  
  194. static int 
  195. stackUnderflow(void) {
  196.     PyErr_SetString(UnpicklingError, "unpickling stack underflow");
  197.     return -1;
  198. }
  199.  
  200. static int
  201. Pdata_clear(Pdata *self, int clearto) {
  202.     int i;
  203.     PyObject **p;
  204.  
  205.     if (clearto < 0) return stackUnderflow();
  206.     if (clearto >= self->length) return 0;
  207.  
  208.     for (i=self->length, p=self->data+clearto; --i >= clearto; p++)
  209.       Py_DECREF(*p);
  210.     self->length=clearto;
  211.  
  212.     return 0;
  213. }
  214.  
  215.  
  216. static int 
  217. Pdata_grow(Pdata *self) {
  218.   if (! self->size) {
  219.       PyErr_NoMemory();
  220.       return -1;
  221.   }
  222.   self->size *= 2;                          
  223.   self->data = realloc(self->data, self->size*sizeof(PyObject*));
  224.   if (! self->data) {
  225.     self->size = 0;                       
  226.     PyErr_NoMemory();                              
  227.     return -1;                                     
  228.   }
  229.   return 0;
  230. }                                                      
  231.  
  232. #define PDATA_POP(D,V) {                                      \
  233.     if ((D)->length) V=D->data[--((D)->length)];              \
  234.     else {                                                    \
  235.         PyErr_SetString(UnpicklingError, "bad pickle data");  \
  236.         V=NULL;                                               \
  237.     }                                                         \
  238. }
  239.  
  240.  
  241. static PyObject *
  242. Pdata_popTuple(Pdata *self, int start) {
  243.     PyObject *r;
  244.     int i, j, l;
  245.  
  246.     l=self->length-start;
  247.     UNLESS (r=PyTuple_New(l)) return NULL;
  248.     for (i=start, j=0 ; j < l; i++, j++)
  249.         PyTuple_SET_ITEM(r, j, self->data[i]);
  250.  
  251.     self->length=start;
  252.     return r;
  253. }
  254.  
  255. static PyObject *
  256. Pdata_popList(Pdata *self, int start) {
  257.     PyObject *r;
  258.     int i, j, l;
  259.  
  260.     l=self->length-start;
  261.     UNLESS (r=PyList_New(l)) return NULL;
  262.     for (i=start, j=0 ; j < l; i++, j++)
  263.         PyList_SET_ITEM(r, j, self->data[i]);
  264.  
  265.     self->length=start;
  266.     return r;
  267. }
  268.  
  269. #define PDATA_APPEND_(D,O,ER) { \
  270.   if (Pdata_Append(((Pdata*)(D)), O) < 0) return ER; \
  271. }
  272.  
  273. #define PDATA_APPEND(D,O,ER) {                                 \
  274.     if (((Pdata*)(D))->length == ((Pdata*)(D))->size &&        \
  275.         Pdata_grow((Pdata*)(D)) < 0)                           \
  276.         return ER;                                             \
  277.     Py_INCREF(O);                                              \
  278.     ((Pdata*)(D))->data[((Pdata*)(D))->length++]=O;            \
  279. }
  280.  
  281. #define PDATA_PUSH(D,O,ER) {                                   \
  282.     if (((Pdata*)(D))->length == ((Pdata*)(D))->size &&        \
  283.         Pdata_grow((Pdata*)(D)) < 0) {                         \
  284.         Py_DECREF(O);                                          \
  285.         return ER;                                             \
  286.     }                                                          \
  287.     ((Pdata*)(D))->data[((Pdata*)(D))->length++]=O;            \
  288. }
  289.  
  290. /*************************************************************************/
  291.  
  292. #define ARG_TUP(self, o) {                          \
  293.   if (self->arg || (self->arg=PyTuple_New(1))) {    \
  294.       Py_XDECREF(PyTuple_GET_ITEM(self->arg,0));    \
  295.       PyTuple_SET_ITEM(self->arg,0,o);              \
  296.   }                                                 \
  297.   else {                                            \
  298.       Py_DECREF(o);                                 \
  299.   }                                                 \
  300. }
  301.  
  302. #define FREE_ARG_TUP(self) {                        \
  303.     if (self->arg->ob_refcnt > 1) {                 \
  304.       Py_DECREF(self->arg);                         \
  305.       self->arg=NULL;                               \
  306.     }                                               \
  307.   }
  308.  
  309. typedef struct Picklerobject {
  310.      PyObject_HEAD
  311.      FILE *fp;
  312.      PyObject *write;
  313.      PyObject *file;
  314.      PyObject *memo;
  315.      PyObject *arg;
  316.      PyObject *pers_func;
  317.      PyObject *inst_pers_func;
  318.      int bin;
  319.      int fast; /* Fast mode doesn't save in memo, don't use if circ ref */
  320.      int (*write_func)(struct Picklerobject *, char *, int);
  321.      char *write_buf;
  322.      int buf_size;
  323.      PyObject *dispatch_table;
  324. } Picklerobject;
  325.  
  326. staticforward PyTypeObject Picklertype;
  327.  
  328. typedef struct Unpicklerobject {
  329.      PyObject_HEAD
  330.      FILE *fp;
  331.      PyObject *file;
  332.      PyObject *readline;
  333.      PyObject *read;
  334.      PyObject *memo;
  335.      PyObject *arg;
  336.      Pdata *stack;
  337.      PyObject *mark;
  338.      PyObject *pers_func;
  339.      PyObject *last_string;
  340.      int *marks;
  341.      int num_marks;
  342.      int marks_size;
  343.      int (*read_func)(struct Unpicklerobject *, char **, int);
  344.      int (*readline_func)(struct Unpicklerobject *, char **);
  345.      int buf_size;
  346.      char *buf;
  347.      PyObject *safe_constructors;
  348.      PyObject *find_class;
  349. } Unpicklerobject;
  350.  
  351. staticforward PyTypeObject Unpicklertype;
  352.  
  353. /* Forward decls that need the above structs */
  354. static int save(Picklerobject *, PyObject *, int);
  355. static int put2(Picklerobject *, PyObject *);
  356.  
  357. int 
  358. cPickle_PyMapping_HasKey(PyObject *o, PyObject *key) {
  359.     PyObject *v;
  360.  
  361.     if ((v = PyObject_GetItem(o,key))) {
  362.         Py_DECREF(v);
  363.         return 1;
  364.     }
  365.  
  366.     PyErr_Clear();
  367.     return 0;
  368. }
  369.  
  370. static
  371. PyObject *
  372. cPickle_ErrFormat(PyObject *ErrType, char *stringformat, char *format, ...)
  373. {
  374.   va_list va;
  375.   PyObject *args=0, *retval=0;
  376.   va_start(va, format);
  377.   
  378.   if (format) args = Py_VaBuildValue(format, va);
  379.   va_end(va);
  380.   if (format && ! args) return NULL;
  381.   if (stringformat && !(retval=PyString_FromString(stringformat))) return NULL;
  382.  
  383.   if (retval) {
  384.       if (args) {
  385.           PyObject *v;
  386.           v=PyString_Format(retval, args);
  387.           Py_DECREF(retval);
  388.           Py_DECREF(args);
  389.           if (! v) return NULL;
  390.           retval=v;
  391.         }
  392.     }
  393.   else
  394.     if (args) retval=args;
  395.     else {
  396.         PyErr_SetObject(ErrType,Py_None);
  397.         return NULL;
  398.       }
  399.   PyErr_SetObject(ErrType,retval);
  400.   Py_DECREF(retval);
  401.   return NULL;
  402. }
  403.  
  404. static int 
  405. write_file(Picklerobject *self, char *s, int  n) {
  406.     if (s == NULL) {
  407.         return 0;
  408.     }
  409.  
  410.     if (fwrite(s, sizeof(char), n, self->fp) != (size_t)n) {
  411.         PyErr_SetFromErrno(PyExc_IOError);
  412.         return -1;
  413.     }
  414.  
  415.     return n;
  416. }
  417.  
  418. static int 
  419. write_cStringIO(Picklerobject *self, char *s, int  n) {
  420.     if (s == NULL) {
  421.         return 0;
  422.     }
  423.  
  424.     if (PycStringIO->cwrite((PyObject *)self->file, s, n) != n) {
  425.         return -1;
  426.     }
  427.  
  428.     return n;
  429. }
  430.  
  431. static int 
  432. write_none(Picklerobject *self, char *s, int  n) {
  433.     if (s == NULL) return 0;
  434.     return n;
  435. }
  436.  
  437. static int 
  438. write_other(Picklerobject *self, char *s, int  n) {
  439.     PyObject *py_str = 0, *junk = 0;
  440.  
  441.     if (s == NULL) {
  442.         UNLESS (self->buf_size) return 0;
  443.         UNLESS (py_str = 
  444.             PyString_FromStringAndSize(self->write_buf, self->buf_size))
  445.             return -1;
  446.     }
  447.     else {
  448.         if (self->buf_size && (n + self->buf_size) > WRITE_BUF_SIZE) {
  449.             if (write_other(self, NULL, 0) < 0)
  450.                 return -1;
  451.         }
  452.  
  453.         if (n > WRITE_BUF_SIZE) {    
  454.             UNLESS (py_str = 
  455.                 PyString_FromStringAndSize(s, n))
  456.                 return -1;
  457.         }
  458.         else {
  459.             memcpy(self->write_buf + self->buf_size, s, n);
  460.             self->buf_size += n;
  461.             return n;
  462.         }
  463.     }
  464.  
  465.     if (self->write) {
  466.         /* object with write method */
  467.         ARG_TUP(self, py_str);
  468.         if (self->arg) {
  469.             junk = PyObject_CallObject(self->write, self->arg);
  470.             FREE_ARG_TUP(self);
  471.         }
  472.         if (junk) Py_DECREF(junk);
  473.         else return -1;
  474.       }
  475.     else 
  476.       PDATA_PUSH(self->file, py_str, -1);
  477.     
  478.     self->buf_size = 0; 
  479.     return n;
  480. }
  481.  
  482.  
  483. static int 
  484. read_file(Unpicklerobject *self, char **s, int  n) {
  485.  
  486.     if (self->buf_size == 0) {
  487.         int size;
  488.  
  489.         size = ((n < 32) ? 32 : n); 
  490.         UNLESS (self->buf = (char *)malloc(size * sizeof(char))) {
  491.             PyErr_NoMemory();
  492.             return -1;
  493.         }
  494.  
  495.         self->buf_size = size;
  496.     }
  497.     else if (n > self->buf_size) {
  498.         UNLESS (self->buf = (char *)realloc(self->buf, n * sizeof(char))) {
  499.             PyErr_NoMemory();
  500.             return -1;
  501.         }
  502.  
  503.         self->buf_size = n;
  504.     }
  505.             
  506.     if (fread(self->buf, sizeof(char), n, self->fp) != (size_t)n) {
  507.         if (feof(self->fp)) {
  508.             PyErr_SetNone(PyExc_EOFError);
  509.             return -1;
  510.         }
  511.  
  512.         PyErr_SetFromErrno(PyExc_IOError);
  513.         return -1;
  514.     }
  515.  
  516.     *s = self->buf;
  517.  
  518.     return n;
  519. }
  520.  
  521.  
  522. static int 
  523. readline_file(Unpicklerobject *self, char **s) {
  524.     int i;
  525.  
  526.     if (self->buf_size == 0) {
  527.         UNLESS (self->buf = (char *)malloc(40 * sizeof(char))) {
  528.             PyErr_NoMemory();
  529.             return -1;
  530.         }
  531.    
  532.         self->buf_size = 40;
  533.     }
  534.  
  535.     i = 0;
  536.     while (1) {
  537.         for (; i < (self->buf_size - 1); i++) {
  538.             if (feof(self->fp) || (self->buf[i] = getc(self->fp)) == '\n') {
  539.                 self->buf[i + 1] = '\0';
  540.                 *s = self->buf;
  541.                 return i + 1;
  542.             }
  543.         }
  544.  
  545.         UNLESS (self->buf = (char *)realloc(self->buf, 
  546.             (self->buf_size * 2) * sizeof(char))) {
  547.             PyErr_NoMemory();
  548.             return -1;
  549.         }
  550.  
  551.         self->buf_size *= 2;
  552.     }
  553.  
  554. }    
  555.  
  556.  
  557. static int 
  558. read_cStringIO(Unpicklerobject *self, char **s, int  n) {
  559.     char *ptr;
  560.  
  561.     if (PycStringIO->cread((PyObject *)self->file, &ptr, n) != n) {
  562.         PyErr_SetNone(PyExc_EOFError);
  563.         return -1;
  564.     }
  565.  
  566.     *s = ptr;
  567.  
  568.     return n;
  569. }
  570.  
  571.  
  572. static int 
  573. readline_cStringIO(Unpicklerobject *self, char **s) {
  574.     int n;
  575.     char *ptr;
  576.  
  577.     if ((n = PycStringIO->creadline((PyObject *)self->file, &ptr)) < 0) {
  578.         return -1;
  579.     }
  580.  
  581.     *s = ptr;
  582.  
  583.     return n;
  584. }
  585.  
  586.  
  587. static int 
  588. read_other(Unpicklerobject *self, char **s, int  n) {
  589.     PyObject *bytes, *str=0;
  590.  
  591.     UNLESS (bytes = PyInt_FromLong(n)) return -1;
  592.  
  593.     ARG_TUP(self, bytes);
  594.     if (self->arg) {
  595.         str = PyObject_CallObject(self->read, self->arg);
  596.         FREE_ARG_TUP(self);
  597.     }
  598.     if (! str) return -1;
  599.  
  600.     Py_XDECREF(self->last_string);
  601.     self->last_string = str;
  602.  
  603.     if (! (*s = PyString_AsString(str))) return -1;
  604.     return n;
  605. }
  606.  
  607.  
  608. static int 
  609. readline_other(Unpicklerobject *self, char **s) {
  610.     PyObject *str;
  611.     int str_size;
  612.  
  613.     UNLESS (str = PyObject_CallObject(self->readline, empty_tuple)) {
  614.         return -1;
  615.     }
  616.  
  617.     if ((str_size = PyString_Size(str)) < 0)
  618.       return -1;
  619.  
  620.     Py_XDECREF(self->last_string);
  621.     self->last_string = str;
  622.  
  623.     if (! (*s = PyString_AsString(str)))
  624.       return -1;
  625.  
  626.     return str_size;
  627. }
  628.  
  629.  
  630. static char *
  631. pystrndup(char *s, int l) {
  632.   char *r;
  633.   UNLESS (r=malloc((l+1)*sizeof(char))) return (char*)PyErr_NoMemory();
  634.   memcpy(r,s,l);
  635.   r[l]=0;
  636.   return r;
  637. }
  638.  
  639.  
  640. static int
  641. get(Picklerobject *self, PyObject *id) {
  642.     PyObject *value, *mv;
  643.     long c_value;
  644.     char s[30];
  645.     size_t len;
  646.  
  647.     UNLESS (mv = PyDict_GetItem(self->memo, id)) {
  648.         PyErr_SetObject(PyExc_KeyError, id);
  649.         return -1;
  650.       }
  651.  
  652.     UNLESS (value = PyTuple_GetItem(mv, 0))
  653.         return -1;
  654.         
  655.     UNLESS (PyInt_Check(value)) {
  656.       PyErr_SetString(PicklingError, "no int where int expected in memo");
  657.       return -1;
  658.     }
  659.     c_value = PyInt_AS_LONG((PyIntObject*)value);
  660.  
  661.     if (!self->bin) {
  662.         s[0] = GET;
  663.         sprintf(s + 1, "%ld\n", c_value);
  664.         len = strlen(s);
  665.     }
  666.     else if (Pdata_Check(self->file)) {
  667.         if (write_other(self, NULL, 0) < 0) return -1;
  668.         PDATA_APPEND(self->file, mv, -1);
  669.         return 0;
  670.       }
  671.     else {
  672.         if (c_value < 256) {
  673.             s[0] = BINGET;
  674.             s[1] = (int)(c_value & 0xff);
  675.             len = 2;
  676.         }
  677.         else {
  678.             s[0] = LONG_BINGET;
  679.             s[1] = (int)(c_value & 0xff);
  680.             s[2] = (int)((c_value >> 8)  & 0xff);
  681.             s[3] = (int)((c_value >> 16) & 0xff);
  682.             s[4] = (int)((c_value >> 24) & 0xff);
  683.             len = 5;
  684.         }
  685.     }
  686.  
  687.     if ((*self->write_func)(self, s, len) < 0)
  688.         return -1;
  689.  
  690.     return 0;
  691. }
  692.     
  693.  
  694. static int
  695. put(Picklerobject *self, PyObject *ob) {
  696.     if (ob->ob_refcnt < 2 || self->fast)
  697.         return 0;
  698.  
  699.     return put2(self, ob);
  700. }
  701.  
  702.   
  703. static int
  704. put2(Picklerobject *self, PyObject *ob) {
  705.     char c_str[30];
  706.     int p;
  707.     size_t len;
  708.     int res = -1;
  709.     PyObject *py_ob_id = 0, *memo_len = 0, *t = 0;
  710.  
  711.     if (self->fast) return 0;
  712.  
  713.     if ((p = PyDict_Size(self->memo)) < 0)
  714.         goto finally;
  715.  
  716.     p++;  /* Make sure memo keys are positive! */
  717.  
  718.     UNLESS (py_ob_id = PyLong_FromVoidPtr(ob))
  719.         goto finally;
  720.  
  721.     UNLESS (memo_len = PyInt_FromLong(p))
  722.         goto finally;
  723.  
  724.     UNLESS (t = PyTuple_New(2))
  725.         goto finally;
  726.  
  727.     PyTuple_SET_ITEM(t, 0, memo_len);
  728.     Py_INCREF(memo_len);
  729.     PyTuple_SET_ITEM(t, 1, ob);
  730.     Py_INCREF(ob);
  731.  
  732.     if (PyDict_SetItem(self->memo, py_ob_id, t) < 0)
  733.         goto finally;
  734.  
  735.     if (!self->bin) {
  736.         c_str[0] = PUT;
  737.         sprintf(c_str + 1, "%d\n", p);
  738.         len = strlen(c_str);
  739.     }
  740.     else if (Pdata_Check(self->file)) {
  741.         if (write_other(self, NULL, 0) < 0) return -1;
  742.         PDATA_APPEND(self->file, memo_len, -1);
  743.         res=0;          /* Job well done ;) */
  744.         goto finally;
  745.     }
  746.     else {
  747.         if (p >= 256) {
  748.             c_str[0] = LONG_BINPUT;
  749.             c_str[1] = (int)(p & 0xff);
  750.             c_str[2] = (int)((p >> 8)  & 0xff);
  751.             c_str[3] = (int)((p >> 16) & 0xff);
  752.             c_str[4] = (int)((p >> 24) & 0xff);
  753.             len = 5;
  754.         }
  755.         else {
  756.             c_str[0] = BINPUT;
  757.             c_str[1] = p;
  758.             len = 2; 
  759.         }
  760.     }
  761.  
  762.     if ((*self->write_func)(self, c_str, len) < 0)
  763.         goto finally;
  764.  
  765.     res = 0;
  766.  
  767. finally:
  768.     Py_XDECREF(py_ob_id);
  769.     Py_XDECREF(memo_len);
  770.     Py_XDECREF(t);
  771.  
  772.     return res;
  773. }
  774.  
  775. #define PyImport_Import cPickle_Import
  776.  
  777. static PyObject *
  778. PyImport_Import(PyObject *module_name) {
  779.   static PyObject *silly_list=0, *__builtins___str=0, *__import___str;
  780.   static PyObject *standard_builtins=0;
  781.   PyObject *globals=0, *__import__=0, *__builtins__=0, *r=0;
  782.  
  783.   UNLESS (silly_list) {
  784.       UNLESS (__import___str=PyString_FromString("__import__"))
  785.         return NULL;
  786.       UNLESS (__builtins___str=PyString_FromString("__builtins__"))
  787.         return NULL;
  788.       UNLESS (silly_list=Py_BuildValue("[s]","__doc__"))
  789.         return NULL;
  790.     }
  791.  
  792.   if ((globals=PyEval_GetGlobals())) {
  793.       Py_INCREF(globals);
  794.       UNLESS (__builtins__=PyObject_GetItem(globals,__builtins___str))
  795.         goto err;
  796.     }
  797.   else {
  798.       PyErr_Clear();
  799.  
  800.       UNLESS (standard_builtins ||
  801.              (standard_builtins=PyImport_ImportModule("__builtin__")))
  802.         return NULL;
  803.       
  804.       __builtins__=standard_builtins;
  805.       Py_INCREF(__builtins__);
  806.       UNLESS (globals = Py_BuildValue("{sO}", "__builtins__", __builtins__))
  807.         goto err;
  808.     }
  809.  
  810.   if (PyDict_Check(__builtins__)) {
  811.     UNLESS (__import__=PyObject_GetItem(__builtins__,__import___str)) goto err;
  812.   }
  813.   else {
  814.     UNLESS (__import__=PyObject_GetAttr(__builtins__,__import___str)) goto err;
  815.   }
  816.  
  817.   UNLESS (r=PyObject_CallFunction(__import__,"OOOO",
  818.                                  module_name, globals, globals, silly_list))
  819.     goto err;
  820.  
  821.   Py_DECREF(globals);
  822.   Py_DECREF(__builtins__);
  823.   Py_DECREF(__import__);
  824.   
  825.   return r;
  826. err:
  827.   Py_XDECREF(globals);
  828.   Py_XDECREF(__builtins__);
  829.   Py_XDECREF(__import__);
  830.   return NULL;
  831. }
  832.  
  833. static PyObject *
  834. whichmodule(PyObject *global, PyObject *global_name) {
  835.     int i, j;
  836.     PyObject *module = 0, *modules_dict = 0,
  837.         *global_name_attr = 0, *name = 0;
  838.  
  839.     module = PyObject_GetAttrString(global, "__module__");
  840.     if (module) return module;
  841.     PyErr_Clear();
  842.  
  843.     UNLESS (modules_dict = PySys_GetObject("modules"))
  844.         return NULL;
  845.  
  846.     i = 0;
  847.     while ((j = PyDict_Next(modules_dict, &i, &name, &module))) {
  848.  
  849.         if (PyObject_Compare(name, __main___str)==0) continue;
  850.       
  851.         UNLESS (global_name_attr = PyObject_GetAttr(module, global_name)) {
  852.             PyErr_Clear();
  853.             continue;
  854.         }
  855.  
  856.         if (global_name_attr != global) {
  857.             Py_DECREF(global_name_attr);
  858.             continue;
  859.         }
  860.  
  861.         Py_DECREF(global_name_attr);
  862.  
  863.         break;
  864.     }
  865.  
  866.     /* The following implements the rule in pickle.py added in 1.5
  867.        that used __main__ if no module is found.  I don't actually
  868.        like this rule. jlf
  869.      */
  870.     if (!j) {
  871.         j=1;
  872.         name=__main___str;
  873.     }
  874.  
  875.     Py_INCREF(name);
  876.     return name;
  877. }
  878.  
  879.  
  880. static int
  881. save_none(Picklerobject *self, PyObject *args) {
  882.     static char none = NONE;
  883.     if ((*self->write_func)(self, &none, 1) < 0)  
  884.         return -1;
  885.  
  886.     return 0;
  887. }
  888.  
  889.       
  890. static int
  891. save_int(Picklerobject *self, PyObject *args) {
  892.     char c_str[32];
  893.     long l = PyInt_AS_LONG((PyIntObject *)args);
  894.     int len = 0;
  895.  
  896.     if (!self->bin
  897. #if SIZEOF_LONG > 4
  898.         || (l >> 32)
  899. #endif
  900.             ) {
  901.                 /* Save extra-long ints in non-binary mode, so that
  902.                    we can use python long parsing code to restore,
  903.                    if necessary. */
  904.         c_str[0] = INT;
  905.         sprintf(c_str + 1, "%ld\n", l);
  906.         if ((*self->write_func)(self, c_str, strlen(c_str)) < 0)
  907.             return -1;
  908.     }
  909.     else {
  910.         c_str[1] = (int)( l        & 0xff);
  911.         c_str[2] = (int)((l >> 8)  & 0xff);
  912.         c_str[3] = (int)((l >> 16) & 0xff);
  913.         c_str[4] = (int)((l >> 24) & 0xff);
  914.  
  915.         if ((c_str[4] == 0) && (c_str[3] == 0)) {
  916.             if (c_str[2] == 0) {
  917.                 c_str[0] = BININT1;
  918.                 len = 2;
  919.             }
  920.             else {
  921.                 c_str[0] = BININT2;
  922.                 len = 3;
  923.             }
  924.         }
  925.         else {
  926.             c_str[0] = BININT;
  927.             len = 5;
  928.         }
  929.  
  930.         if ((*self->write_func)(self, c_str, len) < 0)
  931.             return -1;
  932.     }
  933.  
  934.     return 0;
  935. }
  936.  
  937.  
  938. static int
  939. save_long(Picklerobject *self, PyObject *args) {
  940.     int size, res = -1;
  941.     PyObject *repr = 0;
  942.  
  943.     static char l = LONG;
  944.  
  945.     UNLESS (repr = PyObject_Repr(args))
  946.         goto finally;
  947.  
  948.     if ((size = PyString_Size(repr)) < 0)
  949.         goto finally;
  950.  
  951.     if ((*self->write_func)(self, &l, 1) < 0)
  952.         goto finally;
  953.  
  954.     if ((*self->write_func)(self, 
  955.         PyString_AS_STRING((PyStringObject *)repr), size) < 0)
  956.         goto finally;
  957.  
  958.     if ((*self->write_func)(self, "\n", 1) < 0)
  959.         goto finally;
  960.  
  961.     res = 0;
  962.  
  963. finally:
  964.     Py_XDECREF(repr);
  965.  
  966.     return res;
  967. }
  968.  
  969.  
  970. static int
  971. save_float(Picklerobject *self, PyObject *args) {
  972.     double x = PyFloat_AS_DOUBLE((PyFloatObject *)args);
  973.  
  974.     if (self->bin) {
  975.         int s, e;
  976.         double f;
  977.         long fhi, flo;
  978.         char str[9], *p = str;
  979.  
  980.         *p = BINFLOAT;
  981.         p++;
  982.  
  983.         if (x < 0) {
  984.             s = 1;
  985.             x = -x;
  986.         }
  987.         else
  988.             s = 0;
  989.  
  990.         f = frexp(x, &e);
  991.  
  992.         /* Normalize f to be in the range [1.0, 2.0) */
  993.         if (0.5 <= f && f < 1.0) {
  994.             f *= 2.0;
  995.             e--;
  996.         }
  997.         else if (f == 0.0) {
  998.             e = 0;
  999.         }
  1000.         else {
  1001.             PyErr_SetString(PyExc_SystemError,
  1002.                             "frexp() result out of range");
  1003.             return -1;
  1004.         }
  1005.  
  1006.         if (e >= 1024) {
  1007.             /* XXX 1024 itself is reserved for Inf/NaN */
  1008.             PyErr_SetString(PyExc_OverflowError,
  1009.                             "float too large to pack with d format");
  1010.             return -1;
  1011.         }
  1012.         else if (e < -1022) {
  1013.             /* Gradual underflow */
  1014.             f = ldexp(f, 1022 + e);
  1015.             e = 0;
  1016.         }
  1017.         else if (!(e == 0 && f == 0.0)) {
  1018.             e += 1023;
  1019.             f -= 1.0; /* Get rid of leading 1 */
  1020.         }
  1021.  
  1022.         /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
  1023.         f *= 268435456.0; /* 2**28 */
  1024.         fhi = (long) floor(f); /* Truncate */
  1025.         f -= (double)fhi;
  1026.         f *= 16777216.0; /* 2**24 */
  1027.         flo = (long) floor(f + 0.5); /* Round */
  1028.  
  1029.         /* First byte */
  1030.         *p = (s<<7) | (e>>4);
  1031.         p++;
  1032.  
  1033.         /* Second byte */
  1034.         *p = (char) (((e&0xF)<<4) | (fhi>>24));
  1035.         p++;
  1036.  
  1037.         /* Third byte */
  1038.         *p = (fhi>>16) & 0xFF;
  1039.         p++;
  1040.  
  1041.         /* Fourth byte */
  1042.         *p = (fhi>>8) & 0xFF;
  1043.         p++;
  1044.  
  1045.         /* Fifth byte */
  1046.         *p = fhi & 0xFF;
  1047.         p++;
  1048.  
  1049.         /* Sixth byte */
  1050.         *p = (flo>>16) & 0xFF;
  1051.         p++;
  1052.  
  1053.         /* Seventh byte */
  1054.         *p = (flo>>8) & 0xFF;
  1055.         p++;
  1056.  
  1057.         /* Eighth byte */
  1058.         *p = flo & 0xFF;
  1059.  
  1060.         if ((*self->write_func)(self, str, 9) < 0)
  1061.             return -1;
  1062.     }
  1063.     else {
  1064.         char c_str[250];
  1065.         c_str[0] = FLOAT;
  1066.         sprintf(c_str + 1, "%.17g\n", x);
  1067.  
  1068.         if ((*self->write_func)(self, c_str, strlen(c_str)) < 0)
  1069.             return -1;
  1070.     }
  1071.  
  1072.     return 0;
  1073. }
  1074.  
  1075.  
  1076. static int
  1077. save_string(Picklerobject *self, PyObject *args, int doput) {
  1078.     int size, len;
  1079.     PyObject *repr=0;
  1080.  
  1081.     if ((size = PyString_Size(args)) < 0)
  1082.       return -1;
  1083.  
  1084.     if (!self->bin) {
  1085.         char *repr_str;
  1086.  
  1087.         static char string = STRING;
  1088.  
  1089.         UNLESS (repr = PyObject_Repr(args))
  1090.             return -1;
  1091.  
  1092.         if ((len = PyString_Size(repr)) < 0)
  1093.           goto err;
  1094.         repr_str = PyString_AS_STRING((PyStringObject *)repr);
  1095.  
  1096.         if ((*self->write_func)(self, &string, 1) < 0)
  1097.             goto err;
  1098.  
  1099.         if ((*self->write_func)(self, repr_str, len) < 0)
  1100.             goto err;
  1101.  
  1102.         if ((*self->write_func)(self, "\n", 1) < 0)
  1103.             goto err;
  1104.  
  1105.         Py_XDECREF(repr);
  1106.     }
  1107.     else {
  1108.         int i;
  1109.         char c_str[5];
  1110.  
  1111.         if ((size = PyString_Size(args)) < 0)
  1112.           return -1;
  1113.  
  1114.         if (size < 256) {
  1115.             c_str[0] = SHORT_BINSTRING;
  1116.             c_str[1] = size;
  1117.             len = 2;
  1118.         }
  1119.         else {
  1120.             c_str[0] = BINSTRING;
  1121.             for (i = 1; i < 5; i++)
  1122.                 c_str[i] = (int)(size >> ((i - 1) * 8));
  1123.             len = 5;
  1124.         }
  1125.  
  1126.         if ((*self->write_func)(self, c_str, len) < 0)
  1127.             return -1;
  1128.  
  1129.         if (size > 128 && Pdata_Check(self->file)) {
  1130.             if (write_other(self, NULL, 0) < 0) return -1;
  1131.             PDATA_APPEND(self->file, args, -1);
  1132.           }
  1133.         else {
  1134.           if ((*self->write_func)(self, 
  1135.               PyString_AS_STRING((PyStringObject *)args), size) < 0)
  1136.             return -1;
  1137.         }
  1138.     }
  1139.  
  1140.     if (doput)
  1141.       if (put(self, args) < 0)
  1142.         return -1;
  1143.  
  1144.     return 0;
  1145.  
  1146. err:
  1147.     Py_XDECREF(repr);
  1148.     return -1;
  1149. }
  1150.  
  1151.  
  1152. static int
  1153. save_unicode(Picklerobject *self, PyObject *args, int doput) {
  1154.     int size, len;
  1155.     PyObject *repr=0;
  1156.  
  1157.     if (!PyUnicode_Check(args))
  1158.       return -1;
  1159.  
  1160.     if (!self->bin) {
  1161.         char *repr_str;
  1162.         static char string = UNICODE;
  1163.  
  1164.         UNLESS (repr = PyUnicode_AsRawUnicodeEscapeString(args))
  1165.             return -1;
  1166.  
  1167.         if ((len = PyString_Size(repr)) < 0)
  1168.           goto err;
  1169.         repr_str = PyString_AS_STRING((PyStringObject *)repr);
  1170.  
  1171.         if ((*self->write_func)(self, &string, 1) < 0)
  1172.             goto err;
  1173.  
  1174.         if ((*self->write_func)(self, repr_str, len) < 0)
  1175.             goto err;
  1176.  
  1177.         if ((*self->write_func)(self, "\n", 1) < 0)
  1178.             goto err;
  1179.  
  1180.         Py_XDECREF(repr);
  1181.     }
  1182.     else {
  1183.         int i;
  1184.         char c_str[5];
  1185.  
  1186.         UNLESS (repr = PyUnicode_AsUTF8String(args))
  1187.             return -1;
  1188.  
  1189.         if ((size = PyString_Size(repr)) < 0)
  1190.         goto err;
  1191.  
  1192.     c_str[0] = BINUNICODE;
  1193.     for (i = 1; i < 5; i++)
  1194.         c_str[i] = (int)(size >> ((i - 1) * 8));
  1195.     len = 5;
  1196.  
  1197.         if ((*self->write_func)(self, c_str, len) < 0)
  1198.             goto err;
  1199.  
  1200.         if (size > 128 && Pdata_Check(self->file)) {
  1201.             if (write_other(self, NULL, 0) < 0)
  1202.         goto err;
  1203.             PDATA_APPEND(self->file, repr, -1);
  1204.           }
  1205.         else {
  1206.           if ((*self->write_func)(self, PyString_AS_STRING(repr), size) < 0)
  1207.           goto err;
  1208.         }
  1209.  
  1210.     Py_DECREF(repr);
  1211.     }
  1212.  
  1213.     if (doput)
  1214.       if (put(self, args) < 0)
  1215.         return -1;
  1216.  
  1217.     return 0;
  1218.  
  1219. err:
  1220.     Py_XDECREF(repr);
  1221.     return -1;
  1222. }
  1223.  
  1224.  
  1225. static int
  1226. save_tuple(Picklerobject *self, PyObject *args) {
  1227.     PyObject *element = 0, *py_tuple_id = 0;
  1228.     int len, i, has_key, res = -1;
  1229.  
  1230.     static char tuple = TUPLE;
  1231.  
  1232.     if ((*self->write_func)(self, &MARKv, 1) < 0)
  1233.         goto finally;
  1234.  
  1235.     if ((len = PyTuple_Size(args)) < 0)  
  1236.         goto finally;
  1237.  
  1238.     for (i = 0; i < len; i++) {
  1239.         UNLESS (element = PyTuple_GET_ITEM((PyTupleObject *)args, i))  
  1240.             goto finally;
  1241.     
  1242.         if (save(self, element, 0) < 0)
  1243.             goto finally;
  1244.     }
  1245.  
  1246.     UNLESS (py_tuple_id = PyLong_FromVoidPtr(args))
  1247.         goto finally;
  1248.  
  1249.     if (len) {
  1250.         if ((has_key = cPickle_PyMapping_HasKey(self->memo, py_tuple_id)) < 0)
  1251.             goto finally;
  1252.  
  1253.         if (has_key) {
  1254.             if (self->bin) {
  1255.                 static char pop_mark = POP_MARK;
  1256.   
  1257.                 if ((*self->write_func)(self, &pop_mark, 1) < 0)
  1258.                     goto finally;
  1259.             }
  1260.             else {
  1261.                 static char pop = POP;
  1262.        
  1263.                 for (i = 0; i <= len; i++) {
  1264.                     if ((*self->write_func)(self, &pop, 1) < 0)
  1265.                         goto finally;
  1266.                 } 
  1267.             }
  1268.         
  1269.             if (get(self, py_tuple_id) < 0)
  1270.                 goto finally;
  1271.  
  1272.             res = 0;
  1273.             goto finally;
  1274.         }
  1275.     }
  1276.  
  1277.     if ((*self->write_func)(self, &tuple, 1) < 0) {
  1278.         goto finally;
  1279.     }
  1280.  
  1281.     if (put(self, args) < 0)
  1282.         goto finally;
  1283.  
  1284.     res = 0;
  1285.  
  1286. finally:
  1287.     Py_XDECREF(py_tuple_id);
  1288.  
  1289.     return res;
  1290. }
  1291.  
  1292. static int
  1293. save_empty_tuple(Picklerobject *self, PyObject *args) {
  1294.     static char tuple = EMPTY_TUPLE;
  1295.  
  1296.     return (*self->write_func)(self, &tuple, 1);
  1297. }
  1298.  
  1299.  
  1300. static int
  1301. save_list(Picklerobject *self, PyObject *args) {
  1302.     PyObject *element = 0;
  1303.     int s_len, len, i, using_appends, res = -1;
  1304.     char s[3];
  1305.  
  1306.     static char append = APPEND, appends = APPENDS;
  1307.  
  1308.     if (self->bin) {
  1309.         s[0] = EMPTY_LIST;
  1310.         s_len = 1;
  1311.     } 
  1312.     else {
  1313.         s[0] = MARK;
  1314.         s[1] = LIST;
  1315.         s_len = 2;
  1316.     }
  1317.  
  1318.     if ((len = PyList_Size(args)) < 0)
  1319.         goto finally;
  1320.  
  1321.     if ((*self->write_func)(self, s, s_len) < 0)
  1322.         goto finally;
  1323.  
  1324.     if (len == 0) {
  1325.         if (put(self, args) < 0)
  1326.             goto finally;
  1327.     }
  1328.     else {
  1329.         if (put2(self, args) < 0)
  1330.             goto finally;
  1331.     }
  1332.  
  1333.     if ((using_appends = (self->bin && (len > 1))))
  1334.         if ((*self->write_func)(self, &MARKv, 1) < 0)
  1335.             goto finally;
  1336.  
  1337.     for (i = 0; i < len; i++) {
  1338.         UNLESS (element = PyList_GET_ITEM((PyListObject *)args, i))  
  1339.             goto finally;
  1340.  
  1341.         if (save(self, element, 0) < 0)  
  1342.             goto finally;       
  1343.  
  1344.         if (!using_appends) {
  1345.             if ((*self->write_func)(self, &append, 1) < 0)
  1346.                 goto finally;
  1347.         }
  1348.     }
  1349.  
  1350.     if (using_appends) {
  1351.         if ((*self->write_func)(self, &appends, 1) < 0)
  1352.             goto finally;
  1353.     }
  1354.  
  1355.     res = 0;
  1356.  
  1357. finally:
  1358.  
  1359.     return res;
  1360. }
  1361.  
  1362.  
  1363. static int
  1364. save_dict(Picklerobject *self, PyObject *args) {
  1365.     PyObject *key = 0, *value = 0;
  1366.     int i, len, res = -1, using_setitems;
  1367.     char s[3];
  1368.  
  1369.     static char setitem = SETITEM, setitems = SETITEMS;
  1370.  
  1371.     if (self->bin) {
  1372.         s[0] = EMPTY_DICT;
  1373.         len = 1;
  1374.     }
  1375.     else {
  1376.         s[0] = MARK;
  1377.         s[1] = DICT;
  1378.         len = 2;
  1379.     }
  1380.  
  1381.     if ((*self->write_func)(self, s, len) < 0)
  1382.         goto finally;
  1383.  
  1384.     if ((len = PyDict_Size(args)) < 0)
  1385.         goto finally;
  1386.  
  1387.     if (len == 0) {
  1388.         if (put(self, args) < 0)
  1389.             goto finally;
  1390.     }
  1391.     else {
  1392.         if (put2(self, args) < 0)
  1393.             goto finally;
  1394.     }
  1395.  
  1396.     if ((using_setitems = (self->bin && (PyDict_Size(args) > 1))))
  1397.         if ((*self->write_func)(self, &MARKv, 1) < 0)
  1398.             goto finally;
  1399.  
  1400.     i = 0;
  1401.     while (PyDict_Next(args, &i, &key, &value)) {
  1402.         if (save(self, key, 0) < 0)
  1403.             goto finally;
  1404.  
  1405.         if (save(self, value, 0) < 0)
  1406.             goto finally;
  1407.  
  1408.         if (!using_setitems) {
  1409.             if ((*self->write_func)(self, &setitem, 1) < 0)
  1410.                 goto finally;
  1411.         }
  1412.     }
  1413.  
  1414.     if (using_setitems) {
  1415.         if ((*self->write_func)(self, &setitems, 1) < 0)
  1416.             goto finally;
  1417.     }
  1418.  
  1419.     res = 0;
  1420.  
  1421. finally:
  1422.  
  1423.     return res;
  1424. }
  1425.  
  1426.  
  1427. static int  
  1428. save_inst(Picklerobject *self, PyObject *args) {
  1429.     PyObject *class = 0, *module = 0, *name = 0, *state = 0, 
  1430.              *getinitargs_func = 0, *getstate_func = 0, *class_args = 0;
  1431.     char *module_str, *name_str;
  1432.     int module_size, name_size, res = -1;
  1433.  
  1434.     static char inst = INST, obj = OBJ, build = BUILD;
  1435.  
  1436.     if ((*self->write_func)(self, &MARKv, 1) < 0)
  1437.         goto finally;
  1438.  
  1439.     UNLESS (class = PyObject_GetAttr(args, __class___str))
  1440.         goto finally;
  1441.  
  1442.     if (self->bin) {
  1443.         if (save(self, class, 0) < 0)
  1444.             goto finally;
  1445.     }
  1446.  
  1447.     if ((getinitargs_func = PyObject_GetAttr(args, __getinitargs___str))) {
  1448.         PyObject *element = 0;
  1449.         int i, len;
  1450.  
  1451.         UNLESS (class_args = 
  1452.             PyObject_CallObject(getinitargs_func, empty_tuple))
  1453.             goto finally;
  1454.  
  1455.         if ((len = PyObject_Size(class_args)) < 0)  
  1456.             goto finally;
  1457.  
  1458.         for (i = 0; i < len; i++) {
  1459.             UNLESS (element = PySequence_GetItem(class_args, i)) 
  1460.                 goto finally;
  1461.  
  1462.             if (save(self, element, 0) < 0) {
  1463.                 Py_DECREF(element);
  1464.                 goto finally;
  1465.             }
  1466.  
  1467.             Py_DECREF(element);
  1468.         }
  1469.     }
  1470.     else {
  1471.         PyErr_Clear();
  1472.     }
  1473.  
  1474.     if (!self->bin) {
  1475.         UNLESS (name = ((PyClassObject *)class)->cl_name) {
  1476.             PyErr_SetString(PicklingError, "class has no name");
  1477.             goto finally;
  1478.         }
  1479.  
  1480.         UNLESS (module = whichmodule(class, name))
  1481.             goto finally;
  1482.  
  1483.         
  1484.         if ((module_size = PyString_Size(module)) < 0 ||
  1485.            (name_size = PyString_Size(name)) < 0)
  1486.           goto finally;
  1487.  
  1488.         module_str = PyString_AS_STRING((PyStringObject *)module);
  1489.         name_str   = PyString_AS_STRING((PyStringObject *)name);
  1490.  
  1491.         if ((*self->write_func)(self, &inst, 1) < 0)
  1492.             goto finally;
  1493.  
  1494.         if ((*self->write_func)(self, module_str, module_size) < 0)
  1495.             goto finally;
  1496.  
  1497.         if ((*self->write_func)(self, "\n", 1) < 0)
  1498.             goto finally;
  1499.  
  1500.         if ((*self->write_func)(self, name_str, name_size) < 0)
  1501.             goto finally;
  1502.  
  1503.         if ((*self->write_func)(self, "\n", 1) < 0)
  1504.             goto finally;
  1505.     }
  1506.     else if ((*self->write_func)(self, &obj, 1) < 0) {
  1507.         goto finally;
  1508.     }
  1509.  
  1510.     if ((getstate_func = PyObject_GetAttr(args, __getstate___str))) {
  1511.         UNLESS (state = PyObject_CallObject(getstate_func, empty_tuple))
  1512.             goto finally;
  1513.     }
  1514.     else {
  1515.         PyErr_Clear();
  1516.  
  1517.         UNLESS (state = PyObject_GetAttr(args, __dict___str)) {
  1518.             PyErr_Clear();
  1519.             res = 0;
  1520.             goto finally;
  1521.         }
  1522.     }
  1523.  
  1524.     if (!PyDict_Check(state)) {
  1525.         if (put2(self, args) < 0)
  1526.             goto finally;
  1527.     }
  1528.     else {
  1529.         if (put(self, args) < 0)
  1530.             goto finally;
  1531.     }
  1532.   
  1533.     if (save(self, state, 0) < 0)
  1534.         goto finally;
  1535.  
  1536.     if ((*self->write_func)(self, &build, 1) < 0)
  1537.         goto finally;
  1538.  
  1539.     res = 0;
  1540.  
  1541. finally:
  1542.     Py_XDECREF(module);
  1543.     Py_XDECREF(class);
  1544.     Py_XDECREF(state);
  1545.     Py_XDECREF(getinitargs_func);
  1546.     Py_XDECREF(getstate_func);
  1547.     Py_XDECREF(class_args);
  1548.  
  1549.     return res;
  1550. }
  1551.  
  1552.  
  1553. static int
  1554. save_global(Picklerobject *self, PyObject *args, PyObject *name) {
  1555.     PyObject *global_name = 0, *module = 0;
  1556.     char *name_str, *module_str; 
  1557.     int module_size, name_size, res = -1;
  1558.  
  1559.     static char global = GLOBAL;
  1560.  
  1561.     if (name) {
  1562.         global_name = name;
  1563.         Py_INCREF(global_name);
  1564.     }
  1565.     else {
  1566.         UNLESS (global_name = PyObject_GetAttr(args, __name___str))
  1567.             goto finally;
  1568.     }
  1569.  
  1570.     UNLESS (module = whichmodule(args, global_name))
  1571.         goto finally;
  1572.  
  1573.     if ((module_size = PyString_Size(module)) < 0 ||
  1574.         (name_size = PyString_Size(global_name)) < 0)
  1575.       goto finally;
  1576.  
  1577.     module_str = PyString_AS_STRING((PyStringObject *)module);
  1578.     name_str   = PyString_AS_STRING((PyStringObject *)global_name);
  1579.  
  1580.     if ((*self->write_func)(self, &global, 1) < 0)
  1581.         goto finally;
  1582.  
  1583.     if ((*self->write_func)(self, module_str, module_size) < 0)
  1584.         goto finally;
  1585.  
  1586.     if ((*self->write_func)(self, "\n", 1) < 0)
  1587.         goto finally;
  1588.  
  1589.     if ((*self->write_func)(self, name_str, name_size) < 0)
  1590.         goto finally;
  1591.  
  1592.     if ((*self->write_func)(self, "\n", 1) < 0)
  1593.         goto finally;
  1594.  
  1595.     if (put(self, args) < 0)
  1596.         goto finally;
  1597.  
  1598.     res = 0;
  1599.  
  1600. finally:
  1601.     Py_XDECREF(module);
  1602.     Py_XDECREF(global_name);
  1603.  
  1604.     return res;
  1605. }
  1606.  
  1607. static int
  1608. save_pers(Picklerobject *self, PyObject *args, PyObject *f) {
  1609.     PyObject *pid = 0;
  1610.     int size, res = -1;
  1611.  
  1612.     static char persid = PERSID, binpersid = BINPERSID;
  1613.  
  1614.     Py_INCREF(args);
  1615.     ARG_TUP(self, args);
  1616.     if (self->arg) {
  1617.         pid = PyObject_CallObject(f, self->arg);
  1618.         FREE_ARG_TUP(self);
  1619.     }
  1620.     if (! pid) return -1;
  1621.  
  1622.     if (pid != Py_None) {
  1623.         if (!self->bin) {
  1624.             if (!PyString_Check(pid)) {
  1625.                 PyErr_SetString(PicklingError, 
  1626.                     "persistent id must be string");
  1627.                 goto finally;
  1628.             }
  1629.  
  1630.             if ((*self->write_func)(self, &persid, 1) < 0)
  1631.                 goto finally;
  1632.  
  1633.             if ((size = PyString_Size(pid)) < 0)
  1634.                 goto finally;
  1635.  
  1636.             if ((*self->write_func)(self, 
  1637.                 PyString_AS_STRING((PyStringObject *)pid), size) < 0)
  1638.                 goto finally;
  1639.  
  1640.             if ((*self->write_func)(self, "\n", 1) < 0)
  1641.                 goto finally;
  1642.      
  1643.             res = 1;
  1644.             goto finally;
  1645.         }
  1646.         else if (save(self, pid, 1) >= 0) {
  1647.             if ((*self->write_func)(self, &binpersid, 1) < 0)
  1648.                 res = -1;
  1649.             else
  1650.                 res = 1;
  1651.         }
  1652.  
  1653.         goto finally;              
  1654.     }
  1655.  
  1656.     res = 0;
  1657.  
  1658. finally:
  1659.     Py_XDECREF(pid);
  1660.  
  1661.     return res;
  1662. }
  1663.  
  1664.  
  1665. static int 
  1666. save_reduce(Picklerobject *self, PyObject *callable,
  1667.             PyObject *tup, PyObject *state, PyObject *ob) {
  1668.     static char reduce = REDUCE, build = BUILD;
  1669.  
  1670.     if (save(self, callable, 0) < 0)
  1671.         return -1;
  1672.  
  1673.     if (save(self, tup, 0) < 0)
  1674.         return -1;
  1675.  
  1676.     if ((*self->write_func)(self, &reduce, 1) < 0)
  1677.         return -1;
  1678.  
  1679.     if (ob != NULL) {
  1680.         if (state && !PyDict_Check(state)) {
  1681.             if (put2(self, ob) < 0)
  1682.                 return -1;
  1683.         }
  1684.         else {
  1685.             if (put(self, ob) < 0)
  1686.                 return -1;
  1687.         }
  1688.     }
  1689.     
  1690.     if (state) {
  1691.         if (save(self, state, 0) < 0)
  1692.             return -1;
  1693.  
  1694.         if ((*self->write_func)(self, &build, 1) < 0)
  1695.             return -1;
  1696.     }
  1697.  
  1698.     return 0;
  1699. }
  1700.  
  1701. static int
  1702. save(Picklerobject *self, PyObject *args, int  pers_save) {
  1703.     PyTypeObject *type;
  1704.     PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0, *arg_tup = 0,
  1705.              *callable = 0, *state = 0;
  1706.     int res = -1, tmp, size;
  1707.  
  1708.     if (!pers_save && self->pers_func) {
  1709.         if ((tmp = save_pers(self, args, self->pers_func)) != 0) {
  1710.             res = tmp;
  1711.             goto finally;
  1712.         }
  1713.     }
  1714.  
  1715.     if (args == Py_None) {
  1716.         res = save_none(self, args);
  1717.         goto finally;
  1718.     }
  1719.  
  1720.     type = args->ob_type;
  1721.  
  1722.     switch (type->tp_name[0]) {
  1723.         case 'i':
  1724.             if (type == &PyInt_Type) {
  1725.                 res = save_int(self, args);
  1726.                 goto finally;
  1727.             }
  1728.             break;
  1729.  
  1730.         case 'l':
  1731.             if (type == &PyLong_Type) {
  1732.                 res = save_long(self, args);
  1733.                 goto finally;
  1734.             }
  1735.             break;
  1736.  
  1737.         case 'f':
  1738.             if (type == &PyFloat_Type) {
  1739.                 res = save_float(self, args);
  1740.                 goto finally;
  1741.             }
  1742.             break;
  1743.  
  1744.         case 't':
  1745.             if (type == &PyTuple_Type && PyTuple_Size(args)==0) {
  1746.                 if (self->bin) res = save_empty_tuple(self, args);
  1747.                 else          res = save_tuple(self, args);
  1748.                 goto finally;
  1749.             }
  1750.             break;
  1751.  
  1752.         case 's':
  1753.             if ((type == &PyString_Type) && (PyString_GET_SIZE(args) < 2)) {
  1754.                 res = save_string(self, args, 0);
  1755.                 goto finally;
  1756.             }
  1757.  
  1758.         case 'u':
  1759.             if ((type == &PyUnicode_Type) && (PyString_GET_SIZE(args) < 2)) {
  1760.                 res = save_unicode(self, args, 0);
  1761.                 goto finally;
  1762.             }
  1763.     }
  1764.  
  1765.     if (args->ob_refcnt > 1) {
  1766.         int  has_key;
  1767.  
  1768.         UNLESS (py_ob_id = PyLong_FromVoidPtr(args))
  1769.             goto finally;
  1770.  
  1771.         if ((has_key = cPickle_PyMapping_HasKey(self->memo, py_ob_id)) < 0)
  1772.             goto finally;
  1773.  
  1774.         if (has_key) {
  1775.             if (get(self, py_ob_id) < 0)
  1776.                 goto finally;
  1777.  
  1778.             res = 0;
  1779.             goto finally;
  1780.         }
  1781.     }
  1782.  
  1783.     switch (type->tp_name[0]) {
  1784.         case 's':
  1785.             if (type == &PyString_Type) {
  1786.                 res = save_string(self, args, 1);
  1787.                 goto finally;
  1788.             }
  1789.             break;
  1790.  
  1791.         case 'u':
  1792.             if (type == &PyUnicode_Type) {
  1793.                 res = save_unicode(self, args, 1);
  1794.                 goto finally;
  1795.             }
  1796.             break;
  1797.  
  1798.         case 't':
  1799.             if (type == &PyTuple_Type) {
  1800.                 res = save_tuple(self, args);
  1801.                 goto finally;
  1802.             }
  1803.             break;
  1804.  
  1805.         case 'l':
  1806.             if (type == &PyList_Type) {
  1807.                 res = save_list(self, args);
  1808.                 goto finally;
  1809.             }
  1810.             break;
  1811.  
  1812.         case 'd':
  1813.             if (type == &PyDict_Type) {
  1814.                 res = save_dict(self, args);
  1815.                 goto finally; 
  1816.             }
  1817.             break;
  1818.  
  1819.         case 'i':
  1820.             if (type == &PyInstance_Type) {
  1821.                 res = save_inst(self, args);
  1822.                 goto finally;
  1823.             }
  1824.             break;
  1825.  
  1826.         case 'c':
  1827.             if (type == &PyClass_Type) {
  1828.                 res = save_global(self, args, NULL);
  1829.                 goto finally;
  1830.             }
  1831.             break;
  1832.  
  1833.         case 'f':
  1834.             if (type == &PyFunction_Type) {
  1835.                 res = save_global(self, args, NULL);
  1836.                 goto finally;
  1837.             }
  1838.             break;
  1839.  
  1840.         case 'b':
  1841.             if (type == &PyCFunction_Type) {
  1842.                 res = save_global(self, args, NULL);
  1843.                 goto finally;
  1844.             }
  1845.     }
  1846.  
  1847.     if (!pers_save && self->inst_pers_func) {
  1848.         if ((tmp = save_pers(self, args, self->inst_pers_func)) != 0) {
  1849.             res = tmp;
  1850.             goto finally;
  1851.         }
  1852.     }
  1853.  
  1854.     if ((__reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type))) {
  1855.         Py_INCREF(__reduce__);
  1856.  
  1857.         Py_INCREF(args);
  1858.         ARG_TUP(self, args);
  1859.         if (self->arg) {
  1860.             t = PyObject_CallObject(__reduce__, self->arg);
  1861.             FREE_ARG_TUP(self);
  1862.         }
  1863.         if (! t) goto finally;
  1864.     }        
  1865.     else {
  1866.         PyErr_Clear();
  1867.  
  1868.         if ((__reduce__ = PyObject_GetAttr(args, __reduce___str))) {
  1869.             UNLESS (t = PyObject_CallObject(__reduce__, empty_tuple))
  1870.                 goto finally;
  1871.         }
  1872.         else {
  1873.             PyErr_Clear();
  1874.         }
  1875.     }
  1876.  
  1877.     if (t) {
  1878.         if (PyString_Check(t)) {
  1879.             res = save_global(self, args, t);
  1880.             goto finally;
  1881.         }
  1882.  
  1883.         if (!PyTuple_Check(t)) {
  1884.             cPickle_ErrFormat(PicklingError, "Value returned by %s must "
  1885.                 "be a tuple", "O", __reduce__);
  1886.             goto finally;
  1887.         }
  1888.  
  1889.         size = PyTuple_Size(t);
  1890.         
  1891.         if ((size != 3) && (size != 2)) {
  1892.             cPickle_ErrFormat(PicklingError, "tuple returned by %s must "     
  1893.                 "contain only two or three elements", "O", __reduce__);
  1894.                 goto finally;
  1895.         }
  1896.         
  1897.         callable = PyTuple_GET_ITEM(t, 0);
  1898.  
  1899.         arg_tup = PyTuple_GET_ITEM(t, 1);
  1900.  
  1901.         if (size > 2) {
  1902.             state = PyTuple_GET_ITEM(t, 2);
  1903.         }
  1904.  
  1905.         UNLESS (PyTuple_Check(arg_tup) || arg_tup==Py_None) {
  1906.             cPickle_ErrFormat(PicklingError, "Second element of tuple "
  1907.                 "returned by %s must be a tuple", "O", __reduce__);
  1908.             goto finally;
  1909.         }
  1910.  
  1911.         res = save_reduce(self, callable, arg_tup, state, args);
  1912.         goto finally;
  1913.     }
  1914.  
  1915.     PyErr_SetObject(UnpickleableError, args);
  1916.  
  1917. finally:
  1918.     Py_XDECREF(py_ob_id);
  1919.     Py_XDECREF(__reduce__);
  1920.     Py_XDECREF(t);
  1921.    
  1922.     return res;
  1923. }
  1924.  
  1925.  
  1926. static int
  1927. dump(Picklerobject *self, PyObject *args) {
  1928.     static char stop = STOP;
  1929.  
  1930.     if (save(self, args, 0) < 0)
  1931.         return -1;
  1932.  
  1933.     if ((*self->write_func)(self, &stop, 1) < 0)
  1934.         return -1;
  1935.  
  1936.     if ((*self->write_func)(self, NULL, 0) < 0)
  1937.         return -1;
  1938.  
  1939.     return 0;
  1940. }
  1941.  
  1942. static PyObject *
  1943. Pickle_clear_memo(Picklerobject *self, PyObject *args) {
  1944.   if (args && ! PyArg_ParseTuple(args,":clear_memo")) return NULL;
  1945.   if (self->memo) PyDict_Clear(self->memo);
  1946.   Py_INCREF(Py_None);
  1947.   return Py_None;
  1948. }
  1949.  
  1950. static PyObject *
  1951. Pickle_getvalue(Picklerobject *self, PyObject *args) {
  1952.   int l, i, rsize, ssize, clear=1, lm;
  1953.   long ik;
  1954.   PyObject *k, *r;
  1955.   char *s, *p, *have_get;
  1956.   Pdata *data;
  1957.  
  1958.   if (args && ! PyArg_ParseTuple(args,"|i:getvalue",&clear)) return NULL;
  1959.  
  1960.   /* Check to make sure we are based on a list */
  1961.   if (! Pdata_Check(self->file)) {
  1962.       PyErr_SetString(PicklingError,
  1963.                       "Attempt to getvalue a non-list-based pickler");
  1964.       return NULL;
  1965.     }
  1966.  
  1967.   /* flush write buffer */
  1968.   if (write_other(self, NULL, 0) < 0) return NULL;
  1969.  
  1970.   data=(Pdata*)self->file;
  1971.   l=data->length;
  1972.  
  1973.   /* set up an array to hold get/put status */
  1974.   if ((lm=PyDict_Size(self->memo)) < 0) return NULL;
  1975.   lm++;
  1976.   if (! (have_get=malloc((lm)*sizeof(char)))) return PyErr_NoMemory();  
  1977.   memset(have_get,0,lm);
  1978.  
  1979.   /* Scan for gets. */
  1980.   for (rsize=0, i=l; --i >= 0; ) {
  1981.       k=data->data[i];
  1982.       
  1983.       if (PyString_Check(k)) {
  1984.         rsize += PyString_GET_SIZE(k);
  1985.       }
  1986.  
  1987.       else if (PyInt_Check(k)) { /* put */
  1988.         ik=PyInt_AS_LONG((PyIntObject*)k);
  1989.         if (ik >= lm || ik==0) {
  1990.           PyErr_SetString(PicklingError,
  1991.                           "Invalid get data");
  1992.           return NULL;
  1993.         }      
  1994.         if (have_get[ik]) { /* with matching get */
  1995.           if (ik < 256) rsize += 2;
  1996.           else rsize+=5;
  1997.         }
  1998.       }
  1999.  
  2000.       else if (! (PyTuple_Check(k) &&
  2001.                   PyTuple_GET_SIZE(k) == 2 &&
  2002.                   PyInt_Check((k=PyTuple_GET_ITEM(k,0))))
  2003.                ) {
  2004.         PyErr_SetString(PicklingError,
  2005.                         "Unexpected data in internal list");
  2006.         return NULL;
  2007.       }
  2008.  
  2009.       else { /* put */
  2010.         ik=PyInt_AS_LONG((PyIntObject*)k);
  2011.         if (ik >= lm || ik==0) {
  2012.           PyErr_SetString(PicklingError,
  2013.                           "Invalid get data");
  2014.           return NULL;
  2015.         }      
  2016.         have_get[ik]=1;
  2017.         if (ik < 256) rsize += 2;
  2018.         else rsize+=5;
  2019.       }
  2020.  
  2021.     }
  2022.  
  2023.   /* Now generate the result */
  2024.   UNLESS (r=PyString_FromStringAndSize(NULL,rsize)) goto err;
  2025.   s=PyString_AS_STRING((PyStringObject*)r);
  2026.  
  2027.   for (i=0; i<l; i++) {
  2028.       k=data->data[i];
  2029.  
  2030.       if (PyString_Check(k)) {
  2031.         ssize=PyString_GET_SIZE(k);
  2032.         if (ssize) {
  2033.             p=PyString_AS_STRING((PyStringObject*)k);
  2034.             while (--ssize >= 0) *s++=*p++;
  2035.           }
  2036.       }
  2037.  
  2038.       else if (PyTuple_Check(k)) { /* get */
  2039.         ik=PyInt_AS_LONG((PyIntObject*)PyTuple_GET_ITEM(k,0));
  2040.         if (ik < 256) {
  2041.           *s++ = BINGET;
  2042.           *s++ = (int)(ik & 0xff);
  2043.         }
  2044.         else {
  2045.           *s++ = LONG_BINGET;
  2046.           *s++ = (int)(ik & 0xff);
  2047.           *s++ = (int)((ik >> 8)  & 0xff);
  2048.           *s++ = (int)((ik >> 16) & 0xff);
  2049.           *s++ = (int)((ik >> 24) & 0xff);
  2050.         }
  2051.       }
  2052.  
  2053.       else { /* put */
  2054.         ik=PyInt_AS_LONG((PyIntObject*)k);
  2055.  
  2056.         if (have_get[ik]) { /* with matching get */
  2057.           if (ik < 256) {
  2058.             *s++ = BINPUT;
  2059.             *s++ = (int)(ik & 0xff);
  2060.           }
  2061.           else {
  2062.             *s++ = LONG_BINPUT;
  2063.             *s++ = (int)(ik & 0xff);
  2064.             *s++ = (int)((ik >> 8)  & 0xff);
  2065.             *s++ = (int)((ik >> 16) & 0xff);
  2066.             *s++ = (int)((ik >> 24) & 0xff);
  2067.           }
  2068.         }
  2069.       }
  2070.  
  2071.     }
  2072.  
  2073.   if (clear) {
  2074.     PyDict_Clear(self->memo);
  2075.     Pdata_clear(data,0);
  2076.   }
  2077.     
  2078.   free(have_get);
  2079.   return r;
  2080. err:
  2081.   free(have_get);
  2082.   return NULL;
  2083. }
  2084.  
  2085. static PyObject *
  2086. Pickler_dump(Picklerobject *self, PyObject *args) {
  2087.     PyObject *ob;
  2088.     int get=0;
  2089.  
  2090.     UNLESS (PyArg_ParseTuple(args, "O|i:dump", &ob, &get))
  2091.         return NULL;
  2092.  
  2093.     if (dump(self, ob) < 0)
  2094.         return NULL;
  2095.  
  2096.     if (get) return Pickle_getvalue(self, NULL);
  2097.  
  2098.     Py_INCREF(self);
  2099.     return (PyObject*)self;
  2100. }
  2101.  
  2102.  
  2103. static struct PyMethodDef Pickler_methods[] = {
  2104.   {"dump",          (PyCFunction)Pickler_dump,  1,
  2105.    "dump(object) --"
  2106.    "Write an object in pickle format to the object's pickle stream\n"
  2107.   },
  2108.   {"clear_memo",  (PyCFunction)Pickle_clear_memo,  1,
  2109.    "clear_memo() -- Clear the picklers memo"},
  2110.   {"getvalue",  (PyCFunction)Pickle_getvalue,  1,
  2111.    "getvalue() -- Finish picking a list-based pickle"},
  2112.   {NULL,                NULL}           /* sentinel */
  2113. };
  2114.  
  2115.  
  2116. static Picklerobject *
  2117. newPicklerobject(PyObject *file, int bin) {
  2118.     Picklerobject *self;
  2119.  
  2120.     UNLESS (self = PyObject_New(Picklerobject, &Picklertype))
  2121.         return NULL;
  2122.  
  2123.     self->fp = NULL;
  2124.     self->write = NULL;
  2125.     self->memo = NULL;
  2126.     self->arg = NULL;
  2127.     self->pers_func = NULL;
  2128.     self->inst_pers_func = NULL;
  2129.     self->write_buf = NULL;
  2130.     self->bin = bin;
  2131.     self->fast = 0;
  2132.     self->buf_size = 0;
  2133.     self->dispatch_table = NULL;
  2134.  
  2135.     if (file)
  2136.       Py_INCREF(file);
  2137.     else
  2138.       file=Pdata_New();
  2139.     
  2140.     UNLESS (self->file = file) 
  2141.       goto err;
  2142.  
  2143.     UNLESS (self->memo = PyDict_New()) 
  2144.        goto err;
  2145.  
  2146.     if (PyFile_Check(file)) {
  2147.         self->fp = PyFile_AsFile(file);
  2148.     if (self->fp == NULL) {
  2149.         PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  2150.         goto err;
  2151.     }
  2152.         self->write_func = write_file;
  2153.     }
  2154.     else if (PycStringIO_OutputCheck(file)) {
  2155.         self->write_func = write_cStringIO;
  2156.     }
  2157.     else if (file == Py_None) {
  2158.         self->write_func = write_none;
  2159.     }
  2160.     else {
  2161.         self->write_func = write_other;
  2162.  
  2163.         if (! Pdata_Check(file)) {
  2164.           UNLESS (self->write = PyObject_GetAttr(file, write_str)) {
  2165.             PyErr_Clear();
  2166.             PyErr_SetString(PyExc_TypeError, "argument must have 'write' "
  2167.                             "attribute");
  2168.             goto err;
  2169.           }
  2170.         }
  2171.  
  2172.         UNLESS (self->write_buf = 
  2173.             (char *)malloc(WRITE_BUF_SIZE * sizeof(char))) { 
  2174.             PyErr_NoMemory();
  2175.             goto err;
  2176.         }
  2177.     }
  2178.  
  2179.     if (PyEval_GetRestricted()) {
  2180.         /* Restricted execution, get private tables */
  2181.         PyObject *m;
  2182.  
  2183.         UNLESS (m=PyImport_Import(copy_reg_str)) goto err;
  2184.         self->dispatch_table=PyObject_GetAttr(m, dispatch_table_str);
  2185.         Py_DECREF(m);
  2186.         UNLESS (self->dispatch_table) goto err;
  2187.     }
  2188.     else {
  2189.         self->dispatch_table=dispatch_table;
  2190.         Py_INCREF(dispatch_table);
  2191.     }
  2192.  
  2193.     return self;
  2194.  
  2195. err:
  2196.     Py_DECREF((PyObject *)self);
  2197.     return NULL;
  2198. }
  2199.  
  2200.  
  2201. static PyObject *
  2202. get_Pickler(PyObject *self, PyObject *args) {
  2203.     PyObject *file=NULL;
  2204.     int bin;
  2205.  
  2206.     bin=1;
  2207.     if (! PyArg_ParseTuple(args, "|i:Pickler", &bin)) {
  2208.         PyErr_Clear();
  2209.         bin=0;
  2210.         if (! PyArg_ParseTuple(args, "O|i:Pickler", &file, &bin))
  2211.           return NULL;
  2212.       }
  2213.     return (PyObject *)newPicklerobject(file, bin);
  2214. }
  2215.  
  2216.  
  2217. static void
  2218. Pickler_dealloc(Picklerobject *self) {
  2219.     Py_XDECREF(self->write);
  2220.     Py_XDECREF(self->memo);
  2221.     Py_XDECREF(self->arg);
  2222.     Py_XDECREF(self->file);
  2223.     Py_XDECREF(self->pers_func);
  2224.     Py_XDECREF(self->inst_pers_func);
  2225.     Py_XDECREF(self->dispatch_table);
  2226.  
  2227.     if (self->write_buf) {    
  2228.         free(self->write_buf);
  2229.     }
  2230.  
  2231.     PyObject_Del(self);
  2232. }
  2233.  
  2234.  
  2235. static PyObject *
  2236. Pickler_getattr(Picklerobject *self, char *name) {
  2237.  
  2238.   switch (*name) {
  2239.   case 'p':
  2240.     if (strcmp(name, "persistent_id") == 0) {
  2241.         if (!self->pers_func) {
  2242.             PyErr_SetString(PyExc_AttributeError, name);
  2243.             return NULL;
  2244.         }
  2245.  
  2246.         Py_INCREF(self->pers_func);
  2247.         return self->pers_func;
  2248.     }
  2249.     break;
  2250.   case 'm':
  2251.     if (strcmp(name, "memo") == 0) {
  2252.         if (!self->memo) {
  2253.             PyErr_SetString(PyExc_AttributeError, name);
  2254.             return NULL;
  2255.         }
  2256.  
  2257.         Py_INCREF(self->memo);
  2258.         return self->memo;
  2259.     }
  2260.     break;
  2261.   case 'P':
  2262.     if (strcmp(name, "PicklingError") == 0) {
  2263.         Py_INCREF(PicklingError);
  2264.         return PicklingError;
  2265.     }
  2266.     break;
  2267.   case 'b':
  2268.     if (strcmp(name, "binary")==0)
  2269.       return PyInt_FromLong(self->bin);
  2270.     break;
  2271.   case 'f':
  2272.     if (strcmp(name, "fast")==0)
  2273.       return PyInt_FromLong(self->fast);
  2274.     break;
  2275.   case 'g':
  2276.     if (strcmp(name, "getvalue")==0 && ! Pdata_Check(self->file)) {
  2277.       PyErr_SetString(PyExc_AttributeError, name);
  2278.       return NULL;
  2279.     }
  2280.     break;
  2281.   }
  2282.   return Py_FindMethod(Pickler_methods, (PyObject *)self, name);
  2283. }
  2284.  
  2285.  
  2286. int 
  2287. Pickler_setattr(Picklerobject *self, char *name, PyObject *value) {
  2288.  
  2289.     if (! value) {
  2290.         PyErr_SetString(PyExc_TypeError,
  2291.                         "attribute deletion is not supported");
  2292.         return -1;
  2293.     }
  2294.   
  2295.     if (strcmp(name, "persistent_id") == 0) {
  2296.         Py_XDECREF(self->pers_func);
  2297.         self->pers_func = value;
  2298.         Py_INCREF(value);
  2299.         return 0;
  2300.     }
  2301.  
  2302.     if (strcmp(name, "inst_persistent_id") == 0) {
  2303.         Py_XDECREF(self->inst_pers_func);
  2304.         self->inst_pers_func = value;
  2305.         Py_INCREF(value);
  2306.         return 0;
  2307.     }
  2308.  
  2309.     if (strcmp(name, "memo") == 0) {
  2310.         if (! PyDict_Check(value)) {
  2311.           PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
  2312.           return -1;
  2313.         }
  2314.         Py_XDECREF(self->memo);
  2315.         self->memo = value;
  2316.         Py_INCREF(value);
  2317.         return 0;
  2318.     }
  2319.  
  2320.     if (strcmp(name, "binary")==0) {
  2321.         self->bin=PyObject_IsTrue(value);
  2322.         return 0;
  2323.     }
  2324.  
  2325.     if (strcmp(name, "fast")==0) {
  2326.         self->fast=PyObject_IsTrue(value);
  2327.         return 0;
  2328.     }
  2329.  
  2330.     PyErr_SetString(PyExc_AttributeError, name);
  2331.     return -1;
  2332. }
  2333.  
  2334.  
  2335. static char Picklertype__doc__[] =
  2336. "Objects that know how to pickle objects\n"
  2337. ;
  2338.  
  2339. static PyTypeObject Picklertype = {
  2340.     PyObject_HEAD_INIT(NULL)
  2341.     0,                            /*ob_size*/
  2342.     "Pickler",                    /*tp_name*/
  2343.     sizeof(Picklerobject),                /*tp_basicsize*/
  2344.     0,                            /*tp_itemsize*/
  2345.     /* methods */
  2346.     (destructor)Pickler_dealloc,  /*tp_dealloc*/
  2347.     (printfunc)0,         /*tp_print*/
  2348.     (getattrfunc)Pickler_getattr, /*tp_getattr*/
  2349.     (setattrfunc)Pickler_setattr, /*tp_setattr*/
  2350.     (cmpfunc)0,           /*tp_compare*/
  2351.     (reprfunc)0,          /*tp_repr*/
  2352.     0,                    /*tp_as_number*/
  2353.     0,            /*tp_as_sequence*/
  2354.     0,            /*tp_as_mapping*/
  2355.     (hashfunc)0,          /*tp_hash*/
  2356.     (ternaryfunc)0,               /*tp_call*/
  2357.     (reprfunc)0,          /*tp_str*/
  2358.  
  2359.     /* Space for future expansion */
  2360.     0L,0L,0L,0L,
  2361.     Picklertype__doc__ /* Documentation string */
  2362. };
  2363.  
  2364. static PyObject *
  2365. find_class(PyObject *py_module_name, PyObject *py_global_name, PyObject *fc) {
  2366.     PyObject *global = 0, *module;
  2367.  
  2368.     if (fc) {
  2369.       if (fc==Py_None) {
  2370.     PyErr_SetString(UnpicklingError, 
  2371.             "Global and instance pickles are not supported.");
  2372.     return NULL;
  2373.       }
  2374.       return PyObject_CallFunction(fc, "OO", py_module_name, py_global_name);
  2375.     }
  2376.  
  2377.     module = PySys_GetObject("modules");
  2378.     if (module == NULL)
  2379.       return NULL;
  2380.  
  2381.     module = PyDict_GetItem(module, py_module_name);
  2382.     if (module == NULL) {
  2383.       module = PyImport_Import(py_module_name);
  2384.       if (!module)
  2385.           return NULL;
  2386.       global = PyObject_GetAttr(module, py_global_name);
  2387.       Py_DECREF(module);
  2388.     }
  2389.     else
  2390.       global = PyObject_GetAttr(module, py_global_name);
  2391.     if (global == NULL) {
  2392.       char buf[256 + 37];
  2393.       sprintf(buf, "Failed to import class %.128s from module %.128s",
  2394.               PyString_AS_STRING((PyStringObject*)py_global_name),
  2395.               PyString_AS_STRING((PyStringObject*)py_module_name));  
  2396.       PyErr_SetString(PyExc_SystemError, buf);
  2397.       return NULL;
  2398.     }
  2399.     return global;
  2400. }
  2401.  
  2402. static int
  2403. marker(Unpicklerobject *self) {
  2404.     if (self->num_marks < 1) {
  2405.         PyErr_SetString(UnpicklingError, "could not find MARK");
  2406.         return -1;
  2407.     }
  2408.  
  2409.     return self->marks[--self->num_marks];
  2410. }
  2411.  
  2412.     
  2413. static int
  2414. load_none(Unpicklerobject *self) {
  2415.     PDATA_APPEND(self->stack, Py_None, -1);
  2416.     return 0;
  2417. }
  2418.  
  2419. static int
  2420. bad_readline(void) {
  2421.     PyErr_SetString(UnpicklingError, "pickle data was truncated");
  2422.     return -1;
  2423. }
  2424.  
  2425. static int
  2426. load_int(Unpicklerobject *self) {
  2427.     PyObject *py_int = 0;
  2428.     char *endptr, *s;
  2429.     int len, res = -1;
  2430.     long l;
  2431.  
  2432.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2433.     if (len < 2) return bad_readline();
  2434.     UNLESS (s=pystrndup(s,len)) return -1;
  2435.  
  2436.     errno = 0;
  2437.     l = strtol(s, &endptr, 0);
  2438.  
  2439.     if (errno || (*endptr != '\n') || (endptr[1] != '\0')) {
  2440.         /* Hm, maybe we've got something long.  Let's try reading
  2441.            it as a Python long object. */
  2442.         errno=0;
  2443.         UNLESS (py_int=PyLong_FromString(s,&endptr,0)) goto finally;
  2444.  
  2445.         if ((*endptr != '\n') || (endptr[1] != '\0')) {
  2446.             PyErr_SetString(PyExc_ValueError,
  2447.                             "could not convert string to int");
  2448.             goto finally;
  2449.         }
  2450.     }
  2451.     else {
  2452.         UNLESS (py_int = PyInt_FromLong(l)) goto finally;
  2453.     }
  2454.  
  2455.     free(s);
  2456.     PDATA_PUSH(self->stack, py_int, -1);
  2457.     return 0;
  2458.  
  2459. finally:
  2460.     free(s);
  2461.  
  2462.     return res;
  2463. }
  2464.  
  2465.  
  2466. static long 
  2467. calc_binint(char *s, int  x) {
  2468.     unsigned char c;
  2469.     int i;
  2470.     long l;
  2471.  
  2472.     for (i = 0, l = 0L; i < x; i++) {
  2473.         c = (unsigned char)s[i];
  2474.         l |= (long)c << (i * 8);
  2475.     }
  2476.  
  2477.     return l;
  2478. }
  2479.  
  2480.  
  2481. static int
  2482. load_binintx(Unpicklerobject *self, char *s, int  x) {
  2483.     PyObject *py_int = 0;
  2484.     long l;
  2485.  
  2486.     l = calc_binint(s, x);
  2487.  
  2488.     UNLESS (py_int = PyInt_FromLong(l))
  2489.         return -1;
  2490.  
  2491.     PDATA_PUSH(self->stack, py_int, -1);
  2492.     return 0;
  2493. }
  2494.  
  2495.  
  2496. static int
  2497. load_binint(Unpicklerobject *self) {
  2498.     char *s;
  2499.  
  2500.     if ((*self->read_func)(self, &s, 4) < 0)
  2501.         return -1;
  2502.  
  2503.     return load_binintx(self, s, 4);
  2504. }
  2505.  
  2506.  
  2507. static int
  2508. load_binint1(Unpicklerobject *self) {
  2509.     char *s;
  2510.  
  2511.     if ((*self->read_func)(self, &s, 1) < 0)
  2512.         return -1;
  2513.  
  2514.     return load_binintx(self, s, 1);
  2515. }
  2516.  
  2517.  
  2518. static int
  2519. load_binint2(Unpicklerobject *self) {
  2520.     char *s;
  2521.  
  2522.     if ((*self->read_func)(self, &s, 2) < 0)
  2523.         return -1;
  2524.  
  2525.     return load_binintx(self, s, 2);
  2526. }
  2527.     
  2528. static int
  2529. load_long(Unpicklerobject *self) {
  2530.     PyObject *l = 0;
  2531.     char *end, *s;
  2532.     int len, res = -1;
  2533.  
  2534.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2535.     if (len < 2) return bad_readline();
  2536.     UNLESS (s=pystrndup(s,len)) return -1;
  2537.  
  2538.     UNLESS (l = PyLong_FromString(s, &end, 0))
  2539.         goto finally;
  2540.  
  2541.     free(s);
  2542.     PDATA_PUSH(self->stack, l, -1);
  2543.     return 0;
  2544.  
  2545. finally:
  2546.     free(s);
  2547.  
  2548.     return res;
  2549. }
  2550.  
  2551.  
  2552. static int
  2553. load_float(Unpicklerobject *self) {
  2554.     PyObject *py_float = 0;
  2555.     char *endptr, *s;
  2556.     int len, res = -1;
  2557.     double d;
  2558.  
  2559.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2560.     if (len < 2) return bad_readline();
  2561.     UNLESS (s=pystrndup(s,len)) return -1;
  2562.  
  2563.     errno = 0;
  2564.     d = strtod(s, &endptr);
  2565.  
  2566.     if (errno || (endptr[0] != '\n') || (endptr[1] != '\0')) {
  2567.         PyErr_SetString(PyExc_ValueError, 
  2568.         "could not convert string to float");
  2569.         goto finally;
  2570.     }
  2571.  
  2572.     UNLESS (py_float = PyFloat_FromDouble(d))
  2573.         goto finally;
  2574.  
  2575.     free(s);
  2576.     PDATA_PUSH(self->stack, py_float, -1);
  2577.     return 0;
  2578.  
  2579. finally:
  2580.     free(s);
  2581.  
  2582.     return res;
  2583. }
  2584.  
  2585. static int
  2586. load_binfloat(Unpicklerobject *self) {
  2587.     PyObject *py_float = 0;
  2588.     int s, e;
  2589.     long fhi, flo;
  2590.     double x;
  2591.     char *p;
  2592.  
  2593.     if ((*self->read_func)(self, &p, 8) < 0)
  2594.         return -1;
  2595.  
  2596.     /* First byte */
  2597.     s = (*p>>7) & 1;
  2598.     e = (*p & 0x7F) << 4;
  2599.     p++;
  2600.  
  2601.     /* Second byte */
  2602.     e |= (*p>>4) & 0xF;
  2603.     fhi = (*p & 0xF) << 24;
  2604.     p++;
  2605.  
  2606.     /* Third byte */
  2607.     fhi |= (*p & 0xFF) << 16;
  2608.     p++;
  2609.  
  2610.     /* Fourth byte */
  2611.     fhi |= (*p & 0xFF) << 8;
  2612.     p++;
  2613.  
  2614.     /* Fifth byte */
  2615.     fhi |= *p & 0xFF;
  2616.     p++;
  2617.  
  2618.     /* Sixth byte */
  2619.     flo = (*p & 0xFF) << 16;
  2620.     p++;
  2621.  
  2622.     /* Seventh byte */
  2623.     flo |= (*p & 0xFF) << 8;
  2624.     p++;
  2625.  
  2626.     /* Eighth byte */
  2627.     flo |= *p & 0xFF;
  2628.  
  2629.     x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
  2630.     x /= 268435456.0; /* 2**28 */
  2631.  
  2632.     /* XXX This sadly ignores Inf/NaN */
  2633.     if (e == 0)
  2634.         e = -1022;
  2635.     else {
  2636.         x += 1.0;
  2637.         e -= 1023;
  2638.     }
  2639.     x = ldexp(x, e);
  2640.  
  2641.     if (s)
  2642.         x = -x;
  2643.  
  2644.     UNLESS (py_float = PyFloat_FromDouble(x)) return -1;
  2645.  
  2646.     PDATA_PUSH(self->stack, py_float, -1);
  2647.     return 0;
  2648. }
  2649.  
  2650. static int
  2651. load_string(Unpicklerobject *self) {
  2652.     PyObject *str = 0;
  2653.     int len, res = -1, nslash;
  2654.     char *s, q, *p;
  2655.  
  2656.     static PyObject *eval_dict = 0;
  2657.  
  2658.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2659.     if (len < 2) return bad_readline();
  2660.     UNLESS (s=pystrndup(s,len)) return -1;
  2661.  
  2662.     /* Check for unquoted quotes (evil strings) */
  2663.     q=*s;
  2664.     if (q != '"' && q != '\'') goto insecure;
  2665.     for (p=s+1, nslash=0; *p; p++) {
  2666.         if (*p==q && nslash%2==0) break;
  2667.         if (*p=='\\') nslash++;
  2668.         else nslash=0;
  2669.       }
  2670.     if (*p==q)
  2671.       {
  2672.         for (p++; *p; p++) if (*p > ' ') goto insecure;
  2673.       }
  2674.     else goto insecure;
  2675.     /********************************************/
  2676.  
  2677.     UNLESS (eval_dict)
  2678.         UNLESS (eval_dict = Py_BuildValue("{s{}}", "__builtins__"))
  2679.             goto finally;
  2680.  
  2681.     UNLESS (str = PyRun_String(s, Py_eval_input, eval_dict, eval_dict))
  2682.         goto finally;
  2683.  
  2684.     free(s);
  2685.     PDATA_PUSH(self->stack, str, -1);
  2686.     return 0;
  2687.  
  2688. finally:
  2689.     free(s);
  2690.  
  2691.     return res;
  2692.     
  2693. insecure:
  2694.     free(s);
  2695.     PyErr_SetString(PyExc_ValueError,"insecure string pickle");
  2696.     return -1;
  2697.  
  2698.  
  2699. static int
  2700. load_binstring(Unpicklerobject *self) {
  2701.     PyObject *py_string = 0;
  2702.     long l;
  2703.     char *s;
  2704.  
  2705.     if ((*self->read_func)(self, &s, 4) < 0) return -1;
  2706.  
  2707.     l = calc_binint(s, 4);
  2708.  
  2709.     if ((*self->read_func)(self, &s, l) < 0)
  2710.         return -1;
  2711.  
  2712.     UNLESS (py_string = PyString_FromStringAndSize(s, l))
  2713.         return -1;
  2714.  
  2715.     PDATA_PUSH(self->stack, py_string, -1);
  2716.     return 0;
  2717. }
  2718.  
  2719.  
  2720. static int
  2721. load_short_binstring(Unpicklerobject *self) {
  2722.     PyObject *py_string = 0;
  2723.     unsigned char l;  
  2724.     char *s;
  2725.  
  2726.     if ((*self->read_func)(self, &s, 1) < 0)
  2727.         return -1;
  2728.  
  2729.     l = (unsigned char)s[0];
  2730.  
  2731.     if ((*self->read_func)(self, &s, l) < 0) return -1;
  2732.  
  2733.     UNLESS (py_string = PyString_FromStringAndSize(s, l)) return -1;
  2734.  
  2735.     PDATA_PUSH(self->stack, py_string, -1);
  2736.     return 0;
  2737.  
  2738.  
  2739. static int
  2740. load_unicode(Unpicklerobject *self) {
  2741.     PyObject *str = 0;
  2742.     int len, res = -1;
  2743.     char *s;
  2744.  
  2745.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2746.     if (len < 2) return bad_readline();
  2747.  
  2748.     UNLESS (str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL))
  2749.         goto finally;
  2750.  
  2751.     PDATA_PUSH(self->stack, str, -1);
  2752.     return 0;
  2753.  
  2754. finally:
  2755.     return res;
  2756.  
  2757.  
  2758. static int
  2759. load_binunicode(Unpicklerobject *self) {
  2760.     PyObject *unicode;
  2761.     long l;
  2762.     char *s;
  2763.  
  2764.     if ((*self->read_func)(self, &s, 4) < 0) return -1;
  2765.  
  2766.     l = calc_binint(s, 4);
  2767.  
  2768.     if ((*self->read_func)(self, &s, l) < 0)
  2769.         return -1;
  2770.  
  2771.     UNLESS (unicode = PyUnicode_DecodeUTF8(s, l, NULL))
  2772.         return -1;
  2773.  
  2774.     PDATA_PUSH(self->stack, unicode, -1);
  2775.     return 0;
  2776. }
  2777.  
  2778.  
  2779. static int
  2780. load_tuple(Unpicklerobject *self) {
  2781.     PyObject *tup;
  2782.     int i;
  2783.  
  2784.     if ((i = marker(self)) < 0) return -1;
  2785.     UNLESS (tup=Pdata_popTuple(self->stack, i)) return -1;
  2786.     PDATA_PUSH(self->stack, tup, -1);
  2787.     return 0;
  2788. }
  2789.  
  2790. static int
  2791. load_empty_tuple(Unpicklerobject *self) {
  2792.     PyObject *tup;
  2793.  
  2794.     UNLESS (tup=PyTuple_New(0)) return -1;
  2795.     PDATA_PUSH(self->stack, tup, -1);
  2796.     return 0;
  2797. }
  2798.  
  2799. static int
  2800. load_empty_list(Unpicklerobject *self) {
  2801.     PyObject *list;
  2802.  
  2803.     UNLESS (list=PyList_New(0)) return -1;
  2804.     PDATA_PUSH(self->stack, list, -1);
  2805.     return 0;
  2806. }
  2807.  
  2808. static int
  2809. load_empty_dict(Unpicklerobject *self) {
  2810.     PyObject *dict;
  2811.  
  2812.     UNLESS (dict=PyDict_New()) return -1;
  2813.     PDATA_PUSH(self->stack, dict, -1);
  2814.     return 0;
  2815. }
  2816.  
  2817.  
  2818. static int
  2819. load_list(Unpicklerobject *self) {
  2820.     PyObject *list = 0;
  2821.     int i;
  2822.  
  2823.     if ((i = marker(self)) < 0) return -1;
  2824.     UNLESS (list=Pdata_popList(self->stack, i)) return -1;
  2825.     PDATA_PUSH(self->stack, list, -1);
  2826.     return 0;
  2827. }
  2828.  
  2829. static int
  2830. load_dict(Unpicklerobject *self) {
  2831.     PyObject *dict, *key, *value;
  2832.     int i, j, k;
  2833.  
  2834.     if ((i = marker(self)) < 0) return -1;
  2835.     j=self->stack->length;
  2836.  
  2837.     UNLESS (dict = PyDict_New()) return -1;
  2838.  
  2839.     for (k = i+1; k < j; k += 2) {
  2840.         key  =self->stack->data[k-1];
  2841.         value=self->stack->data[k  ];
  2842.         if (PyDict_SetItem(dict, key, value) < 0) {
  2843.             Py_DECREF(dict);
  2844.             return -1;
  2845.         }
  2846.     }
  2847.     Pdata_clear(self->stack, i);
  2848.     PDATA_PUSH(self->stack, dict, -1);
  2849.     return 0;
  2850. }
  2851.  
  2852. static PyObject *
  2853. Instance_New(PyObject *cls, PyObject *args) {
  2854.   int has_key;
  2855.   PyObject *safe=0, *r=0;
  2856.  
  2857.   if (PyClass_Check(cls)) {
  2858.       int l;
  2859.       
  2860.       if ((l=PyObject_Size(args)) < 0) goto err;
  2861.       UNLESS (l) {
  2862.           PyObject *__getinitargs__;
  2863.  
  2864.           UNLESS (__getinitargs__=PyObject_GetAttr(cls, __getinitargs___str)) {
  2865.               /* We have a class with no __getinitargs__, so bypass usual
  2866.                  construction  */
  2867.               PyInstanceObject *inst;
  2868.  
  2869.               PyErr_Clear();
  2870.               UNLESS (inst=PyObject_New(PyInstanceObject, &PyInstance_Type))
  2871.                 goto err;
  2872.               inst->in_class=(PyClassObject*)cls;
  2873.               Py_INCREF(cls);
  2874.               UNLESS (inst->in_dict=PyDict_New()) {
  2875.                 inst = (PyInstanceObject *) PyObject_AS_GC(inst);
  2876.                 PyObject_DEL(inst);
  2877.                 goto err;
  2878.               }
  2879.               PyObject_GC_Init(inst);
  2880.               return (PyObject *)inst;
  2881.             }
  2882.           Py_DECREF(__getinitargs__);
  2883.         }
  2884.       
  2885.       if ((r=PyInstance_New(cls, args, NULL))) return r;
  2886.       else goto err;
  2887.     }
  2888.        
  2889.   
  2890.   if ((has_key = cPickle_PyMapping_HasKey(safe_constructors, cls)) < 0)
  2891.     goto err;
  2892.     
  2893.   if (!has_key)
  2894.     if (!(safe = PyObject_GetAttr(cls, __safe_for_unpickling___str)) ||
  2895.        !PyObject_IsTrue(safe)) {
  2896.       cPickle_ErrFormat(UnpicklingError,
  2897.                         "%s is not safe for unpickling", "O", cls);
  2898.       Py_XDECREF(safe);
  2899.       return NULL;
  2900.   }
  2901.  
  2902.   if (args==Py_None) {
  2903.       /* Special case, call cls.__basicnew__() */
  2904.       PyObject *basicnew;
  2905.       
  2906.       UNLESS (basicnew=PyObject_GetAttr(cls, __basicnew___str)) return NULL;
  2907.       r=PyObject_CallObject(basicnew, NULL);
  2908.       Py_DECREF(basicnew);
  2909.       if (r) return r;
  2910.     }
  2911.  
  2912.   if ((r=PyObject_CallObject(cls, args))) return r;
  2913.  
  2914. err:
  2915.   {
  2916.     PyObject *tp, *v, *tb;
  2917.  
  2918.     PyErr_Fetch(&tp, &v, &tb);
  2919.     if ((r=Py_BuildValue("OOO",v,cls,args))) {
  2920.         Py_XDECREF(v);
  2921.         v=r;
  2922.       }
  2923.     PyErr_Restore(tp,v,tb);
  2924.   }
  2925.   return NULL;
  2926. }
  2927.   
  2928.  
  2929. static int
  2930. load_obj(Unpicklerobject *self) {
  2931.     PyObject *class, *tup, *obj=0;
  2932.     int i;
  2933.  
  2934.     if ((i = marker(self)) < 0) return -1;
  2935.     UNLESS (tup=Pdata_popTuple(self->stack, i+1)) return -1;
  2936.     PDATA_POP(self->stack, class);
  2937.     if (class) {
  2938.         obj = Instance_New(class, tup);
  2939.         Py_DECREF(class);
  2940.     }
  2941.     Py_DECREF(tup);
  2942.  
  2943.     if (! obj) return -1;
  2944.     PDATA_PUSH(self->stack, obj, -1);
  2945.     return 0;
  2946. }
  2947.  
  2948.  
  2949. static int
  2950. load_inst(Unpicklerobject *self) {
  2951.     PyObject *tup, *class=0, *obj=0, *module_name, *class_name;
  2952.     int i, len;
  2953.     char *s;
  2954.  
  2955.     if ((i = marker(self)) < 0) return -1;
  2956.  
  2957.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2958.     if (len < 2) return bad_readline();
  2959.     UNLESS (module_name = PyString_FromStringAndSize(s, len - 1)) return -1;
  2960.  
  2961.     if ((len = (*self->readline_func)(self, &s)) >= 0) {
  2962.         if (len < 2) return bad_readline();
  2963.         if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
  2964.             class = find_class(module_name, class_name, self->find_class);
  2965.             Py_DECREF(class_name);
  2966.         }
  2967.     }
  2968.     Py_DECREF(module_name);
  2969.  
  2970.     if (! class) return -1;
  2971.       
  2972.     if ((tup=Pdata_popTuple(self->stack, i))) {
  2973.         obj = Instance_New(class, tup);
  2974.         Py_DECREF(tup);
  2975.     }
  2976.     Py_DECREF(class);
  2977.  
  2978.     if (! obj) return -1;
  2979.  
  2980.     PDATA_PUSH(self->stack, obj, -1);
  2981.     return 0;
  2982. }
  2983.  
  2984.  
  2985. static int
  2986. load_global(Unpicklerobject *self) {
  2987.     PyObject *class = 0, *module_name = 0, *class_name = 0;
  2988.     int len;
  2989.     char *s;
  2990.  
  2991.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  2992.     if (len < 2) return bad_readline();
  2993.     UNLESS (module_name = PyString_FromStringAndSize(s, len - 1)) return -1;
  2994.  
  2995.     if ((len = (*self->readline_func)(self, &s)) >= 0) {
  2996.         if (len < 2) return bad_readline();
  2997.         if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
  2998.             class = find_class(module_name, class_name, self->find_class);
  2999.             Py_DECREF(class_name);
  3000.         }
  3001.     }
  3002.     Py_DECREF(module_name);
  3003.  
  3004.     if (! class) return -1;
  3005.     PDATA_PUSH(self->stack, class, -1);
  3006.     return 0;
  3007. }
  3008.  
  3009.  
  3010. static int
  3011. load_persid(Unpicklerobject *self) {
  3012.     PyObject *pid = 0;
  3013.     int len;
  3014.     char *s;
  3015.  
  3016.     if (self->pers_func) {
  3017.         if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  3018.     if (len < 2) return bad_readline();
  3019.   
  3020.         UNLESS (pid = PyString_FromStringAndSize(s, len - 1)) return -1;
  3021.  
  3022.         if (PyList_Check(self->pers_func)) {
  3023.             if (PyList_Append(self->pers_func, pid) < 0) {
  3024.                 Py_DECREF(pid);
  3025.                 return -1;
  3026.             }
  3027.         }
  3028.         else {
  3029.             ARG_TUP(self, pid);
  3030.             if (self->arg) {
  3031.                 pid = PyObject_CallObject(self->pers_func, self->arg);
  3032.                 FREE_ARG_TUP(self);
  3033.             }
  3034.         }
  3035.  
  3036.         if (! pid) return -1;
  3037.  
  3038.         PDATA_PUSH(self->stack, pid, -1);
  3039.         return 0;
  3040.     }
  3041.     else {
  3042.       PyErr_SetString(UnpicklingError,
  3043.                       "A load persistent id instruction was encountered,\n"
  3044.                       "but no persistent_load function was specified.");
  3045.       return -1;
  3046.     }
  3047. }
  3048.  
  3049. static int
  3050. load_binpersid(Unpicklerobject *self) {
  3051.     PyObject *pid = 0;
  3052.  
  3053.     if (self->pers_func) {
  3054.         PDATA_POP(self->stack, pid);
  3055.         if (! pid) return -1;
  3056.  
  3057.         if (PyList_Check(self->pers_func)) {
  3058.             if (PyList_Append(self->pers_func, pid) < 0) {
  3059.                 Py_DECREF(pid);
  3060.                 return -1;
  3061.             }
  3062.           }
  3063.         else {
  3064.             ARG_TUP(self, pid);
  3065.             if (self->arg) {
  3066.                 pid = PyObject_CallObject(self->pers_func, self->arg);
  3067.                 FREE_ARG_TUP(self);
  3068.             }
  3069.             if (! pid) return -1;
  3070.         }
  3071.  
  3072.         PDATA_PUSH(self->stack, pid, -1);
  3073.         return 0;
  3074.     }
  3075.     else {
  3076.       PyErr_SetString(UnpicklingError,
  3077.                       "A load persistent id instruction was encountered,\n"
  3078.                       "but no persistent_load function was specified.");
  3079.       return -1;
  3080.     }
  3081. }
  3082.  
  3083.  
  3084. static int
  3085. load_pop(Unpicklerobject *self) {
  3086.     int len;
  3087.  
  3088.     UNLESS ((len=self->stack->length) > 0) return stackUnderflow();
  3089.  
  3090.     /* Note that we split the (pickle.py) stack into two stacks, 
  3091.        an object stack and a mark stack. We have to be clever and
  3092.        pop the right one. We do this by looking at the top of the
  3093.        mark stack.
  3094.     */
  3095.  
  3096.     if ((self->num_marks > 0) && 
  3097.         (self->marks[self->num_marks - 1] == len))
  3098.         self->num_marks--;
  3099.     else { 
  3100.         len--;
  3101.         Py_DECREF(self->stack->data[len]);
  3102.     self->stack->length=len;
  3103.     }
  3104.  
  3105.     return 0;
  3106. }
  3107.  
  3108.  
  3109. static int
  3110. load_pop_mark(Unpicklerobject *self) {
  3111.     int i;
  3112.  
  3113.     if ((i = marker(self)) < 0)
  3114.         return -1;
  3115.  
  3116.     Pdata_clear(self->stack, i);
  3117.  
  3118.     return 0;
  3119. }
  3120.  
  3121.  
  3122. static int
  3123. load_dup(Unpicklerobject *self) {
  3124.     PyObject *last;
  3125.     int len;
  3126.  
  3127.     if ((len = self->stack->length) <= 0) return stackUnderflow();
  3128.     last=self->stack->data[len-1];
  3129.     Py_INCREF(last);
  3130.     PDATA_PUSH(self->stack, last, -1);
  3131.     return 0;
  3132. }
  3133.  
  3134.  
  3135. static int
  3136. load_get(Unpicklerobject *self) {
  3137.     PyObject *py_str = 0, *value = 0;
  3138.     int len;
  3139.     char *s;
  3140.     int rc;
  3141.  
  3142.     if ((len = (*self->readline_func)(self, &s)) < 0) return -1;
  3143.     if (len < 2) return bad_readline();
  3144.  
  3145.     UNLESS (py_str = PyString_FromStringAndSize(s, len - 1)) return -1;
  3146.  
  3147.     value = PyDict_GetItem(self->memo, py_str);
  3148.     if (! value) {
  3149.         PyErr_SetObject(BadPickleGet, py_str);
  3150.         rc = -1;
  3151.     } else {
  3152.       PDATA_APPEND(self->stack, value, -1);
  3153.       rc = 0;
  3154.     }
  3155.  
  3156.     Py_DECREF(py_str);
  3157.     return rc;
  3158. }
  3159.  
  3160.  
  3161. static int
  3162. load_binget(Unpicklerobject *self) {
  3163.     PyObject *py_key = 0, *value = 0;
  3164.     unsigned char key;
  3165.     char *s;
  3166.     int rc;
  3167.  
  3168.     if ((*self->read_func)(self, &s, 1) < 0) return -1;
  3169.  
  3170.     key = (unsigned char)s[0];
  3171.     UNLESS (py_key = PyInt_FromLong((long)key)) return -1;
  3172.     
  3173.     value = PyDict_GetItem(self->memo, py_key);
  3174.     if (! value) {
  3175.         PyErr_SetObject(BadPickleGet, py_key);
  3176.         rc = -1;
  3177.     } else {
  3178.       PDATA_APPEND(self->stack, value, -1);
  3179.       rc = 0;
  3180.     }
  3181.  
  3182.     Py_DECREF(py_key);
  3183.     return rc;
  3184. }
  3185.  
  3186.  
  3187. static int
  3188. load_long_binget(Unpicklerobject *self) {
  3189.     PyObject *py_key = 0, *value = 0;
  3190.     unsigned char c;
  3191.     char *s;
  3192.     long key;
  3193.     int rc;
  3194.  
  3195.     if ((*self->read_func)(self, &s, 4) < 0) return -1;
  3196.  
  3197.     c = (unsigned char)s[0];
  3198.     key = (long)c;
  3199.     c = (unsigned char)s[1];
  3200.     key |= (long)c << 8;
  3201.     c = (unsigned char)s[2];
  3202.     key |= (long)c << 16;
  3203.     c = (unsigned char)s[3];
  3204.     key |= (long)c << 24;
  3205.  
  3206.     UNLESS (py_key = PyInt_FromLong((long)key)) return -1;
  3207.     
  3208.     value = PyDict_GetItem(self->memo, py_key);
  3209.     if (! value) {
  3210.         PyErr_SetObject(BadPickleGet, py_key);
  3211.         rc = -1;
  3212.     } else {
  3213.       PDATA_APPEND(self->stack, value, -1);
  3214.       rc = 0;
  3215.     }
  3216.  
  3217.     Py_DECREF(py_key);
  3218.     return rc;
  3219. }
  3220.  
  3221.  
  3222. static int
  3223. load_put(Unpicklerobject *self) {
  3224.     PyObject *py_str = 0, *value = 0;
  3225.     int len, l;
  3226.     char *s;
  3227.  
  3228.     if ((l = (*self->readline_func)(self, &s)) < 0) return -1;
  3229.     if (l < 2) return bad_readline();
  3230.     UNLESS (len=self->stack->length) return stackUnderflow();
  3231.     UNLESS (py_str = PyString_FromStringAndSize(s, l - 1)) return -1;
  3232.     value=self->stack->data[len-1];
  3233.     l=PyDict_SetItem(self->memo, py_str, value);
  3234.     Py_DECREF(py_str);
  3235.     return l;
  3236. }
  3237.  
  3238.  
  3239. static int
  3240. load_binput(Unpicklerobject *self) {
  3241.     PyObject *py_key = 0, *value = 0;
  3242.     unsigned char key;
  3243.     char *s;
  3244.     int len;
  3245.  
  3246.     if ((*self->read_func)(self, &s, 1) < 0) return -1;
  3247.     UNLESS ((len=self->stack->length) > 0) return stackUnderflow();
  3248.  
  3249.     key = (unsigned char)s[0];
  3250.  
  3251.     UNLESS (py_key = PyInt_FromLong((long)key)) return -1;
  3252.     value=self->stack->data[len-1];
  3253.     len=PyDict_SetItem(self->memo, py_key, value);
  3254.     Py_DECREF(py_key);
  3255.     return len;
  3256. }
  3257.  
  3258.  
  3259. static int
  3260. load_long_binput(Unpicklerobject *self) {
  3261.     PyObject *py_key = 0, *value = 0;
  3262.     long key;
  3263.     unsigned char c;
  3264.     char *s;
  3265.     int len;
  3266.  
  3267.     if ((*self->read_func)(self, &s, 4) < 0) return -1;
  3268.     UNLESS (len=self->stack->length) return stackUnderflow();
  3269.  
  3270.     c = (unsigned char)s[0];
  3271.     key = (long)c;
  3272.     c = (unsigned char)s[1];
  3273.     key |= (long)c << 8;
  3274.     c = (unsigned char)s[2];
  3275.     key |= (long)c << 16;
  3276.     c = (unsigned char)s[3];
  3277.     key |= (long)c << 24;
  3278.  
  3279.     UNLESS (py_key = PyInt_FromLong(key)) return -1;
  3280.     value=self->stack->data[len-1];
  3281.     len=PyDict_SetItem(self->memo, py_key, value);
  3282.     Py_DECREF(py_key);
  3283.     return len;
  3284. }
  3285.  
  3286.  
  3287. static int 
  3288. do_append(Unpicklerobject *self, int  x) {
  3289.     PyObject *value = 0, *list = 0, *append_method = 0;
  3290.     int len, i;
  3291.  
  3292.     UNLESS ((len=self->stack->length) >= x && x > 0) return stackUnderflow();
  3293.     if (len==x) return 0;       /* nothing to do */
  3294.  
  3295.     list=self->stack->data[x-1];
  3296.  
  3297.     if (PyList_Check(list)) {
  3298.         PyObject *slice;
  3299.         int list_len;
  3300.        
  3301.         slice=Pdata_popList(self->stack, x);
  3302.         list_len = PyList_GET_SIZE(list);
  3303.         i=PyList_SetSlice(list, list_len, list_len, slice);
  3304.         Py_DECREF(slice);
  3305.         return i;
  3306.     }
  3307.     else {
  3308.  
  3309.         UNLESS (append_method = PyObject_GetAttr(list, append_str))
  3310.             return -1;
  3311.          
  3312.         for (i = x; i < len; i++) {
  3313.             PyObject *junk;
  3314.  
  3315.             value=self->stack->data[i];
  3316.             junk=0;
  3317.             ARG_TUP(self, value);
  3318.             if (self->arg) {
  3319.               junk = PyObject_CallObject(append_method, self->arg);
  3320.               FREE_ARG_TUP(self);
  3321.             }
  3322.             if (! junk) {
  3323.                 Pdata_clear(self->stack, i+1);
  3324.                 self->stack->length=x;
  3325.                 Py_DECREF(append_method);
  3326.                 return -1;
  3327.             }
  3328.             Py_DECREF(junk);
  3329.         }
  3330.         self->stack->length=x;
  3331.         Py_DECREF(append_method);
  3332.     }
  3333.  
  3334.     return 0;
  3335. }
  3336.  
  3337.     
  3338. static int
  3339. load_append(Unpicklerobject *self) {
  3340.     return do_append(self, self->stack->length - 1);
  3341. }
  3342.  
  3343.  
  3344. static int
  3345. load_appends(Unpicklerobject *self) {
  3346.     return do_append(self, marker(self));
  3347. }
  3348.  
  3349.  
  3350. static int
  3351. do_setitems(Unpicklerobject *self, int  x) {
  3352.     PyObject *value = 0, *key = 0, *dict = 0;
  3353.     int len, i, r=0;
  3354.  
  3355.     UNLESS ((len=self->stack->length) >= x
  3356.             && x > 0) return stackUnderflow();
  3357.  
  3358.     dict=self->stack->data[x-1];
  3359.  
  3360.     for (i = x+1; i < len; i += 2) {
  3361.         key  =self->stack->data[i-1];
  3362.         value=self->stack->data[i  ];
  3363.         if (PyObject_SetItem(dict, key, value) < 0) {
  3364.             r=-1;
  3365.             break;
  3366.         }
  3367.     }
  3368.  
  3369.     Pdata_clear(self->stack, x);
  3370.  
  3371.     return r;
  3372. }
  3373.  
  3374.  
  3375. static int
  3376. load_setitem(Unpicklerobject *self) {
  3377.     return do_setitems(self, self->stack->length - 2);
  3378. }
  3379.  
  3380. static int
  3381. load_setitems(Unpicklerobject *self) {
  3382.     return do_setitems(self, marker(self));
  3383. }
  3384.  
  3385.  
  3386. static int
  3387. load_build(Unpicklerobject *self) {
  3388.     PyObject *value = 0, *inst = 0, *instdict = 0, *d_key = 0, *d_value = 0, 
  3389.              *junk = 0, *__setstate__ = 0;
  3390.     int i, r = 0;
  3391.  
  3392.     if (self->stack->length < 2) return stackUnderflow();
  3393.     PDATA_POP(self->stack, value);
  3394.     if (! value) return -1;
  3395.     inst=self->stack->data[self->stack->length-1];
  3396.  
  3397.     if ((__setstate__ = PyObject_GetAttr(inst, __setstate___str))) {
  3398.         ARG_TUP(self, value);
  3399.         if (self->arg) {
  3400.             junk = PyObject_CallObject(__setstate__, self->arg);
  3401.             FREE_ARG_TUP(self);
  3402.         }
  3403.         Py_DECREF(__setstate__);
  3404.         if (! junk) return -1;
  3405.         Py_DECREF(junk);
  3406.         return 0;
  3407.     }
  3408.  
  3409.     PyErr_Clear();
  3410.     if ((instdict = PyObject_GetAttr(inst, __dict___str))) {
  3411.         i = 0;
  3412.         while (PyDict_Next(value, &i, &d_key, &d_value)) {
  3413.             if (PyObject_SetItem(instdict, d_key, d_value) < 0) {
  3414.                 r=-1;
  3415.                 break;
  3416.             }
  3417.         }
  3418.         Py_DECREF(instdict);
  3419.     }
  3420.     else r=-1;
  3421.  
  3422.     Py_XDECREF(value);
  3423.   
  3424.     return r;
  3425. }
  3426.  
  3427.  
  3428. static int
  3429. load_mark(Unpicklerobject *self) {
  3430.     int s;
  3431.  
  3432.     /* Note that we split the (pickle.py) stack into two stacks, an
  3433.        object stack and a mark stack. Here we push a mark onto the
  3434.        mark stack.  
  3435.     */
  3436.  
  3437.     if ((self->num_marks + 1) >= self->marks_size) {
  3438.         s=self->marks_size+20;
  3439.         if (s <= self->num_marks) s=self->num_marks + 1;
  3440.         if (self->marks == NULL)
  3441.             self->marks=(int *)malloc(s * sizeof(int));
  3442.         else
  3443.             self->marks=(int *)realloc(self->marks, s * sizeof(int));
  3444.         if (! self->marks) {
  3445.             PyErr_NoMemory();
  3446.             return -1;
  3447.         }
  3448.         self->marks_size = s;
  3449.     }
  3450.  
  3451.     self->marks[self->num_marks++] = self->stack->length;
  3452.  
  3453.     return 0;
  3454. }
  3455.  
  3456. static int
  3457. load_reduce(Unpicklerobject *self) {
  3458.     PyObject *callable = 0, *arg_tup = 0, *ob = 0;
  3459.  
  3460.     PDATA_POP(self->stack, arg_tup);
  3461.     if (! arg_tup) return -1;
  3462.     PDATA_POP(self->stack, callable);
  3463.     if (callable) {
  3464.         ob = Instance_New(callable, arg_tup);
  3465.         Py_DECREF(callable);
  3466.     }
  3467.     Py_DECREF(arg_tup);
  3468.  
  3469.     if (! ob) return -1;
  3470.    
  3471.     PDATA_PUSH(self->stack, ob, -1);
  3472.     return 0;
  3473. }
  3474.     
  3475. static PyObject *
  3476. load(Unpicklerobject *self) {
  3477.     PyObject *err = 0, *val = 0;
  3478.     char *s;
  3479.  
  3480.     self->num_marks = 0;
  3481.     if (self->stack->length) Pdata_clear(self->stack, 0);
  3482.  
  3483.     while (1) {
  3484.         if ((*self->read_func)(self, &s, 1) < 0)
  3485.             break;
  3486.  
  3487.         switch (s[0]) {
  3488.             case NONE:
  3489.                 if (load_none(self) < 0)
  3490.                     break;
  3491.                 continue;
  3492.  
  3493.             case BININT:
  3494.                  if (load_binint(self) < 0)
  3495.                      break;
  3496.                  continue;
  3497.  
  3498.             case BININT1:
  3499.                 if (load_binint1(self) < 0)
  3500.                     break;
  3501.                 continue;
  3502.  
  3503.             case BININT2:
  3504.                 if (load_binint2(self) < 0)
  3505.                     break;
  3506.                 continue;
  3507.  
  3508.             case INT:
  3509.                 if (load_int(self) < 0)
  3510.                     break;
  3511.                 continue;
  3512.  
  3513.             case LONG:
  3514.                 if (load_long(self) < 0)
  3515.                     break;
  3516.                 continue;
  3517.  
  3518.             case FLOAT:
  3519.                 if (load_float(self) < 0)
  3520.                     break;
  3521.                 continue;
  3522.  
  3523.             case BINFLOAT:
  3524.                 if (load_binfloat(self) < 0)
  3525.                     break;
  3526.                 continue;
  3527.  
  3528.             case BINSTRING:
  3529.                 if (load_binstring(self) < 0)
  3530.                     break;
  3531.                 continue;
  3532.  
  3533.             case SHORT_BINSTRING:
  3534.                 if (load_short_binstring(self) < 0)
  3535.                     break;
  3536.                 continue;
  3537.  
  3538.             case STRING:
  3539.                 if (load_string(self) < 0)
  3540.                     break;
  3541.                 continue;
  3542.  
  3543.             case UNICODE:
  3544.                 if (load_unicode(self) < 0)
  3545.                     break;
  3546.                 continue;
  3547.  
  3548.             case BINUNICODE:
  3549.                 if (load_binunicode(self) < 0)
  3550.                     break;
  3551.                 continue;
  3552.  
  3553.             case EMPTY_TUPLE:
  3554.                 if (load_empty_tuple(self) < 0)
  3555.                     break;
  3556.                 continue;
  3557.  
  3558.             case TUPLE:
  3559.                 if (load_tuple(self) < 0)
  3560.                     break;
  3561.                 continue;
  3562.  
  3563.             case EMPTY_LIST:
  3564.                 if (load_empty_list(self) < 0)
  3565.                     break;
  3566.                 continue;
  3567.  
  3568.             case LIST:
  3569.                 if (load_list(self) < 0)
  3570.                     break;
  3571.                 continue;
  3572.  
  3573.             case EMPTY_DICT:
  3574.                 if (load_empty_dict(self) < 0)
  3575.                     break;
  3576.                 continue;
  3577.  
  3578.             case DICT:
  3579.                 if (load_dict(self) < 0)
  3580.                     break;
  3581.                 continue;
  3582.  
  3583.             case OBJ:
  3584.                 if (load_obj(self) < 0)
  3585.                     break;
  3586.                 continue;
  3587.  
  3588.             case INST:
  3589.                 if (load_inst(self) < 0)
  3590.                     break;
  3591.                 continue;
  3592.  
  3593.             case GLOBAL:
  3594.                 if (load_global(self) < 0)
  3595.                     break;
  3596.                 continue;
  3597.  
  3598.             case APPEND:
  3599.                 if (load_append(self) < 0)
  3600.                     break;
  3601.                 continue;
  3602.  
  3603.             case APPENDS:
  3604.                 if (load_appends(self) < 0)
  3605.                     break;
  3606.                 continue;
  3607.    
  3608.             case BUILD:
  3609.                 if (load_build(self) < 0)
  3610.                     break;
  3611.                 continue;
  3612.   
  3613.             case DUP:
  3614.                 if (load_dup(self) < 0)
  3615.                     break;
  3616.                 continue;
  3617.  
  3618.             case BINGET:
  3619.                 if (load_binget(self) < 0)
  3620.                     break;
  3621.                 continue;
  3622.  
  3623.             case LONG_BINGET:
  3624.                 if (load_long_binget(self) < 0)
  3625.                     break;
  3626.                 continue;
  3627.          
  3628.             case GET:
  3629.                 if (load_get(self) < 0)
  3630.                     break;
  3631.                 continue;
  3632.  
  3633.             case MARK:
  3634.                 if (load_mark(self) < 0)
  3635.                     break;
  3636.                 continue;
  3637.  
  3638.             case BINPUT:
  3639.                 if (load_binput(self) < 0)
  3640.                     break;
  3641.                 continue;
  3642.  
  3643.             case LONG_BINPUT:
  3644.                 if (load_long_binput(self) < 0)
  3645.                     break;
  3646.                 continue;
  3647.          
  3648.             case PUT:
  3649.                 if (load_put(self) < 0)
  3650.                     break;
  3651.                 continue;
  3652.  
  3653.             case POP:
  3654.                 if (load_pop(self) < 0)
  3655.                     break;
  3656.                 continue;
  3657.  
  3658.             case POP_MARK:
  3659.                 if (load_pop_mark(self) < 0)
  3660.                     break;
  3661.                 continue;
  3662.  
  3663.             case SETITEM:
  3664.                 if (load_setitem(self) < 0)
  3665.                     break;
  3666.                 continue;
  3667.  
  3668.             case SETITEMS:
  3669.                 if (load_setitems(self) < 0)
  3670.                     break;
  3671.                 continue;
  3672.  
  3673.             case STOP:
  3674.                 break;
  3675.  
  3676.             case PERSID:
  3677.                 if (load_persid(self) < 0)
  3678.                     break;
  3679.                 continue;
  3680.  
  3681.             case BINPERSID:
  3682.                 if (load_binpersid(self) < 0)
  3683.                     break;
  3684.                 continue;
  3685.  
  3686.             case REDUCE:
  3687.                 if (load_reduce(self) < 0)
  3688.                     break;
  3689.                 continue;
  3690.  
  3691.             default: 
  3692.                 cPickle_ErrFormat(UnpicklingError, "invalid load key, '%s'.", 
  3693.                     "c", s[0]);
  3694.                 return NULL;
  3695.         }
  3696.  
  3697.         break;
  3698.     }
  3699.  
  3700.     if ((err = PyErr_Occurred())) {
  3701.         if (err == PyExc_EOFError) {
  3702.             PyErr_SetNone(PyExc_EOFError);
  3703.         }    
  3704.         return NULL;
  3705.     }
  3706.  
  3707.     PDATA_POP(self->stack, val);    
  3708.     return val;
  3709. }
  3710.     
  3711.  
  3712. /* No-load functions to support noload, which is used to
  3713.    find persistent references. */
  3714.  
  3715. static int
  3716. noload_obj(Unpicklerobject *self) {
  3717.     int i;
  3718.  
  3719.     if ((i = marker(self)) < 0) return -1;
  3720.     return Pdata_clear(self->stack, i+1);
  3721. }
  3722.  
  3723.  
  3724. static int
  3725. noload_inst(Unpicklerobject *self) {
  3726.     int i;
  3727.     char *s;
  3728.  
  3729.     if ((i = marker(self)) < 0) return -1;
  3730.     Pdata_clear(self->stack, i);
  3731.     if ((*self->readline_func)(self, &s) < 0) return -1;
  3732.     if ((*self->readline_func)(self, &s) < 0) return -1;
  3733.     PDATA_APPEND(self->stack, Py_None,-1);
  3734.     return 0;
  3735. }
  3736.  
  3737. static int
  3738. noload_global(Unpicklerobject *self) {
  3739.     char *s;
  3740.  
  3741.     if ((*self->readline_func)(self, &s) < 0) return -1;
  3742.     if ((*self->readline_func)(self, &s) < 0) return -1;
  3743.     PDATA_APPEND(self->stack, Py_None,-1);
  3744.     return 0;
  3745. }
  3746.  
  3747. static int
  3748. noload_reduce(Unpicklerobject *self) {
  3749.  
  3750.     if (self->stack->length < 2) return stackUnderflow();
  3751.     Pdata_clear(self->stack, self->stack->length-2);
  3752.     PDATA_APPEND(self->stack, Py_None,-1);
  3753.     return 0;
  3754. }
  3755.  
  3756. static int
  3757. noload_build(Unpicklerobject *self) {
  3758.  
  3759.   if (self->stack->length < 1) return stackUnderflow();
  3760.   Pdata_clear(self->stack, self->stack->length-1);
  3761.   return 0;
  3762. }
  3763.  
  3764.  
  3765. static PyObject *
  3766. noload(Unpicklerobject *self) {
  3767.     PyObject *err = 0, *val = 0;
  3768.     char *s;
  3769.  
  3770.     self->num_marks = 0;
  3771.     Pdata_clear(self->stack, 0);
  3772.  
  3773.     while (1) {
  3774.         if ((*self->read_func)(self, &s, 1) < 0)
  3775.             break;
  3776.  
  3777.         switch (s[0]) {
  3778.             case NONE:
  3779.                 if (load_none(self) < 0)
  3780.                     break;
  3781.                 continue;
  3782.  
  3783.             case BININT:
  3784.                  if (load_binint(self) < 0)
  3785.                      break;
  3786.                  continue;
  3787.  
  3788.             case BININT1:
  3789.                 if (load_binint1(self) < 0)
  3790.                     break;
  3791.                 continue;
  3792.  
  3793.             case BININT2:
  3794.                 if (load_binint2(self) < 0)
  3795.                     break;
  3796.                 continue;
  3797.  
  3798.             case INT:
  3799.                 if (load_int(self) < 0)
  3800.                     break;
  3801.                 continue;
  3802.  
  3803.             case LONG:
  3804.                 if (load_long(self) < 0)
  3805.                     break;
  3806.                 continue;
  3807.  
  3808.             case FLOAT:
  3809.                 if (load_float(self) < 0)
  3810.                     break;
  3811.                 continue;
  3812.  
  3813.             case BINFLOAT:
  3814.                 if (load_binfloat(self) < 0)
  3815.                     break;
  3816.                 continue;
  3817.  
  3818.             case BINSTRING:
  3819.                 if (load_binstring(self) < 0)
  3820.                     break;
  3821.                 continue;
  3822.  
  3823.             case SHORT_BINSTRING:
  3824.                 if (load_short_binstring(self) < 0)
  3825.                     break;
  3826.                 continue;
  3827.  
  3828.             case STRING:
  3829.                 if (load_string(self) < 0)
  3830.                     break;
  3831.                 continue;
  3832.  
  3833.             case UNICODE:
  3834.                 if (load_unicode(self) < 0)
  3835.                     break;
  3836.                 continue;
  3837.  
  3838.             case BINUNICODE:
  3839.                 if (load_binunicode(self) < 0)
  3840.                     break;
  3841.                 continue;
  3842.  
  3843.             case EMPTY_TUPLE:
  3844.                 if (load_empty_tuple(self) < 0)
  3845.                     break;
  3846.                 continue;
  3847.  
  3848.             case TUPLE:
  3849.                 if (load_tuple(self) < 0)
  3850.                     break;
  3851.                 continue;
  3852.  
  3853.             case EMPTY_LIST:
  3854.                 if (load_empty_list(self) < 0)
  3855.                     break;
  3856.                 continue;
  3857.  
  3858.             case LIST:
  3859.                 if (load_list(self) < 0)
  3860.                     break;
  3861.                 continue;
  3862.  
  3863.             case EMPTY_DICT:
  3864.                 if (load_empty_dict(self) < 0)
  3865.                     break;
  3866.                 continue;
  3867.  
  3868.             case DICT:
  3869.                 if (load_dict(self) < 0)
  3870.                     break;
  3871.                 continue;
  3872.  
  3873.             case OBJ:
  3874.                 if (noload_obj(self) < 0)
  3875.                     break;
  3876.                 continue;
  3877.  
  3878.             case INST:
  3879.                 if (noload_inst(self) < 0)
  3880.                     break;
  3881.                 continue;
  3882.  
  3883.             case GLOBAL:
  3884.                 if (noload_global(self) < 0)
  3885.                     break;
  3886.                 continue;
  3887.  
  3888.             case APPEND:
  3889.                 if (load_append(self) < 0)
  3890.                     break;
  3891.                 continue;
  3892.  
  3893.             case APPENDS:
  3894.                 if (load_appends(self) < 0)
  3895.                     break;
  3896.                 continue;
  3897.    
  3898.             case BUILD:
  3899.                 if (noload_build(self) < 0)
  3900.                     break;
  3901.                 continue;
  3902.   
  3903.             case DUP:
  3904.                 if (load_dup(self) < 0)
  3905.                     break;
  3906.                 continue;
  3907.  
  3908.             case BINGET:
  3909.                 if (load_binget(self) < 0)
  3910.                     break;
  3911.                 continue;
  3912.  
  3913.             case LONG_BINGET:
  3914.                 if (load_long_binget(self) < 0)
  3915.                     break;
  3916.                 continue;
  3917.          
  3918.             case GET:
  3919.                 if (load_get(self) < 0)
  3920.                     break;
  3921.                 continue;
  3922.  
  3923.             case MARK:
  3924.                 if (load_mark(self) < 0)
  3925.                     break;
  3926.                 continue;
  3927.  
  3928.             case BINPUT:
  3929.                 if (load_binput(self) < 0)
  3930.                     break;
  3931.                 continue;
  3932.  
  3933.             case LONG_BINPUT:
  3934.                 if (load_long_binput(self) < 0)
  3935.                     break;
  3936.                 continue;
  3937.          
  3938.             case PUT:
  3939.                 if (load_put(self) < 0)
  3940.                     break;
  3941.                 continue;
  3942.  
  3943.             case POP:
  3944.                 if (load_pop(self) < 0)
  3945.                     break;
  3946.                 continue;
  3947.  
  3948.             case POP_MARK:
  3949.                 if (load_pop_mark(self) < 0)
  3950.                     break;
  3951.                 continue;
  3952.  
  3953.             case SETITEM:
  3954.                 if (load_setitem(self) < 0)
  3955.                     break;
  3956.                 continue;
  3957.  
  3958.             case SETITEMS:
  3959.                 if (load_setitems(self) < 0)
  3960.                     break;
  3961.                 continue;
  3962.  
  3963.             case STOP:
  3964.                 break;
  3965.  
  3966.             case PERSID:
  3967.                 if (load_persid(self) < 0)
  3968.                     break;
  3969.                 continue;
  3970.  
  3971.             case BINPERSID:
  3972.                 if (load_binpersid(self) < 0)
  3973.                     break;
  3974.                 continue;
  3975.  
  3976.             case REDUCE:
  3977.                 if (noload_reduce(self) < 0)
  3978.                     break;
  3979.                 continue;
  3980.  
  3981.             default: 
  3982.                 cPickle_ErrFormat(UnpicklingError, "invalid load key, '%s'.", 
  3983.                     "c", s[0]);
  3984.                 return NULL;
  3985.         }
  3986.  
  3987.         break;
  3988.     }
  3989.  
  3990.     if ((err = PyErr_Occurred())) {
  3991.         if (err == PyExc_EOFError) {
  3992.             PyErr_SetNone(PyExc_EOFError);
  3993.         }    
  3994.         return NULL;
  3995.     }
  3996.  
  3997.     PDATA_POP(self->stack, val);    
  3998.     return val;
  3999. }
  4000.     
  4001.  
  4002. static PyObject *
  4003. Unpickler_load(Unpicklerobject *self, PyObject *args) {
  4004.     UNLESS (PyArg_ParseTuple(args, ":load")) 
  4005.         return NULL;
  4006.  
  4007.     return load(self);
  4008. }
  4009.  
  4010. static PyObject *
  4011. Unpickler_noload(Unpicklerobject *self, PyObject *args) {
  4012.     UNLESS (PyArg_ParseTuple(args, ":noload")) 
  4013.         return NULL;
  4014.  
  4015.     return noload(self);
  4016. }
  4017.  
  4018.  
  4019. static struct PyMethodDef Unpickler_methods[] = {
  4020.   {"load",         (PyCFunction)Unpickler_load,   1,
  4021.    "load() -- Load a pickle"
  4022.   },
  4023.   {"noload",         (PyCFunction)Unpickler_noload,   1,
  4024.    "noload() -- not load a pickle, but go through most of the motions\n"
  4025.    "\n"
  4026.    "This function can be used to read past a pickle without instantiating\n"
  4027.    "any objects or importing any modules.  It can also be used to find all\n"
  4028.    "persistent references without instantiating any objects or importing\n"
  4029.    "any modules.\n"
  4030.   },
  4031.   {NULL,              NULL}           /* sentinel */
  4032. };
  4033.  
  4034.  
  4035. static Unpicklerobject *
  4036. newUnpicklerobject(PyObject *f) {
  4037.     Unpicklerobject *self;
  4038.  
  4039.     UNLESS (self = PyObject_New(Unpicklerobject, &Unpicklertype))
  4040.         return NULL;
  4041.  
  4042.     self->file = NULL;
  4043.     self->arg = NULL;
  4044.     self->stack = (Pdata*)Pdata_New();
  4045.     self->pers_func = NULL;
  4046.     self->last_string = NULL;
  4047.     self->marks = NULL;
  4048.     self->num_marks = 0;
  4049.     self->marks_size = 0;
  4050.     self->buf_size = 0;
  4051.     self->read = NULL;
  4052.     self->readline = NULL;
  4053.     self->safe_constructors = NULL;
  4054.     self->find_class = NULL;
  4055.  
  4056.     UNLESS (self->memo = PyDict_New()) 
  4057.        goto err;
  4058.  
  4059.     Py_INCREF(f);
  4060.     self->file = f;
  4061.  
  4062.     /* Set read, readline based on type of f */
  4063.     if (PyFile_Check(f)) {
  4064.         self->fp = PyFile_AsFile(f);
  4065.     if (self->fp == NULL) {
  4066.         PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  4067.         goto err;
  4068.     }
  4069.         self->read_func = read_file;
  4070.         self->readline_func = readline_file;
  4071.     }
  4072.     else if (PycStringIO_InputCheck(f)) {
  4073.         self->fp = NULL;
  4074.         self->read_func = read_cStringIO;
  4075.         self->readline_func = readline_cStringIO;
  4076.     }
  4077.     else {
  4078.  
  4079.         self->fp = NULL;
  4080.         self->read_func = read_other;
  4081.         self->readline_func = readline_other;
  4082.  
  4083.         UNLESS ((self->readline = PyObject_GetAttr(f, readline_str)) &&
  4084.             (self->read = PyObject_GetAttr(f, read_str))) {
  4085.             PyErr_Clear();
  4086.             PyErr_SetString( PyExc_TypeError, "argument must have 'read' and "
  4087.                 "'readline' attributes" );
  4088.             goto err;
  4089.         }
  4090.     }
  4091.  
  4092.     if (PyEval_GetRestricted()) {
  4093.         /* Restricted execution, get private tables */
  4094.         PyObject *m;
  4095.  
  4096.         UNLESS (m=PyImport_Import(copy_reg_str)) goto err;
  4097.         self->safe_constructors=PyObject_GetAttr(m, safe_constructors_str);
  4098.         Py_DECREF(m);
  4099.         UNLESS (self->safe_constructors) goto err;
  4100.     }
  4101.     else {
  4102.         self->safe_constructors=safe_constructors;
  4103.         Py_INCREF(safe_constructors);
  4104.     }
  4105.  
  4106.     return self;
  4107.  
  4108. err:
  4109.     Py_DECREF((PyObject *)self);
  4110.     return NULL;
  4111. }
  4112.  
  4113.  
  4114. static PyObject *
  4115. get_Unpickler(PyObject *self, PyObject *args) {
  4116.     PyObject *file;
  4117.   
  4118.     UNLESS (PyArg_ParseTuple(args, "O:Unpickler", &file))
  4119.         return NULL;
  4120.     return (PyObject *)newUnpicklerobject(file);
  4121. }
  4122.  
  4123.  
  4124. static void
  4125. Unpickler_dealloc(Unpicklerobject *self) {
  4126.     Py_XDECREF(self->readline);
  4127.     Py_XDECREF(self->read);
  4128.     Py_XDECREF(self->file);
  4129.     Py_XDECREF(self->memo);
  4130.     Py_XDECREF(self->stack);
  4131.     Py_XDECREF(self->pers_func);
  4132.     Py_XDECREF(self->arg);
  4133.     Py_XDECREF(self->last_string);
  4134.     Py_XDECREF(self->safe_constructors);
  4135.  
  4136.     if (self->marks) {
  4137.         free(self->marks);
  4138.     }
  4139.  
  4140.     if (self->buf_size) {
  4141.         free(self->buf);
  4142.     }
  4143.     
  4144.     PyObject_Del(self);
  4145. }
  4146.  
  4147.  
  4148. static PyObject *
  4149. Unpickler_getattr(Unpicklerobject *self, char *name) {
  4150.     if (!strcmp(name, "persistent_load")) {
  4151.         if (!self->pers_func) {
  4152.             PyErr_SetString(PyExc_AttributeError, name);
  4153.             return NULL;
  4154.         }
  4155.  
  4156.         Py_INCREF(self->pers_func);
  4157.         return self->pers_func;
  4158.     }
  4159.  
  4160.     if (!strcmp(name, "find_global")) {
  4161.         if (!self->find_class) {
  4162.             PyErr_SetString(PyExc_AttributeError, name);
  4163.             return NULL;
  4164.         }
  4165.  
  4166.         Py_INCREF(self->find_class);
  4167.         return self->find_class;
  4168.     }
  4169.  
  4170.     if (!strcmp(name, "memo")) {
  4171.         if (!self->memo) {
  4172.             PyErr_SetString(PyExc_AttributeError, name);
  4173.             return NULL;
  4174.         }
  4175.  
  4176.         Py_INCREF(self->memo);
  4177.         return self->memo;
  4178.     }
  4179.  
  4180.     if (!strcmp(name, "UnpicklingError")) {
  4181.         Py_INCREF(UnpicklingError);
  4182.         return UnpicklingError;
  4183.     }
  4184.  
  4185.     return Py_FindMethod(Unpickler_methods, (PyObject *)self, name);
  4186. }
  4187.  
  4188.  
  4189. static int
  4190. Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value) {
  4191.  
  4192.     if (!strcmp(name, "persistent_load")) {
  4193.         Py_XDECREF(self->pers_func);
  4194.         self->pers_func = value;
  4195.         Py_XINCREF(value);
  4196.         return 0;
  4197.     }
  4198.  
  4199.     if (!strcmp(name, "find_global")) {
  4200.         Py_XDECREF(self->find_class);
  4201.         self->find_class = value;
  4202.         Py_XINCREF(value);
  4203.         return 0;
  4204.     }
  4205.  
  4206.     if (! value) {
  4207.         PyErr_SetString(PyExc_TypeError,
  4208.                         "attribute deletion is not supported");
  4209.         return -1;
  4210.     }
  4211.  
  4212.     if (strcmp(name, "memo") == 0) {
  4213.         if (! PyDict_Check(value)) {
  4214.           PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
  4215.           return -1;
  4216.         }
  4217.         Py_XDECREF(self->memo);
  4218.         self->memo = value;
  4219.         Py_INCREF(value);
  4220.         return 0;
  4221.     }
  4222.  
  4223.     PyErr_SetString(PyExc_AttributeError, name);
  4224.     return -1;
  4225. }
  4226.  
  4227.  
  4228. static PyObject *
  4229. cpm_dump(PyObject *self, PyObject *args) {
  4230.     PyObject *ob, *file, *res = NULL;
  4231.     Picklerobject *pickler = 0;
  4232.     int bin = 0;
  4233.  
  4234.     UNLESS (PyArg_ParseTuple(args, "OO|i", &ob, &file, &bin))
  4235.         goto finally;
  4236.  
  4237.     UNLESS (pickler = newPicklerobject(file, bin))
  4238.         goto finally;
  4239.  
  4240.     if (dump(pickler, ob) < 0)
  4241.         goto finally;
  4242.  
  4243.     Py_INCREF(Py_None);
  4244.     res = Py_None;
  4245.  
  4246. finally:
  4247.     Py_XDECREF(pickler);
  4248.  
  4249.     return res;
  4250. }
  4251.  
  4252.  
  4253. static PyObject *
  4254. cpm_dumps(PyObject *self, PyObject *args) {
  4255.     PyObject *ob, *file = 0, *res = NULL;
  4256.     Picklerobject *pickler = 0;
  4257.     int bin = 0;
  4258.  
  4259.     UNLESS (PyArg_ParseTuple(args, "O|i:dumps", &ob, &bin))
  4260.         goto finally;
  4261.  
  4262.     UNLESS (file = PycStringIO->NewOutput(128))
  4263.         goto finally;
  4264.  
  4265.     UNLESS (pickler = newPicklerobject(file, bin))
  4266.         goto finally;
  4267.  
  4268.     if (dump(pickler, ob) < 0)
  4269.         goto finally;
  4270.  
  4271.     res = PycStringIO->cgetvalue(file);
  4272.  
  4273. finally:
  4274.     Py_XDECREF(pickler);
  4275.     Py_XDECREF(file);
  4276.  
  4277.     return res;
  4278. }  
  4279.   
  4280.  
  4281. static PyObject *
  4282. cpm_load(PyObject *self, PyObject *args) {
  4283.     Unpicklerobject *unpickler = 0;
  4284.     PyObject *ob, *res = NULL;
  4285.  
  4286.     UNLESS (PyArg_ParseTuple(args, "O:load", &ob))
  4287.         goto finally;
  4288.  
  4289.     UNLESS (unpickler = newUnpicklerobject(ob))
  4290.         goto finally;
  4291.  
  4292.     res = load(unpickler);
  4293.  
  4294. finally:
  4295.     Py_XDECREF(unpickler);
  4296.  
  4297.     return res;
  4298. }
  4299.  
  4300.  
  4301. static PyObject *
  4302. cpm_loads(PyObject *self, PyObject *args) {
  4303.     PyObject *ob, *file = 0, *res = NULL;
  4304.     Unpicklerobject *unpickler = 0;
  4305.  
  4306.     UNLESS (PyArg_ParseTuple(args, "S:loads", &ob))
  4307.         goto finally;
  4308.  
  4309.     UNLESS (file = PycStringIO->NewInput(ob))
  4310.         goto finally;
  4311.   
  4312.     UNLESS (unpickler = newUnpicklerobject(file))
  4313.         goto finally;
  4314.  
  4315.     res = load(unpickler);
  4316.  
  4317. finally:
  4318.     Py_XDECREF(file);
  4319.     Py_XDECREF(unpickler);
  4320.  
  4321.     return res;
  4322. }
  4323.  
  4324.  
  4325. static char Unpicklertype__doc__[] = 
  4326. "Objects that know how to unpickle";
  4327.  
  4328. static PyTypeObject Unpicklertype = {
  4329.     PyObject_HEAD_INIT(NULL)
  4330.     0,                            /*ob_size*/
  4331.     "Unpickler",                  /*tp_name*/
  4332.     sizeof(Unpicklerobject),              /*tp_basicsize*/
  4333.     0,                            /*tp_itemsize*/
  4334.     /* methods */
  4335.     (destructor)Unpickler_dealloc,        /*tp_dealloc*/
  4336.     (printfunc)0,         /*tp_print*/
  4337.     (getattrfunc)Unpickler_getattr,       /*tp_getattr*/
  4338.     (setattrfunc)Unpickler_setattr,       /*tp_setattr*/
  4339.     (cmpfunc)0,           /*tp_compare*/
  4340.     (reprfunc)0,          /*tp_repr*/
  4341.     0,                    /*tp_as_number*/
  4342.     0,            /*tp_as_sequence*/
  4343.     0,            /*tp_as_mapping*/
  4344.     (hashfunc)0,          /*tp_hash*/
  4345.     (ternaryfunc)0,               /*tp_call*/
  4346.     (reprfunc)0,          /*tp_str*/
  4347.  
  4348.     /* Space for future expansion */
  4349.     0L,0L,0L,0L,
  4350.     Unpicklertype__doc__ /* Documentation string */
  4351. };
  4352.  
  4353. static struct PyMethodDef cPickle_methods[] = {
  4354.   {"dump",         (PyCFunction)cpm_dump,         1,
  4355.    "dump(object, file, [binary]) --"
  4356.    "Write an object in pickle format to the given file\n"
  4357.    "\n"
  4358.    "If the optional argument, binary, is provided and is true, then the\n"
  4359.    "pickle will be written in binary format, which is more space and\n"
  4360.    "computationally efficient. \n"
  4361.   },
  4362.   {"dumps",        (PyCFunction)cpm_dumps,        1,
  4363.    "dumps(object, [binary]) --"
  4364.    "Return a string containing an object in pickle format\n"
  4365.    "\n"
  4366.    "If the optional argument, binary, is provided and is true, then the\n"
  4367.    "pickle will be written in binary format, which is more space and\n"
  4368.    "computationally efficient. \n"
  4369.   },
  4370.   {"load",         (PyCFunction)cpm_load,         1,
  4371.    "load(file) -- Load a pickle from the given file"},
  4372.   {"loads",        (PyCFunction)cpm_loads,        1,
  4373.    "loads(string) -- Load a pickle from the given string"},
  4374.   {"Pickler",      (PyCFunction)get_Pickler,      1,
  4375.    "Pickler(file, [binary]) -- Create a pickler\n"
  4376.    "\n"
  4377.    "If the optional argument, binary, is provided and is true, then\n"
  4378.    "pickles will be written in binary format, which is more space and\n"
  4379.    "computationally efficient. \n"
  4380.   },
  4381.   {"Unpickler",    (PyCFunction)get_Unpickler,    1,
  4382.    "Unpickler(file) -- Create an unpickler"},
  4383.   { NULL, NULL }
  4384. };
  4385.  
  4386. static int
  4387. init_stuff(PyObject *module_dict) {
  4388.     PyObject *string, *copy_reg, *t, *r;
  4389.  
  4390. #define INIT_STR(S) UNLESS(S ## _str=PyString_FromString(#S)) return -1;
  4391.  
  4392.     INIT_STR(__class__);
  4393.     INIT_STR(__getinitargs__);
  4394.     INIT_STR(__dict__);
  4395.     INIT_STR(__getstate__);
  4396.     INIT_STR(__setstate__);
  4397.     INIT_STR(__name__);
  4398.     INIT_STR(__main__);
  4399.     INIT_STR(__reduce__);
  4400.     INIT_STR(write);
  4401.     INIT_STR(__safe_for_unpickling__);
  4402.     INIT_STR(append);
  4403.     INIT_STR(read);
  4404.     INIT_STR(readline);
  4405.     INIT_STR(copy_reg);
  4406.     INIT_STR(dispatch_table);
  4407.     INIT_STR(safe_constructors);
  4408.     INIT_STR(__basicnew__);
  4409.     UNLESS (empty_str=PyString_FromString("")) return -1;
  4410.  
  4411.     UNLESS (copy_reg = PyImport_ImportModule("copy_reg"))
  4412.         return -1;
  4413.  
  4414.     /* These next few are special because we want to use different
  4415.        ones in restricted mode. */
  4416.  
  4417.     UNLESS (dispatch_table = PyObject_GetAttr(copy_reg, dispatch_table_str))
  4418.         return -1;
  4419.  
  4420.     UNLESS (safe_constructors = PyObject_GetAttr(copy_reg,
  4421.                                                 safe_constructors_str))
  4422.         return -1;
  4423.  
  4424.     Py_DECREF(copy_reg);
  4425.  
  4426.     /* Down to here ********************************** */
  4427.  
  4428.     UNLESS (string = PyImport_ImportModule("string"))
  4429.         return -1;
  4430.  
  4431.     UNLESS (atol_func = PyObject_GetAttrString(string, "atol"))
  4432.         return -1;
  4433.  
  4434.     Py_DECREF(string);
  4435.  
  4436.     UNLESS (empty_tuple = PyTuple_New(0))
  4437.         return -1;
  4438.  
  4439.     /* Ugh */
  4440.     UNLESS (t=PyImport_ImportModule("__builtin__")) return -1;
  4441.     if (PyDict_SetItemString(module_dict, "__builtins__", t) < 0)
  4442.       return -1;
  4443.  
  4444.     UNLESS (t=PyDict_New()) return -1;
  4445.     UNLESS (r=PyRun_String(
  4446.        "def __init__(self, *args): self.args=args\n\n"
  4447.        "def __str__(self):\n"
  4448.        "  return self.args and ('%s' % self.args[0]) or '(what)'\n",
  4449.        Py_file_input,
  4450.        module_dict, t) ) return -1;
  4451.     Py_DECREF(r);
  4452.  
  4453.     UNLESS (PickleError = PyErr_NewException("cPickle.PickleError", NULL, t))
  4454.       return -1;
  4455.  
  4456.     Py_DECREF(t);
  4457.     
  4458.  
  4459.     UNLESS (PicklingError = PyErr_NewException("cPickle.PicklingError", 
  4460.                            PickleError, NULL))
  4461.       return -1;
  4462.  
  4463.     UNLESS (t=PyDict_New()) return -1;
  4464.     UNLESS (r=PyRun_String(
  4465.        "def __init__(self, *args): self.args=args\n\n"
  4466.        "def __str__(self):\n"
  4467.        "  a=self.args\n"
  4468.        "  a=a and type(a[0]) or '(what)'\n"
  4469.        "  return 'Cannot pickle %s objects' % a\n"
  4470.        , Py_file_input,
  4471.        module_dict, t) ) return -1;
  4472.     Py_DECREF(r);
  4473.  
  4474.     UNLESS (UnpickleableError = PyErr_NewException(
  4475.                 "cPickle.UnpickleableError", PicklingError, t))
  4476.       return -1;
  4477.  
  4478.     Py_DECREF(t);
  4479.  
  4480.     UNLESS (UnpicklingError = PyErr_NewException("cPickle.UnpicklingError", 
  4481.                                 PickleError, NULL))
  4482.       return -1;
  4483.  
  4484.     if (PyDict_SetItemString(module_dict, "PickleError", 
  4485.         PickleError) < 0)
  4486.         return -1;
  4487.  
  4488.     if (PyDict_SetItemString(module_dict, "PicklingError", 
  4489.         PicklingError) < 0)
  4490.         return -1;
  4491.  
  4492.     if (PyDict_SetItemString(module_dict, "UnpicklingError",
  4493.         UnpicklingError) < 0)
  4494.         return -1;
  4495.  
  4496.     if (PyDict_SetItemString(module_dict, "UnpickleableError",
  4497.         UnpickleableError) < 0)
  4498.         return -1;
  4499.  
  4500.     UNLESS (BadPickleGet = PyString_FromString("cPickle.BadPickleGet"))
  4501.         return -1;
  4502.  
  4503.     if (PyDict_SetItemString(module_dict, "BadPickleGet",
  4504.         BadPickleGet) < 0)
  4505.         return -1;
  4506.  
  4507.     PycString_IMPORT;
  4508.  
  4509.     return 0;
  4510. }
  4511.  
  4512. #ifndef DL_EXPORT    /* declarations for DLL import/export */
  4513. #define DL_EXPORT(RTYPE) RTYPE
  4514. #endif
  4515. DL_EXPORT(void)
  4516. initcPickle(void) {
  4517.     PyObject *m, *d, *di, *v, *k;
  4518.     int i;
  4519.     char *rev="1.71";
  4520.     PyObject *format_version;
  4521.     PyObject *compatible_formats;
  4522.  
  4523.     Picklertype.ob_type = &PyType_Type;
  4524.     Unpicklertype.ob_type = &PyType_Type;
  4525.     PdataType.ob_type = &PyType_Type;
  4526.  
  4527.     /* Initialize some pieces. We need to do this before module creation, 
  4528.        so we're forced to use a temporary dictionary. :( 
  4529.     */
  4530.     di=PyDict_New();
  4531.     if (!di) return;
  4532.     if (init_stuff(di) < 0) return;
  4533.  
  4534.     /* Create the module and add the functions */
  4535.     m = Py_InitModule4("cPickle", cPickle_methods,
  4536.                      cPickle_module_documentation,
  4537.                      (PyObject*)NULL,PYTHON_API_VERSION);
  4538.  
  4539.     /* Add some symbolic constants to the module */
  4540.     d = PyModule_GetDict(m);
  4541.     PyDict_SetItemString(d,"__version__", v = PyString_FromString(rev));
  4542.     Py_XDECREF(v);
  4543.  
  4544.     /* Copy data from di. Waaa. */
  4545.     for (i=0; PyDict_Next(di, &i, &k, &v); ) {
  4546.         if (PyObject_SetItem(d, k, v) < 0) {
  4547.             Py_DECREF(di);
  4548.             return;
  4549.         }
  4550.     }
  4551.     Py_DECREF(di);
  4552.  
  4553.     format_version = PyString_FromString("1.3");
  4554.     compatible_formats = Py_BuildValue("[sss]", "1.0", "1.1", "1.2");
  4555.  
  4556.     PyDict_SetItemString(d, "format_version", format_version);
  4557.     PyDict_SetItemString(d, "compatible_formats", compatible_formats);
  4558.     Py_XDECREF(format_version);
  4559.     Py_XDECREF(compatible_formats);
  4560. }
  4561.