]> git.proxmox.com Git - mirror_edk2.git/commitdiff
AppPkg|Python: Files from the Python 2.7.2 distribution that must be modified to...
authordarylm503 <darylm503@6f19259b-4bc3-4df7-8a09-765794883524>
Sun, 11 Sep 2011 20:04:18 +0000 (20:04 +0000)
committerdarylm503 <darylm503@6f19259b-4bc3-4df7-8a09-765794883524>
Sun, 11 Sep 2011 20:04:18 +0000 (20:04 +0000)
Signed-off-by: duanev@gmail.com
Reviewed-by: darylm503
git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@12322 6f19259b-4bc3-4df7-8a09-765794883524

AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Include/pyport.h [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h [new file with mode: 0644]
AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c [new file with mode: 0644]

diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h b/AppPkg/Applications/Python/PyMod-2.7.2/Include/fileobject.h
new file mode 100644 (file)
index 0000000..c5d15b1
--- /dev/null
@@ -0,0 +1,90 @@
+\r
+/* File object interface */\r
+\r
+#ifndef Py_FILEOBJECT_H\r
+#define Py_FILEOBJECT_H\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    FILE *f_fp;\r
+    PyObject *f_name;\r
+    PyObject *f_mode;\r
+    int (*f_close)(FILE *);\r
+    int f_softspace;            /* Flag used by 'print' command */\r
+    int f_binary;               /* Flag which indicates whether the file is\r
+                               open in binary (1) or text (0) mode */\r
+    char* f_buf;                /* Allocated readahead buffer */\r
+    char* f_bufend;             /* Points after last occupied position */\r
+    char* f_bufptr;             /* Current buffer position */\r
+    char *f_setbuf;             /* Buffer for setbuf(3) and setvbuf(3) */\r
+    int f_univ_newline;         /* Handle any newline convention */\r
+    int f_newlinetypes;         /* Types of newlines seen */\r
+    int f_skipnextlf;           /* Skip next \n */\r
+    PyObject *f_encoding;\r
+    PyObject *f_errors;\r
+    PyObject *weakreflist; /* List of weak references */\r
+    int unlocked_count;         /* Num. currently running sections of code\r
+                               using f_fp with the GIL released. */\r
+    int readable;\r
+    int writable;\r
+} PyFileObject;\r
+\r
+PyAPI_DATA(PyTypeObject) PyFile_Type;\r
+\r
+#define PyFile_Check(op) PyObject_TypeCheck(op, &PyFile_Type)\r
+#define PyFile_CheckExact(op) (Py_TYPE(op) == &PyFile_Type)\r
+\r
+PyAPI_FUNC(PyObject *) PyFile_FromString(char *, char *);\r
+PyAPI_FUNC(void) PyFile_SetBufSize(PyObject *, int);\r
+PyAPI_FUNC(int) PyFile_SetEncoding(PyObject *, const char *);\r
+PyAPI_FUNC(int) PyFile_SetEncodingAndErrors(PyObject *, const char *, char *errors);\r
+PyAPI_FUNC(PyObject *) PyFile_FromFile(FILE *, char *, char *,\r
+                                             int (*)(FILE *));\r
+PyAPI_FUNC(FILE *) PyFile_AsFile(PyObject *);\r
+PyAPI_FUNC(void) PyFile_IncUseCount(PyFileObject *);\r
+PyAPI_FUNC(void) PyFile_DecUseCount(PyFileObject *);\r
+PyAPI_FUNC(PyObject *) PyFile_Name(PyObject *);\r
+PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);\r
+PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);\r
+PyAPI_FUNC(int) PyFile_SoftSpace(PyObject *, int);\r
+PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);\r
+PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *);\r
+\r
+/* The default encoding used by the platform file system APIs\r
+   If non-NULL, this is different than the default encoding for strings\r
+*/\r
+PyAPI_DATA(const char *) Py_FileSystemDefaultEncoding;\r
+\r
+/* Routines to replace fread() and fgets() which accept any of \r, \n\r
+   or \r\n as line terminators.\r
+*/\r
+#define PY_STDIOTEXTMODE "b"\r
+char *Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);\r
+size_t Py_UniversalNewlineFread(char *, size_t, FILE *, PyObject *);\r
+\r
+/* A routine to do sanity checking on the file mode string.  returns\r
+   non-zero on if an exception occurred\r
+*/\r
+int _PyFile_SanitizeMode(char *mode);\r
+\r
+//#if defined _MSC_VER && _MSC_VER >= 1400\r
+/* A routine to check if a file descriptor is valid on Windows.  Returns 0\r
+ * and sets errno to EBADF if it isn't.  This is to avoid Assertions\r
+ * from various functions in the Windows CRT beginning with\r
+ * Visual Studio 2005\r
+ */\r
+//int _PyVerify_fd(int fd);\r
+//#elif defined _MSC_VER && _MSC_VER >= 1200\r
+/* fdopen doesn't set errno EBADF and crashes for large fd on debug build */\r
+//#define _PyVerify_fd(fd) (_get_osfhandle(fd) >= 0)\r
+//#else\r
+#define _PyVerify_fd(A) (1) /* dummy */\r
+//#endif\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif /* !Py_FILEOBJECT_H */\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Include/pyport.h b/AppPkg/Applications/Python/PyMod-2.7.2/Include/pyport.h
new file mode 100644 (file)
index 0000000..4c6eef0
--- /dev/null
@@ -0,0 +1,905 @@
+#ifndef Py_PYPORT_H\r
+#define Py_PYPORT_H\r
+\r
+#include "pyconfig.h" /* include for defines */\r
+\r
+/* Some versions of HP-UX & Solaris need inttypes.h for int32_t,\r
+   INT32_MAX, etc. */\r
+#ifdef HAVE_INTTYPES_H\r
+#include <inttypes.h>\r
+#endif\r
+\r
+#ifdef HAVE_STDINT_H\r
+#include <stdint.h>\r
+#endif\r
+\r
+/**************************************************************************\r
+Symbols and macros to supply platform-independent interfaces to basic\r
+C language & library operations whose spellings vary across platforms.\r
+\r
+Please try to make documentation here as clear as possible:  by definition,\r
+the stuff here is trying to illuminate C's darkest corners.\r
+\r
+Config #defines referenced here:\r
+\r
+SIGNED_RIGHT_SHIFT_ZERO_FILLS\r
+Meaning:  To be defined iff i>>j does not extend the sign bit when i is a\r
+          signed integral type and i < 0.\r
+Used in:  Py_ARITHMETIC_RIGHT_SHIFT\r
+\r
+Py_DEBUG\r
+Meaning:  Extra checks compiled in for debug mode.\r
+Used in:  Py_SAFE_DOWNCAST\r
+\r
+HAVE_UINTPTR_T\r
+Meaning:  The C9X type uintptr_t is supported by the compiler\r
+Used in:  Py_uintptr_t\r
+\r
+HAVE_LONG_LONG\r
+Meaning:  The compiler supports the C type "long long"\r
+Used in:  PY_LONG_LONG\r
+\r
+**************************************************************************/\r
+\r
+\r
+/* For backward compatibility only. Obsolete, do not use. */\r
+#ifdef HAVE_PROTOTYPES\r
+#define Py_PROTO(x) x\r
+#else\r
+#define Py_PROTO(x) ()\r
+#endif\r
+#ifndef Py_FPROTO\r
+#define Py_FPROTO(x) Py_PROTO(x)\r
+#endif\r
+\r
+/* typedefs for some C9X-defined synonyms for integral types.\r
+ *\r
+ * The names in Python are exactly the same as the C9X names, except with a\r
+ * Py_ prefix.  Until C9X is universally implemented, this is the only way\r
+ * to ensure that Python gets reliable names that don't conflict with names\r
+ * in non-Python code that are playing their own tricks to define the C9X\r
+ * names.\r
+ *\r
+ * NOTE: don't go nuts here!  Python has no use for *most* of the C9X\r
+ * integral synonyms.  Only define the ones we actually need.\r
+ */\r
+\r
+#ifdef HAVE_LONG_LONG\r
+#ifndef PY_LONG_LONG\r
+#define PY_LONG_LONG long long\r
+#if defined(LLONG_MAX)\r
+/* If LLONG_MAX is defined in limits.h, use that. */\r
+#define PY_LLONG_MIN LLONG_MIN\r
+#define PY_LLONG_MAX LLONG_MAX\r
+#define PY_ULLONG_MAX ULLONG_MAX\r
+#elif defined(__LONG_LONG_MAX__)\r
+/* Otherwise, if GCC has a builtin define, use that. */\r
+#define PY_LLONG_MAX __LONG_LONG_MAX__\r
+#define PY_LLONG_MIN (-PY_LLONG_MAX-1)\r
+#define PY_ULLONG_MAX (__LONG_LONG_MAX__*2ULL + 1ULL)\r
+#else\r
+/* Otherwise, rely on two's complement. */\r
+#define PY_ULLONG_MAX (~0ULL)\r
+#define PY_LLONG_MAX  ((long long)(PY_ULLONG_MAX>>1))\r
+#define PY_LLONG_MIN (-PY_LLONG_MAX-1)\r
+#endif /* LLONG_MAX */\r
+#endif\r
+#endif /* HAVE_LONG_LONG */\r
+\r
+/* a build with 30-bit digits for Python long integers needs an exact-width\r
+ * 32-bit unsigned integer type to store those digits.  (We could just use\r
+ * type 'unsigned long', but that would be wasteful on a system where longs\r
+ * are 64-bits.)  On Unix systems, the autoconf macro AC_TYPE_UINT32_T defines\r
+ * uint32_t to be such a type unless stdint.h or inttypes.h defines uint32_t.\r
+ * However, it doesn't set HAVE_UINT32_T, so we do that here.\r
+ */\r
+#if (defined UINT32_MAX || defined uint32_t)\r
+#ifndef PY_UINT32_T\r
+#define HAVE_UINT32_T 1\r
+#define PY_UINT32_T uint32_t\r
+#endif\r
+#endif\r
+\r
+/* Macros for a 64-bit unsigned integer type; used for type 'twodigits' in the\r
+ * long integer implementation, when 30-bit digits are enabled.\r
+ */\r
+#if (defined UINT64_MAX || defined uint64_t)\r
+#ifndef PY_UINT64_T\r
+#define HAVE_UINT64_T 1\r
+#define PY_UINT64_T uint64_t\r
+#endif\r
+#endif\r
+\r
+/* Signed variants of the above */\r
+#if (defined INT32_MAX || defined int32_t)\r
+#ifndef PY_INT32_T\r
+#define HAVE_INT32_T 1\r
+#define PY_INT32_T int32_t\r
+#endif\r
+#endif\r
+#if (defined INT64_MAX || defined int64_t)\r
+#ifndef PY_INT64_T\r
+#define HAVE_INT64_T 1\r
+#define PY_INT64_T int64_t\r
+#endif\r
+#endif\r
+\r
+/* If PYLONG_BITS_IN_DIGIT is not defined then we'll use 30-bit digits if all\r
+   the necessary integer types are available, and we're on a 64-bit platform\r
+   (as determined by SIZEOF_VOID_P); otherwise we use 15-bit digits. */\r
+\r
+#ifndef PYLONG_BITS_IN_DIGIT\r
+#if (defined HAVE_UINT64_T && defined HAVE_INT64_T && \\r
+     defined HAVE_UINT32_T && defined HAVE_INT32_T && SIZEOF_VOID_P >= 8)\r
+#define PYLONG_BITS_IN_DIGIT 30\r
+#else\r
+#define PYLONG_BITS_IN_DIGIT 15\r
+#endif\r
+#endif\r
+\r
+/* uintptr_t is the C9X name for an unsigned integral type such that a\r
+ * legitimate void* can be cast to uintptr_t and then back to void* again\r
+ * without loss of information.  Similarly for intptr_t, wrt a signed\r
+ * integral type.\r
+ */\r
+#ifdef HAVE_UINTPTR_T\r
+typedef uintptr_t       Py_uintptr_t;\r
+typedef intptr_t        Py_intptr_t;\r
+\r
+#elif SIZEOF_VOID_P <= SIZEOF_INT\r
+typedef unsigned int    Py_uintptr_t;\r
+typedef int             Py_intptr_t;\r
+\r
+#elif SIZEOF_VOID_P <= SIZEOF_LONG\r
+typedef unsigned long   Py_uintptr_t;\r
+typedef long            Py_intptr_t;\r
+\r
+#elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG)\r
+typedef unsigned PY_LONG_LONG   Py_uintptr_t;\r
+typedef PY_LONG_LONG            Py_intptr_t;\r
+\r
+#else\r
+#   error "Python needs a typedef for Py_uintptr_t in pyport.h."\r
+#endif /* HAVE_UINTPTR_T */\r
+\r
+/* Py_ssize_t is a signed integral type such that sizeof(Py_ssize_t) ==\r
+ * sizeof(size_t).  C99 doesn't define such a thing directly (size_t is an\r
+ * unsigned integral type).  See PEP 353 for details.\r
+ */\r
+#ifdef HAVE_SSIZE_T\r
+typedef ssize_t         Py_ssize_t;\r
+#elif SIZEOF_VOID_P == SIZEOF_SIZE_T\r
+typedef Py_intptr_t     Py_ssize_t;\r
+#else\r
+#   error "Python needs a typedef for Py_ssize_t in pyport.h."\r
+#endif\r
+\r
+/* Largest possible value of size_t.\r
+   SIZE_MAX is part of C99, so it might be defined on some\r
+   platforms. If it is not defined, (size_t)-1 is a portable\r
+   definition for C89, due to the way signed->unsigned\r
+   conversion is defined. */\r
+#ifdef SIZE_MAX\r
+#define PY_SIZE_MAX SIZE_MAX\r
+#else\r
+#define PY_SIZE_MAX ((size_t)-1)\r
+#endif\r
+\r
+/* Largest positive value of type Py_ssize_t. */\r
+#define PY_SSIZE_T_MAX ((Py_ssize_t)(((size_t)-1)>>1))\r
+/* Smallest negative value of type Py_ssize_t. */\r
+#define PY_SSIZE_T_MIN (-PY_SSIZE_T_MAX-1)\r
+\r
+#if SIZEOF_PID_T > SIZEOF_LONG\r
+#   error "Python doesn't support sizeof(pid_t) > sizeof(long)"\r
+#endif\r
+\r
+/* PY_FORMAT_SIZE_T is a platform-specific modifier for use in a printf\r
+ * format to convert an argument with the width of a size_t or Py_ssize_t.\r
+ * C99 introduced "z" for this purpose, but not all platforms support that;\r
+ * e.g., MS compilers use "I" instead.\r
+ *\r
+ * These "high level" Python format functions interpret "z" correctly on\r
+ * all platforms (Python interprets the format string itself, and does whatever\r
+ * the platform C requires to convert a size_t/Py_ssize_t argument):\r
+ *\r
+ *     PyString_FromFormat\r
+ *     PyErr_Format\r
+ *     PyString_FromFormatV\r
+ *\r
+ * Lower-level uses require that you interpolate the correct format modifier\r
+ * yourself (e.g., calling printf, fprintf, sprintf, PyOS_snprintf); for\r
+ * example,\r
+ *\r
+ *     Py_ssize_t index;\r
+ *     fprintf(stderr, "index %" PY_FORMAT_SIZE_T "d sucks\n", index);\r
+ *\r
+ * That will expand to %ld, or %Id, or to something else correct for a\r
+ * Py_ssize_t on the platform.\r
+ */\r
+#ifndef PY_FORMAT_SIZE_T\r
+#   if SIZEOF_SIZE_T == SIZEOF_INT && !defined(__APPLE__)\r
+#       define PY_FORMAT_SIZE_T ""\r
+#   elif SIZEOF_SIZE_T == SIZEOF_LONG\r
+#       define PY_FORMAT_SIZE_T "l"\r
+#   elif defined(MS_WINDOWS)\r
+#       define PY_FORMAT_SIZE_T "I"\r
+#   else\r
+#       error "This platform's pyconfig.h needs to define PY_FORMAT_SIZE_T"\r
+#   endif\r
+#endif\r
+\r
+/* PY_FORMAT_LONG_LONG is analogous to PY_FORMAT_SIZE_T above, but for\r
+ * the long long type instead of the size_t type.  It's only available\r
+ * when HAVE_LONG_LONG is defined. The "high level" Python format\r
+ * functions listed above will interpret "lld" or "llu" correctly on\r
+ * all platforms.\r
+ */\r
+#ifdef HAVE_LONG_LONG\r
+#   ifndef PY_FORMAT_LONG_LONG\r
+#       if defined(MS_WIN64) || defined(MS_WINDOWS)\r
+#           define PY_FORMAT_LONG_LONG "I64"\r
+#       else\r
+#           error "This platform's pyconfig.h needs to define PY_FORMAT_LONG_LONG"\r
+#       endif\r
+#   endif\r
+#endif\r
+\r
+/* Py_LOCAL can be used instead of static to get the fastest possible calling\r
+ * convention for functions that are local to a given module.\r
+ *\r
+ * Py_LOCAL_INLINE does the same thing, and also explicitly requests inlining,\r
+ * for platforms that support that.\r
+ *\r
+ * If PY_LOCAL_AGGRESSIVE is defined before python.h is included, more\r
+ * "aggressive" inlining/optimizaion is enabled for the entire module.  This\r
+ * may lead to code bloat, and may slow things down for those reasons.  It may\r
+ * also lead to errors, if the code relies on pointer aliasing.  Use with\r
+ * care.\r
+ *\r
+ * NOTE: You can only use this for functions that are entirely local to a\r
+ * module; functions that are exported via method tables, callbacks, etc,\r
+ * should keep using static.\r
+ */\r
+\r
+#undef USE_INLINE /* XXX - set via configure? */\r
+\r
+#if defined(_MSC_VER)\r
+#if defined(PY_LOCAL_AGGRESSIVE)\r
+/* enable more aggressive optimization for visual studio */\r
+//#pragma optimize("agtw", on)\r
+#pragma optimize("gt", on)    // a and w are not legal for VS2005\r
+#endif\r
+/* ignore warnings if the compiler decides not to inline a function */\r
+#pragma warning(disable: 4710)\r
+/* fastest possible local call under MSVC */\r
+#define Py_LOCAL(type) static type __fastcall\r
+#define Py_LOCAL_INLINE(type) static __inline type __fastcall\r
+#elif defined(USE_INLINE)\r
+#define Py_LOCAL(type) static type\r
+#define Py_LOCAL_INLINE(type) static inline type\r
+#else\r
+#define Py_LOCAL(type) static type\r
+#define Py_LOCAL_INLINE(type) static type\r
+#endif\r
+\r
+/* Py_MEMCPY can be used instead of memcpy in cases where the copied blocks\r
+ * are often very short.  While most platforms have highly optimized code for\r
+ * large transfers, the setup costs for memcpy are often quite high.  MEMCPY\r
+ * solves this by doing short copies "in line".\r
+ */\r
+\r
+#if defined(_MSC_VER)\r
+#define Py_MEMCPY(target, source, length) do {                          \\r
+        size_t i_, n_ = (length);                                       \\r
+        char *t_ = (void*) (target);                                    \\r
+        const char *s_ = (void*) (source);                              \\r
+        if (n_ >= 16)                                                   \\r
+            memcpy(t_, s_, n_);                                         \\r
+        else                                                            \\r
+            for (i_ = 0; i_ < n_; i_++)                                 \\r
+                t_[i_] = s_[i_];                                        \\r
+    } while (0)\r
+#else\r
+#define Py_MEMCPY memcpy\r
+#endif\r
+\r
+#include <stdlib.h>\r
+\r
+#ifdef HAVE_IEEEFP_H\r
+#include <ieeefp.h>  /* needed for 'finite' declaration on some platforms */\r
+#endif\r
+\r
+#include <math.h> /* Moved here from the math section, before extern "C" */\r
+\r
+/********************************************\r
+ * WRAPPER FOR <time.h> and/or <sys/time.h> *\r
+ ********************************************/\r
+\r
+#ifdef TIME_WITH_SYS_TIME\r
+#include <sys/time.h>\r
+#include <time.h>\r
+#else /* !TIME_WITH_SYS_TIME */\r
+#ifdef HAVE_SYS_TIME_H\r
+#include <sys/time.h>\r
+#else /* !HAVE_SYS_TIME_H */\r
+#include <time.h>\r
+#endif /* !HAVE_SYS_TIME_H */\r
+#endif /* !TIME_WITH_SYS_TIME */\r
+\r
+\r
+/******************************\r
+ * WRAPPER FOR <sys/select.h> *\r
+ ******************************/\r
+\r
+/* NB caller must include <sys/types.h> */\r
+\r
+#ifdef HAVE_SYS_SELECT_H\r
+\r
+#include <sys/select.h>\r
+\r
+#endif /* !HAVE_SYS_SELECT_H */\r
+\r
+/*******************************\r
+ * stat() and fstat() fiddling *\r
+ *******************************/\r
+\r
+/* We expect that stat and fstat exist on most systems.\r
+ *  It's confirmed on Unix, Mac and Windows.\r
+ *  If you don't have them, add\r
+ *      #define DONT_HAVE_STAT\r
+ * and/or\r
+ *      #define DONT_HAVE_FSTAT\r
+ * to your pyconfig.h. Python code beyond this should check HAVE_STAT and\r
+ * HAVE_FSTAT instead.\r
+ * Also\r
+ *      #define HAVE_SYS_STAT_H\r
+ * if <sys/stat.h> exists on your platform, and\r
+ *      #define HAVE_STAT_H\r
+ * if <stat.h> does.\r
+ */\r
+#ifndef DONT_HAVE_STAT\r
+#define HAVE_STAT\r
+#endif\r
+\r
+#ifndef DONT_HAVE_FSTAT\r
+#define HAVE_FSTAT\r
+#endif\r
+\r
+#ifdef RISCOS\r
+#include <sys/types.h>\r
+#include "unixstuff.h"\r
+#endif\r
+\r
+#ifdef HAVE_SYS_STAT_H\r
+#if defined(PYOS_OS2) && defined(PYCC_GCC)\r
+#include <sys/types.h>\r
+#endif\r
+#include <sys/stat.h>\r
+#elif defined(HAVE_STAT_H)\r
+#include <stat.h>\r
+#endif\r
+\r
+#if defined(PYCC_VACPP)\r
+/* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */\r
+#define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)\r
+#endif\r
+\r
+#ifndef S_ISREG\r
+#define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)\r
+#endif\r
+\r
+#ifndef S_ISDIR\r
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)\r
+#endif\r
+\r
+\r
+#ifdef __cplusplus\r
+/* Move this down here since some C++ #include's don't like to be included\r
+   inside an extern "C" */\r
+extern "C" {\r
+#endif\r
+\r
+\r
+/* Py_ARITHMETIC_RIGHT_SHIFT\r
+ * C doesn't define whether a right-shift of a signed integer sign-extends\r
+ * or zero-fills.  Here a macro to force sign extension:\r
+ * Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J)\r
+ *    Return I >> J, forcing sign extension.  Arithmetically, return the\r
+ *    floor of I/2**J.\r
+ * Requirements:\r
+ *    I should have signed integer type.  In the terminology of C99, this can\r
+ *    be either one of the five standard signed integer types (signed char,\r
+ *    short, int, long, long long) or an extended signed integer type.\r
+ *    J is an integer >= 0 and strictly less than the number of bits in the\r
+ *    type of I (because C doesn't define what happens for J outside that\r
+ *    range either).\r
+ *    TYPE used to specify the type of I, but is now ignored.  It's been left\r
+ *    in for backwards compatibility with versions <= 2.6 or 3.0.\r
+ * Caution:\r
+ *    I may be evaluated more than once.\r
+ */\r
+#ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS\r
+#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \\r
+    ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))\r
+#else\r
+#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J))\r
+#endif\r
+\r
+/* Py_FORCE_EXPANSION(X)\r
+ * "Simply" returns its argument.  However, macro expansions within the\r
+ * argument are evaluated.  This unfortunate trickery is needed to get\r
+ * token-pasting to work as desired in some cases.\r
+ */\r
+#define Py_FORCE_EXPANSION(X) X\r
+\r
+/* Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW)\r
+ * Cast VALUE to type NARROW from type WIDE.  In Py_DEBUG mode, this\r
+ * assert-fails if any information is lost.\r
+ * Caution:\r
+ *    VALUE may be evaluated more than once.\r
+ */\r
+#ifdef Py_DEBUG\r
+#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \\r
+    (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))\r
+#else\r
+#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE)\r
+#endif\r
+\r
+/* Py_SET_ERRNO_ON_MATH_ERROR(x)\r
+ * If a libm function did not set errno, but it looks like the result\r
+ * overflowed or not-a-number, set errno to ERANGE or EDOM.  Set errno\r
+ * to 0 before calling a libm function, and invoke this macro after,\r
+ * passing the function result.\r
+ * Caution:\r
+ *    This isn't reliable.  See Py_OVERFLOWED comments.\r
+ *    X is evaluated more than once.\r
+ */\r
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__hpux) && defined(__ia64))\r
+#define _Py_SET_EDOM_FOR_NAN(X) if (isnan(X)) errno = EDOM;\r
+#else\r
+#define _Py_SET_EDOM_FOR_NAN(X) ;\r
+#endif\r
+#define Py_SET_ERRNO_ON_MATH_ERROR(X) \\r
+    do { \\r
+        if (errno == 0) { \\r
+            if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \\r
+                errno = ERANGE; \\r
+            else _Py_SET_EDOM_FOR_NAN(X) \\r
+        } \\r
+    } while(0)\r
+\r
+/* Py_SET_ERANGE_ON_OVERFLOW(x)\r
+ * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility.\r
+ */\r
+#define Py_SET_ERANGE_IF_OVERFLOW(X) Py_SET_ERRNO_ON_MATH_ERROR(X)\r
+\r
+/* Py_ADJUST_ERANGE1(x)\r
+ * Py_ADJUST_ERANGE2(x, y)\r
+ * Set errno to 0 before calling a libm function, and invoke one of these\r
+ * macros after, passing the function result(s) (Py_ADJUST_ERANGE2 is useful\r
+ * for functions returning complex results).  This makes two kinds of\r
+ * adjustments to errno:  (A) If it looks like the platform libm set\r
+ * errno=ERANGE due to underflow, clear errno. (B) If it looks like the\r
+ * platform libm overflowed but didn't set errno, force errno to ERANGE.  In\r
+ * effect, we're trying to force a useful implementation of C89 errno\r
+ * behavior.\r
+ * Caution:\r
+ *    This isn't reliable.  See Py_OVERFLOWED comments.\r
+ *    X and Y may be evaluated more than once.\r
+ */\r
+#define Py_ADJUST_ERANGE1(X)                                            \\r
+    do {                                                                \\r
+        if (errno == 0) {                                               \\r
+            if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL)              \\r
+                errno = ERANGE;                                         \\r
+        }                                                               \\r
+        else if (errno == ERANGE && (X) == 0.0)                         \\r
+            errno = 0;                                                  \\r
+    } while(0)\r
+\r
+#define Py_ADJUST_ERANGE2(X, Y)                                         \\r
+    do {                                                                \\r
+        if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL ||                \\r
+            (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) {                \\r
+                        if (errno == 0)                                 \\r
+                                errno = ERANGE;                         \\r
+        }                                                               \\r
+        else if (errno == ERANGE)                                       \\r
+            errno = 0;                                                  \\r
+    } while(0)\r
+\r
+/*  The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are\r
+ *  required to support the short float repr introduced in Python 3.1) require\r
+ *  that the floating-point unit that's being used for arithmetic operations\r
+ *  on C doubles is set to use 53-bit precision.  It also requires that the\r
+ *  FPU rounding mode is round-half-to-even, but that's less often an issue.\r
+ *\r
+ *  If your FPU isn't already set to 53-bit precision/round-half-to-even, and\r
+ *  you want to make use of _Py_dg_strtod and _Py_dg_dtoa, then you should\r
+ *\r
+ *     #define HAVE_PY_SET_53BIT_PRECISION 1\r
+ *\r
+ *  and also give appropriate definitions for the following three macros:\r
+ *\r
+ *    _PY_SET_53BIT_PRECISION_START : store original FPU settings, and\r
+ *        set FPU to 53-bit precision/round-half-to-even\r
+ *    _PY_SET_53BIT_PRECISION_END : restore original FPU settings\r
+ *    _PY_SET_53BIT_PRECISION_HEADER : any variable declarations needed to\r
+ *        use the two macros above.\r
+ *\r
+ * The macros are designed to be used within a single C function: see\r
+ * Python/pystrtod.c for an example of their use.\r
+ */\r
+\r
+/* get and set x87 control word for gcc/x86 */\r
+#ifdef HAVE_GCC_ASM_FOR_X87\r
+#define HAVE_PY_SET_53BIT_PRECISION 1\r
+/* _Py_get/set_387controlword functions are defined in Python/pymath.c */\r
+#define _Py_SET_53BIT_PRECISION_HEADER                          \\r
+    unsigned short old_387controlword, new_387controlword\r
+#define _Py_SET_53BIT_PRECISION_START                                   \\r
+    do {                                                                \\r
+        old_387controlword = _Py_get_387controlword();                  \\r
+        new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \\r
+        if (new_387controlword != old_387controlword)                   \\r
+            _Py_set_387controlword(new_387controlword);                 \\r
+    } while (0)\r
+#define _Py_SET_53BIT_PRECISION_END                             \\r
+    if (new_387controlword != old_387controlword)               \\r
+        _Py_set_387controlword(old_387controlword)\r
+#endif\r
+\r
+/* default definitions are empty */\r
+#ifndef HAVE_PY_SET_53BIT_PRECISION\r
+#define _Py_SET_53BIT_PRECISION_HEADER\r
+#define _Py_SET_53BIT_PRECISION_START\r
+#define _Py_SET_53BIT_PRECISION_END\r
+#endif\r
+\r
+/* If we can't guarantee 53-bit precision, don't use the code\r
+   in Python/dtoa.c, but fall back to standard code.  This\r
+   means that repr of a float will be long (17 sig digits).\r
+\r
+   Realistically, there are two things that could go wrong:\r
+\r
+   (1) doubles aren't IEEE 754 doubles, or\r
+   (2) we're on x86 with the rounding precision set to 64-bits\r
+       (extended precision), and we don't know how to change\r
+       the rounding precision.\r
+ */\r
+\r
+#if !defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) && \\r
+    !defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) && \\r
+    !defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)\r
+#define PY_NO_SHORT_FLOAT_REPR\r
+#endif\r
+\r
+/* double rounding is symptomatic of use of extended precision on x86.  If\r
+   we're seeing double rounding, and we don't have any mechanism available for\r
+   changing the FPU rounding precision, then don't use Python/dtoa.c. */\r
+#if defined(X87_DOUBLE_ROUNDING) && !defined(HAVE_PY_SET_53BIT_PRECISION)\r
+#define PY_NO_SHORT_FLOAT_REPR\r
+#endif\r
+\r
+/* Py_DEPRECATED(version)\r
+ * Declare a variable, type, or function deprecated.\r
+ * Usage:\r
+ *    extern int old_var Py_DEPRECATED(2.3);\r
+ *    typedef int T1 Py_DEPRECATED(2.4);\r
+ *    extern int x() Py_DEPRECATED(2.5);\r
+ */\r
+#if defined(__GNUC__) && ((__GNUC__ >= 4) || \\r
+              (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))\r
+#define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))\r
+#else\r
+#define Py_DEPRECATED(VERSION_UNUSED)\r
+#endif\r
+\r
+/**************************************************************************\r
+Prototypes that are missing from the standard include files on some systems\r
+(and possibly only some versions of such systems.)\r
+\r
+Please be conservative with adding new ones, document them and enclose them\r
+in platform-specific #ifdefs.\r
+**************************************************************************/\r
+\r
+#ifdef SOLARIS\r
+/* Unchecked */\r
+extern int gethostname(char *, int);\r
+#endif\r
+\r
+#ifdef __BEOS__\r
+/* Unchecked */\r
+/* It's in the libs, but not the headers... - [cjh] */\r
+int shutdown( int, int );\r
+#endif\r
+\r
+#ifdef HAVE__GETPTY\r
+#include <sys/types.h>          /* we need to import mode_t */\r
+extern char * _getpty(int *, int, mode_t, int);\r
+#endif\r
+\r
+/* On QNX 6, struct termio must be declared by including sys/termio.h\r
+   if TCGETA, TCSETA, TCSETAW, or TCSETAF are used.  sys/termio.h must\r
+   be included before termios.h or it will generate an error. */\r
+#ifdef HAVE_SYS_TERMIO_H\r
+#include <sys/termio.h>\r
+#endif\r
+\r
+#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY)\r
+#if !defined(HAVE_PTY_H) && !defined(HAVE_LIBUTIL_H) && !defined(HAVE_UTIL_H)\r
+/* BSDI does not supply a prototype for the 'openpty' and 'forkpty'\r
+   functions, even though they are included in libutil. */\r
+#include <termios.h>\r
+extern int openpty(int *, int *, char *, struct termios *, struct winsize *);\r
+extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);\r
+#endif /* !defined(HAVE_PTY_H) && !defined(HAVE_LIBUTIL_H) */\r
+#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) */\r
+\r
+\r
+/* These are pulled from various places. It isn't obvious on what platforms\r
+   they are necessary, nor what the exact prototype should look like (which\r
+   is likely to vary between platforms!) If you find you need one of these\r
+   declarations, please move them to a platform-specific block and include\r
+   proper prototypes. */\r
+#if 0\r
+\r
+/* From Modules/resource.c */\r
+extern int getrusage();\r
+extern int getpagesize();\r
+\r
+/* From Python/sysmodule.c and Modules/posixmodule.c */\r
+extern int fclose(FILE *);\r
+\r
+/* From Modules/posixmodule.c */\r
+extern int fdatasync(int);\r
+#endif /* 0 */\r
+\r
+\r
+/* On 4.4BSD-descendants, ctype functions serves the whole range of\r
+ * wchar_t character set rather than single byte code points only.\r
+ * This characteristic can break some operations of string object\r
+ * including str.upper() and str.split() on UTF-8 locales.  This\r
+ * workaround was provided by Tim Robbins of FreeBSD project.\r
+ */\r
+\r
+#ifdef __FreeBSD__\r
+#include <osreldate.h>\r
+#if __FreeBSD_version > 500039\r
+# define _PY_PORT_CTYPE_UTF8_ISSUE\r
+#endif\r
+#endif\r
+\r
+\r
+#if defined(__APPLE__)\r
+# define _PY_PORT_CTYPE_UTF8_ISSUE\r
+#endif\r
+\r
+#ifdef _PY_PORT_CTYPE_UTF8_ISSUE\r
+#include <ctype.h>\r
+#include <wctype.h>\r
+#undef isalnum\r
+#define isalnum(c) iswalnum(btowc(c))\r
+#undef isalpha\r
+#define isalpha(c) iswalpha(btowc(c))\r
+#undef islower\r
+#define islower(c) iswlower(btowc(c))\r
+#undef isspace\r
+#define isspace(c) iswspace(btowc(c))\r
+#undef isupper\r
+#define isupper(c) iswupper(btowc(c))\r
+#undef tolower\r
+#define tolower(c) towlower(btowc(c))\r
+#undef toupper\r
+#define toupper(c) towupper(btowc(c))\r
+#endif\r
+\r
+\r
+/* Declarations for symbol visibility.\r
+\r
+  PyAPI_FUNC(type): Declares a public Python API function and return type\r
+  PyAPI_DATA(type): Declares public Python data and its type\r
+  PyMODINIT_FUNC:   A Python module init function.  If these functions are\r
+                    inside the Python core, they are private to the core.\r
+                    If in an extension module, it may be declared with\r
+                    external linkage depending on the platform.\r
+\r
+  As a number of platforms support/require "__declspec(dllimport/dllexport)",\r
+  we support a HAVE_DECLSPEC_DLL macro to save duplication.\r
+*/\r
+\r
+/*\r
+  All windows ports, except cygwin, are handled in PC/pyconfig.h.\r
+\r
+  BeOS and cygwin are the only other autoconf platform requiring special\r
+  linkage handling and both of these use __declspec().\r
+*/\r
+#if defined(__CYGWIN__) || defined(__BEOS__)\r
+#       define HAVE_DECLSPEC_DLL\r
+#endif\r
+\r
+/* only get special linkage if built as shared or platform is Cygwin */\r
+#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)\r
+#       if defined(HAVE_DECLSPEC_DLL)\r
+#               ifdef Py_BUILD_CORE\r
+#                       define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE\r
+#                       define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE\r
+        /* module init functions inside the core need no external linkage */\r
+        /* except for Cygwin to handle embedding (FIXME: BeOS too?) */\r
+#                       if defined(__CYGWIN__)\r
+#                               define PyMODINIT_FUNC __declspec(dllexport) void\r
+#                       else /* __CYGWIN__ */\r
+#                               define PyMODINIT_FUNC void\r
+#                       endif /* __CYGWIN__ */\r
+#               else /* Py_BUILD_CORE */\r
+        /* Building an extension module, or an embedded situation */\r
+        /* public Python functions and data are imported */\r
+        /* Under Cygwin, auto-import functions to prevent compilation */\r
+        /* failures similar to those described at the bottom of 4.1: */\r
+        /* http://docs.python.org/extending/windows.html#a-cookbook-approach */\r
+#                       if !defined(__CYGWIN__)\r
+#                               define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE\r
+#                       endif /* !__CYGWIN__ */\r
+#                       define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE\r
+        /* module init functions outside the core must be exported */\r
+#                       if defined(__cplusplus)\r
+#                               define PyMODINIT_FUNC extern "C" __declspec(dllexport) void\r
+#                       else /* __cplusplus */\r
+#                               define PyMODINIT_FUNC __declspec(dllexport) void\r
+#                       endif /* __cplusplus */\r
+#               endif /* Py_BUILD_CORE */\r
+#       endif /* HAVE_DECLSPEC */\r
+#endif /* Py_ENABLE_SHARED */\r
+\r
+/* If no external linkage macros defined by now, create defaults */\r
+#ifndef PyAPI_FUNC\r
+#       define PyAPI_FUNC(RTYPE) RTYPE\r
+#endif\r
+#ifndef PyAPI_DATA\r
+#       define PyAPI_DATA(RTYPE) extern RTYPE\r
+#endif\r
+#ifndef PyMODINIT_FUNC\r
+#       if defined(__cplusplus)\r
+#               define PyMODINIT_FUNC extern "C" void\r
+#       else /* __cplusplus */\r
+#               define PyMODINIT_FUNC void\r
+#       endif /* __cplusplus */\r
+#endif\r
+\r
+/* Deprecated DL_IMPORT and DL_EXPORT macros */\r
+#if defined(Py_ENABLE_SHARED) && defined (HAVE_DECLSPEC_DLL)\r
+#       if defined(Py_BUILD_CORE)\r
+#               define DL_IMPORT(RTYPE) __declspec(dllexport) RTYPE\r
+#               define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE\r
+#       else\r
+#               define DL_IMPORT(RTYPE) __declspec(dllimport) RTYPE\r
+#               define DL_EXPORT(RTYPE) __declspec(dllexport) RTYPE\r
+#       endif\r
+#endif\r
+#ifndef DL_EXPORT\r
+#       define DL_EXPORT(RTYPE) RTYPE\r
+#endif\r
+#ifndef DL_IMPORT\r
+#       define DL_IMPORT(RTYPE) RTYPE\r
+#endif\r
+/* End of deprecated DL_* macros */\r
+\r
+/* If the fd manipulation macros aren't defined,\r
+   here is a set that should do the job */\r
+\r
+#if 0 /* disabled and probably obsolete */\r
+\r
+#ifndef FD_SETSIZE\r
+#define FD_SETSIZE      256\r
+#endif\r
+\r
+#ifndef FD_SET\r
+\r
+typedef long fd_mask;\r
+\r
+#define NFDBITS (sizeof(fd_mask) * NBBY)        /* bits per mask */\r
+#ifndef howmany\r
+#define howmany(x, y)   (((x)+((y)-1))/(y))\r
+#endif /* howmany */\r
+\r
+typedef struct fd_set {\r
+    fd_mask     fds_bits[howmany(FD_SETSIZE, NFDBITS)];\r
+} fd_set;\r
+\r
+#define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))\r
+#define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))\r
+#define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))\r
+#define FD_ZERO(p)      memset((char *)(p), '\0', sizeof(*(p)))\r
+\r
+#endif /* FD_SET */\r
+\r
+#endif /* fd manipulation macros */\r
+\r
+\r
+/* limits.h constants that may be missing */\r
+\r
+#ifndef INT_MAX\r
+#define INT_MAX 2147483647\r
+#endif\r
+\r
+#ifndef LONG_MAX\r
+#if SIZEOF_LONG == 4\r
+#define LONG_MAX 0X7FFFFFFFL\r
+#elif SIZEOF_LONG == 8\r
+#define LONG_MAX 0X7FFFFFFFFFFFFFFFL\r
+#else\r
+#error "could not set LONG_MAX in pyport.h"\r
+#endif\r
+#endif\r
+\r
+#ifndef LONG_MIN\r
+#define LONG_MIN (-LONG_MAX-1)\r
+#endif\r
+\r
+#ifndef LONG_BIT\r
+#define LONG_BIT (8 * SIZEOF_LONG)\r
+#endif\r
+\r
+#if LONG_BIT != 8 * SIZEOF_LONG\r
+/* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent\r
+ * 32-bit platforms using gcc.  We try to catch that here at compile-time\r
+ * rather than waiting for integer multiplication to trigger bogus\r
+ * overflows.\r
+ */\r
+#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."\r
+#endif\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/*\r
+ * Hide GCC attributes from compilers that don't support them.\r
+ */\r
+#if (!defined(__GNUC__) || __GNUC__ < 2 || \\r
+     (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ) && \\r
+    !defined(RISCOS)\r
+#define Py_GCC_ATTRIBUTE(x)\r
+#else\r
+#define Py_GCC_ATTRIBUTE(x) __attribute__(x)\r
+#endif\r
+\r
+/*\r
+ * Add PyArg_ParseTuple format where available.\r
+ */\r
+#ifdef HAVE_ATTRIBUTE_FORMAT_PARSETUPLE\r
+#define Py_FORMAT_PARSETUPLE(func,p1,p2) __attribute__((format(func,p1,p2)))\r
+#else\r
+#define Py_FORMAT_PARSETUPLE(func,p1,p2)\r
+#endif\r
+\r
+/*\r
+ * Specify alignment on compilers that support it.\r
+ */\r
+#if defined(__GNUC__) && __GNUC__ >= 3\r
+#define Py_ALIGNED(x) __attribute__((aligned(x)))\r
+#else\r
+#define Py_ALIGNED(x)\r
+#endif\r
+\r
+/* Eliminate end-of-loop code not reached warnings from SunPro C\r
+ * when using do{...}while(0) macros\r
+ */\r
+#ifdef __SUNPRO_C\r
+#pragma error_messages (off,E_END_OF_LOOP_CODE_NOT_REACHED)\r
+#endif\r
+\r
+/*\r
+ * Older Microsoft compilers don't support the C99 long long literal suffixes,\r
+ * so these will be defined in PC/pyconfig.h for those compilers.\r
+ */\r
+#ifndef Py_LL\r
+#define Py_LL(x) x##LL\r
+#endif\r
+\r
+#ifndef Py_ULL\r
+#define Py_ULL(x) Py_LL(x##U)\r
+#endif\r
+\r
+#endif /* Py_PYPORT_H */\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/_sre.c
new file mode 100644 (file)
index 0000000..ec723cc
--- /dev/null
@@ -0,0 +1,3912 @@
+/*\r
+ * Secret Labs' Regular Expression Engine\r
+ *\r
+ * regular expression matching engine\r
+ *\r
+ * partial history:\r
+ * 1999-10-24 fl  created (based on existing template matcher code)\r
+ * 2000-03-06 fl  first alpha, sort of\r
+ * 2000-08-01 fl  fixes for 1.6b1\r
+ * 2000-08-07 fl  use PyOS_CheckStack() if available\r
+ * 2000-09-20 fl  added expand method\r
+ * 2001-03-20 fl  lots of fixes for 2.1b2\r
+ * 2001-04-15 fl  export copyright as Python attribute, not global\r
+ * 2001-04-28 fl  added __copy__ methods (work in progress)\r
+ * 2001-05-14 fl  fixes for 1.5.2 compatibility\r
+ * 2001-07-01 fl  added BIGCHARSET support (from Martin von Loewis)\r
+ * 2001-10-18 fl  fixed group reset issue (from Matthew Mueller)\r
+ * 2001-10-20 fl  added split primitive; reenable unicode for 1.6/2.0/2.1\r
+ * 2001-10-21 fl  added sub/subn primitive\r
+ * 2001-10-24 fl  added finditer primitive (for 2.2 only)\r
+ * 2001-12-07 fl  fixed memory leak in sub/subn (Guido van Rossum)\r
+ * 2002-11-09 fl  fixed empty sub/subn return type\r
+ * 2003-04-18 mvl fully support 4-byte codes\r
+ * 2003-10-17 gn  implemented non recursive scheme\r
+ *\r
+ * Copyright (c) 1997-2001 by Secret Labs AB.  All rights reserved.\r
+ *\r
+ * This version of the SRE library can be redistributed under CNRI's\r
+ * Python 1.6 license.  For any other use, please contact Secret Labs\r
+ * AB (info@pythonware.com).\r
+ *\r
+ * Portions of this engine have been developed in cooperation with\r
+ * CNRI.  Hewlett-Packard provided funding for 1.6 integration and\r
+ * other compatibility work.\r
+ */\r
+\r
+/* Get rid of these macros to prevent collisions between EFI and Python in this file. */\r
+#undef  RETURN_ERROR\r
+#undef  RETURN_SUCCESS\r
+\r
+#ifndef SRE_RECURSIVE\r
+\r
+static char copyright[] =\r
+    " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB ";\r
+\r
+#define PY_SSIZE_T_CLEAN\r
+\r
+#include "Python.h"\r
+#include "structmember.h" /* offsetof */\r
+\r
+#include "sre.h"\r
+\r
+#include <ctype.h>\r
+\r
+/* name of this module, minus the leading underscore */\r
+#if !defined(SRE_MODULE)\r
+#define SRE_MODULE "sre"\r
+#endif\r
+\r
+#define SRE_PY_MODULE "re"\r
+\r
+/* defining this one enables tracing */\r
+#undef VERBOSE\r
+\r
+#if PY_VERSION_HEX >= 0x01060000\r
+#if PY_VERSION_HEX  < 0x02020000 || defined(Py_USING_UNICODE)\r
+/* defining this enables unicode support (default under 1.6a1 and later) */\r
+#define HAVE_UNICODE\r
+#endif\r
+#endif\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* optional features */\r
+\r
+/* enables fast searching */\r
+#define USE_FAST_SEARCH\r
+\r
+/* enables aggressive inlining (always on for Visual C) */\r
+#undef USE_INLINE\r
+\r
+/* enables copy/deepcopy handling (work in progress) */\r
+#undef USE_BUILTIN_COPY\r
+\r
+#if PY_VERSION_HEX < 0x01060000\r
+#define PyObject_DEL(op) PyMem_DEL((op))\r
+#endif\r
+\r
+/* -------------------------------------------------------------------- */\r
+\r
+#if defined(_MSC_VER)\r
+#pragma optimize("gt", on) /* doesn't seem to make much difference... */\r
+#pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */\r
+/* fastest possible local call under MSVC */\r
+#define LOCAL(type) static __inline type __fastcall\r
+#elif defined(USE_INLINE)\r
+#define LOCAL(type) static inline type\r
+#else\r
+#define LOCAL(type) static type\r
+#endif\r
+\r
+/* error codes */\r
+#define SRE_ERROR_ILLEGAL -1 /* illegal opcode */\r
+#define SRE_ERROR_STATE -2 /* illegal state */\r
+#define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */\r
+#define SRE_ERROR_MEMORY -9 /* out of memory */\r
+#define SRE_ERROR_INTERRUPTED -10 /* signal handler raised exception */\r
+\r
+#if defined(VERBOSE)\r
+#define TRACE(v) printf v\r
+#else\r
+#define TRACE(v)\r
+#endif\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* search engine state */\r
+\r
+/* default character predicates (run sre_chars.py to regenerate tables) */\r
+\r
+#define SRE_DIGIT_MASK 1\r
+#define SRE_SPACE_MASK 2\r
+#define SRE_LINEBREAK_MASK 4\r
+#define SRE_ALNUM_MASK 8\r
+#define SRE_WORD_MASK 16\r
+\r
+/* FIXME: this assumes ASCII.  create tables in init_sre() instead */\r
+\r
+static char sre_char_info[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2,\r
+2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,\r
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25,\r
+25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\r
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0,\r
+0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\r
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 };\r
+\r
+static char sre_char_lower[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\r
+10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\r
+27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,\r
+44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\r
+61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,\r
+108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,\r
+122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,\r
+106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,\r
+120, 121, 122, 123, 124, 125, 126, 127 };\r
+\r
+#define SRE_IS_DIGIT(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) : 0)\r
+#define SRE_IS_SPACE(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) : 0)\r
+#define SRE_IS_LINEBREAK(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_LINEBREAK_MASK) : 0)\r
+#define SRE_IS_ALNUM(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_ALNUM_MASK) : 0)\r
+#define SRE_IS_WORD(ch)\\r
+    ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) : 0)\r
+\r
+static unsigned int sre_lower(unsigned int ch)\r
+{\r
+    return ((ch) < 128 ? (unsigned int)sre_char_lower[ch] : ch);\r
+}\r
+\r
+/* locale-specific character predicates */\r
+/* !(c & ~N) == (c < N+1) for any unsigned c, this avoids\r
+ * warnings when c's type supports only numbers < N+1 */\r
+#define SRE_LOC_IS_DIGIT(ch) (!((ch) & ~255) ? isdigit((ch)) : 0)\r
+#define SRE_LOC_IS_SPACE(ch) (!((ch) & ~255) ? isspace((ch)) : 0)\r
+#define SRE_LOC_IS_LINEBREAK(ch) ((ch) == '\n')\r
+#define SRE_LOC_IS_ALNUM(ch) (!((ch) & ~255) ? isalnum((ch)) : 0)\r
+#define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')\r
+\r
+static unsigned int sre_lower_locale(unsigned int ch)\r
+{\r
+    return ((ch) < 256 ? (unsigned int)tolower((ch)) : ch);\r
+}\r
+\r
+/* unicode-specific character predicates */\r
+\r
+#if defined(HAVE_UNICODE)\r
+\r
+#define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDECIMAL((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM((Py_UNICODE)(ch))\r
+#define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM((ch)) || (ch) == '_')\r
+\r
+static unsigned int sre_lower_unicode(unsigned int ch)\r
+{\r
+    return (unsigned int) Py_UNICODE_TOLOWER((Py_UNICODE)(ch));\r
+}\r
+\r
+#endif\r
+\r
+LOCAL(int)\r
+sre_category(SRE_CODE category, unsigned int ch)\r
+{\r
+    switch (category) {\r
+\r
+    case SRE_CATEGORY_DIGIT:\r
+        return SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_NOT_DIGIT:\r
+        return !SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_SPACE:\r
+        return SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_NOT_SPACE:\r
+        return !SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_WORD:\r
+        return SRE_IS_WORD(ch);\r
+    case SRE_CATEGORY_NOT_WORD:\r
+        return !SRE_IS_WORD(ch);\r
+    case SRE_CATEGORY_LINEBREAK:\r
+        return SRE_IS_LINEBREAK(ch);\r
+    case SRE_CATEGORY_NOT_LINEBREAK:\r
+        return !SRE_IS_LINEBREAK(ch);\r
+\r
+    case SRE_CATEGORY_LOC_WORD:\r
+        return SRE_LOC_IS_WORD(ch);\r
+    case SRE_CATEGORY_LOC_NOT_WORD:\r
+        return !SRE_LOC_IS_WORD(ch);\r
+\r
+#if defined(HAVE_UNICODE)\r
+    case SRE_CATEGORY_UNI_DIGIT:\r
+        return SRE_UNI_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_NOT_DIGIT:\r
+        return !SRE_UNI_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_SPACE:\r
+        return SRE_UNI_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_NOT_SPACE:\r
+        return !SRE_UNI_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_WORD:\r
+        return SRE_UNI_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_NOT_WORD:\r
+        return !SRE_UNI_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_LINEBREAK:\r
+        return SRE_UNI_IS_LINEBREAK(ch);\r
+    case SRE_CATEGORY_UNI_NOT_LINEBREAK:\r
+        return !SRE_UNI_IS_LINEBREAK(ch);\r
+#else\r
+    case SRE_CATEGORY_UNI_DIGIT:\r
+        return SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_NOT_DIGIT:\r
+        return !SRE_IS_DIGIT(ch);\r
+    case SRE_CATEGORY_UNI_SPACE:\r
+        return SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_NOT_SPACE:\r
+        return !SRE_IS_SPACE(ch);\r
+    case SRE_CATEGORY_UNI_WORD:\r
+        return SRE_LOC_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_NOT_WORD:\r
+        return !SRE_LOC_IS_WORD(ch);\r
+    case SRE_CATEGORY_UNI_LINEBREAK:\r
+        return SRE_IS_LINEBREAK(ch);\r
+    case SRE_CATEGORY_UNI_NOT_LINEBREAK:\r
+        return !SRE_IS_LINEBREAK(ch);\r
+#endif\r
+    }\r
+    return 0;\r
+}\r
+\r
+/* helpers */\r
+\r
+static void\r
+data_stack_dealloc(SRE_STATE* state)\r
+{\r
+    if (state->data_stack) {\r
+        PyMem_FREE(state->data_stack);\r
+        state->data_stack = NULL;\r
+    }\r
+    state->data_stack_size = state->data_stack_base = 0;\r
+}\r
+\r
+static int\r
+data_stack_grow(SRE_STATE* state, Py_ssize_t size)\r
+{\r
+    Py_ssize_t minsize, cursize;\r
+    minsize = state->data_stack_base+size;\r
+    cursize = state->data_stack_size;\r
+    if (cursize < minsize) {\r
+        void* stack;\r
+        cursize = minsize+minsize/4+1024;\r
+        TRACE(("allocate/grow stack %d\n", cursize));\r
+        stack = PyMem_REALLOC(state->data_stack, cursize);\r
+        if (!stack) {\r
+            data_stack_dealloc(state);\r
+            return SRE_ERROR_MEMORY;\r
+        }\r
+        state->data_stack = (char *)stack;\r
+        state->data_stack_size = cursize;\r
+    }\r
+    return 0;\r
+}\r
+\r
+/* generate 8-bit version */\r
+\r
+#define SRE_CHAR unsigned char\r
+#define SRE_AT sre_at\r
+#define SRE_COUNT sre_count\r
+#define SRE_CHARSET sre_charset\r
+#define SRE_INFO sre_info\r
+#define SRE_MATCH sre_match\r
+#define SRE_MATCH_CONTEXT sre_match_context\r
+#define SRE_SEARCH sre_search\r
+#define SRE_LITERAL_TEMPLATE sre_literal_template\r
+\r
+#if defined(HAVE_UNICODE)\r
+\r
+#define SRE_RECURSIVE\r
+#include "_sre.c"\r
+#undef SRE_RECURSIVE\r
+\r
+#undef SRE_LITERAL_TEMPLATE\r
+#undef SRE_SEARCH\r
+#undef SRE_MATCH\r
+#undef SRE_MATCH_CONTEXT\r
+#undef SRE_INFO\r
+#undef SRE_CHARSET\r
+#undef SRE_COUNT\r
+#undef SRE_AT\r
+#undef SRE_CHAR\r
+\r
+/* generate 16-bit unicode version */\r
+\r
+#define SRE_CHAR Py_UNICODE\r
+#define SRE_AT sre_uat\r
+#define SRE_COUNT sre_ucount\r
+#define SRE_CHARSET sre_ucharset\r
+#define SRE_INFO sre_uinfo\r
+#define SRE_MATCH sre_umatch\r
+#define SRE_MATCH_CONTEXT sre_umatch_context\r
+#define SRE_SEARCH sre_usearch\r
+#define SRE_LITERAL_TEMPLATE sre_uliteral_template\r
+#endif\r
+\r
+#endif /* SRE_RECURSIVE */\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* String matching engine */\r
+\r
+/* the following section is compiled twice, with different character\r
+   settings */\r
+\r
+LOCAL(int)\r
+SRE_AT(SRE_STATE* state, SRE_CHAR* ptr, SRE_CODE at)\r
+{\r
+    /* check if pointer is at given position */\r
+\r
+    Py_ssize_t thisp, thatp;\r
+\r
+    switch (at) {\r
+\r
+    case SRE_AT_BEGINNING:\r
+    case SRE_AT_BEGINNING_STRING:\r
+        return ((void*) ptr == state->beginning);\r
+\r
+    case SRE_AT_BEGINNING_LINE:\r
+        return ((void*) ptr == state->beginning ||\r
+                SRE_IS_LINEBREAK((int) ptr[-1]));\r
+\r
+    case SRE_AT_END:\r
+        return (((void*) (ptr+1) == state->end &&\r
+                 SRE_IS_LINEBREAK((int) ptr[0])) ||\r
+                ((void*) ptr == state->end));\r
+\r
+    case SRE_AT_END_LINE:\r
+        return ((void*) ptr == state->end ||\r
+                SRE_IS_LINEBREAK((int) ptr[0]));\r
+\r
+    case SRE_AT_END_STRING:\r
+        return ((void*) ptr == state->end);\r
+\r
+    case SRE_AT_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp != thatp;\r
+\r
+    case SRE_AT_NON_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp == thatp;\r
+\r
+    case SRE_AT_LOC_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_LOC_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_LOC_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp != thatp;\r
+\r
+    case SRE_AT_LOC_NON_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_LOC_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_LOC_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp == thatp;\r
+\r
+#if defined(HAVE_UNICODE)\r
+    case SRE_AT_UNI_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_UNI_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_UNI_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp != thatp;\r
+\r
+    case SRE_AT_UNI_NON_BOUNDARY:\r
+        if (state->beginning == state->end)\r
+            return 0;\r
+        thatp = ((void*) ptr > state->beginning) ?\r
+            SRE_UNI_IS_WORD((int) ptr[-1]) : 0;\r
+        thisp = ((void*) ptr < state->end) ?\r
+            SRE_UNI_IS_WORD((int) ptr[0]) : 0;\r
+        return thisp == thatp;\r
+#endif\r
+\r
+    }\r
+\r
+    return 0;\r
+}\r
+\r
+LOCAL(int)\r
+SRE_CHARSET(SRE_CODE* set, SRE_CODE ch)\r
+{\r
+    /* check if character is a member of the given set */\r
+\r
+    int ok = 1;\r
+\r
+    for (;;) {\r
+        switch (*set++) {\r
+\r
+        case SRE_OP_FAILURE:\r
+            return !ok;\r
+\r
+        case SRE_OP_LITERAL:\r
+            /* <LITERAL> <code> */\r
+            if (ch == set[0])\r
+                return ok;\r
+            set++;\r
+            break;\r
+\r
+        case SRE_OP_CATEGORY:\r
+            /* <CATEGORY> <code> */\r
+            if (sre_category(set[0], (int) ch))\r
+                return ok;\r
+            set += 1;\r
+            break;\r
+\r
+        case SRE_OP_CHARSET:\r
+            if (sizeof(SRE_CODE) == 2) {\r
+                /* <CHARSET> <bitmap> (16 bits per code word) */\r
+                if (ch < 256 && (set[ch >> 4] & (1 << (ch & 15))))\r
+                    return ok;\r
+                set += 16;\r
+            }\r
+            else {\r
+                /* <CHARSET> <bitmap> (32 bits per code word) */\r
+                if (ch < 256 && (set[ch >> 5] & (1 << (ch & 31))))\r
+                    return ok;\r
+                set += 8;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_RANGE:\r
+            /* <RANGE> <lower> <upper> */\r
+            if (set[0] <= ch && ch <= set[1])\r
+                return ok;\r
+            set += 2;\r
+            break;\r
+\r
+        case SRE_OP_NEGATE:\r
+            ok = !ok;\r
+            break;\r
+\r
+        case SRE_OP_BIGCHARSET:\r
+            /* <BIGCHARSET> <blockcount> <256 blockindices> <blocks> */\r
+        {\r
+            Py_ssize_t count, block;\r
+            count = *(set++);\r
+\r
+            if (sizeof(SRE_CODE) == 2) {\r
+                block = ((unsigned char*)set)[ch >> 8];\r
+                set += 128;\r
+                if (set[block*16 + ((ch & 255)>>4)] & (1 << (ch & 15)))\r
+                    return ok;\r
+                set += count*16;\r
+            }\r
+            else {\r
+                /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids\r
+                 * warnings when c's type supports only numbers < N+1 */\r
+                if (!(ch & ~65535))\r
+                    block = ((unsigned char*)set)[ch >> 8];\r
+                else\r
+                    block = -1;\r
+                set += 64;\r
+                if (block >=0 &&\r
+                    (set[block*8 + ((ch & 255)>>5)] & (1 << (ch & 31))))\r
+                    return ok;\r
+                set += count*8;\r
+            }\r
+            break;\r
+        }\r
+\r
+        default:\r
+            /* internal error -- there's not much we can do about it\r
+               here, so let's just pretend it didn't match... */\r
+            return 0;\r
+        }\r
+    }\r
+}\r
+\r
+LOCAL(Py_ssize_t) SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern);\r
+\r
+LOCAL(Py_ssize_t)\r
+SRE_COUNT(SRE_STATE* state, SRE_CODE* pattern, Py_ssize_t maxcount)\r
+{\r
+    SRE_CODE chr;\r
+    SRE_CHAR* ptr = (SRE_CHAR *)state->ptr;\r
+    SRE_CHAR* end = (SRE_CHAR *)state->end;\r
+    Py_ssize_t i;\r
+\r
+    /* adjust end */\r
+    if (maxcount < end - ptr && maxcount != 65535)\r
+        end = ptr + maxcount;\r
+\r
+    switch (pattern[0]) {\r
+\r
+    case SRE_OP_IN:\r
+        /* repeated set */\r
+        TRACE(("|%p|%p|COUNT IN\n", pattern, ptr));\r
+        while (ptr < end && SRE_CHARSET(pattern + 2, *ptr))\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_ANY:\r
+        /* repeated dot wildcard. */\r
+        TRACE(("|%p|%p|COUNT ANY\n", pattern, ptr));\r
+        while (ptr < end && !SRE_IS_LINEBREAK(*ptr))\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_ANY_ALL:\r
+        /* repeated dot wildcard.  skip to the end of the target\r
+           string, and backtrack from there */\r
+        TRACE(("|%p|%p|COUNT ANY_ALL\n", pattern, ptr));\r
+        ptr = end;\r
+        break;\r
+\r
+    case SRE_OP_LITERAL:\r
+        /* repeated literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT LITERAL %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) *ptr == chr)\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_LITERAL_IGNORE:\r
+        /* repeated literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT LITERAL_IGNORE %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) state->lower(*ptr) == chr)\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_NOT_LITERAL:\r
+        /* repeated non-literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT NOT_LITERAL %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) *ptr != chr)\r
+            ptr++;\r
+        break;\r
+\r
+    case SRE_OP_NOT_LITERAL_IGNORE:\r
+        /* repeated non-literal */\r
+        chr = pattern[1];\r
+        TRACE(("|%p|%p|COUNT NOT_LITERAL_IGNORE %d\n", pattern, ptr, chr));\r
+        while (ptr < end && (SRE_CODE) state->lower(*ptr) != chr)\r
+            ptr++;\r
+        break;\r
+\r
+    default:\r
+        /* repeated single character pattern */\r
+        TRACE(("|%p|%p|COUNT SUBPATTERN\n", pattern, ptr));\r
+        while ((SRE_CHAR*) state->ptr < end) {\r
+            i = SRE_MATCH(state, pattern);\r
+            if (i < 0)\r
+                return i;\r
+            if (!i)\r
+                break;\r
+        }\r
+        TRACE(("|%p|%p|COUNT %d\n", pattern, ptr,\r
+               (SRE_CHAR*) state->ptr - ptr));\r
+        return (SRE_CHAR*) state->ptr - ptr;\r
+    }\r
+\r
+    TRACE(("|%p|%p|COUNT %d\n", pattern, ptr, ptr - (SRE_CHAR*) state->ptr));\r
+    return ptr - (SRE_CHAR*) state->ptr;\r
+}\r
+\r
+#if 0 /* not used in this release */\r
+LOCAL(int)\r
+SRE_INFO(SRE_STATE* state, SRE_CODE* pattern)\r
+{\r
+    /* check if an SRE_OP_INFO block matches at the current position.\r
+       returns the number of SRE_CODE objects to skip if successful, 0\r
+       if no match */\r
+\r
+    SRE_CHAR* end = state->end;\r
+    SRE_CHAR* ptr = state->ptr;\r
+    Py_ssize_t i;\r
+\r
+    /* check minimal length */\r
+    if (pattern[3] && (end - ptr) < pattern[3])\r
+        return 0;\r
+\r
+    /* check known prefix */\r
+    if (pattern[2] & SRE_INFO_PREFIX && pattern[5] > 1) {\r
+        /* <length> <skip> <prefix data> <overlap data> */\r
+        for (i = 0; i < pattern[5]; i++)\r
+            if ((SRE_CODE) ptr[i] != pattern[7 + i])\r
+                return 0;\r
+        return pattern[0] + 2 * pattern[6];\r
+    }\r
+    return pattern[0];\r
+}\r
+#endif\r
+\r
+/* The macros below should be used to protect recursive SRE_MATCH()\r
+ * calls that *failed* and do *not* return immediately (IOW, those\r
+ * that will backtrack). Explaining:\r
+ *\r
+ * - Recursive SRE_MATCH() returned true: that's usually a success\r
+ *   (besides atypical cases like ASSERT_NOT), therefore there's no\r
+ *   reason to restore lastmark;\r
+ *\r
+ * - Recursive SRE_MATCH() returned false but the current SRE_MATCH()\r
+ *   is returning to the caller: If the current SRE_MATCH() is the\r
+ *   top function of the recursion, returning false will be a matching\r
+ *   failure, and it doesn't matter where lastmark is pointing to.\r
+ *   If it's *not* the top function, it will be a recursive SRE_MATCH()\r
+ *   failure by itself, and the calling SRE_MATCH() will have to deal\r
+ *   with the failure by the same rules explained here (it will restore\r
+ *   lastmark by itself if necessary);\r
+ *\r
+ * - Recursive SRE_MATCH() returned false, and will continue the\r
+ *   outside 'for' loop: must be protected when breaking, since the next\r
+ *   OP could potentially depend on lastmark;\r
+ *\r
+ * - Recursive SRE_MATCH() returned false, and will be called again\r
+ *   inside a local for/while loop: must be protected between each\r
+ *   loop iteration, since the recursive SRE_MATCH() could do anything,\r
+ *   and could potentially depend on lastmark.\r
+ *\r
+ * For more information, check the discussion at SF patch #712900.\r
+ */\r
+#define LASTMARK_SAVE()     \\r
+    do { \\r
+        ctx->lastmark = state->lastmark; \\r
+        ctx->lastindex = state->lastindex; \\r
+    } while (0)\r
+#define LASTMARK_RESTORE()  \\r
+    do { \\r
+        state->lastmark = ctx->lastmark; \\r
+        state->lastindex = ctx->lastindex; \\r
+    } while (0)\r
+\r
+#define RETURN_ERROR(i) do { return i; } while(0)\r
+#define RETURN_FAILURE do { ret = 0; goto exit; } while(0)\r
+#define RETURN_SUCCESS do { ret = 1; goto exit; } while(0)\r
+\r
+#define RETURN_ON_ERROR(i) \\r
+    do { if (i < 0) RETURN_ERROR(i); } while (0)\r
+#define RETURN_ON_SUCCESS(i) \\r
+    do { RETURN_ON_ERROR(i); if (i > 0) RETURN_SUCCESS; } while (0)\r
+#define RETURN_ON_FAILURE(i) \\r
+    do { RETURN_ON_ERROR(i); if (i == 0) RETURN_FAILURE; } while (0)\r
+\r
+#define SFY(x) #x\r
+\r
+#define DATA_STACK_ALLOC(state, type, ptr) \\r
+do { \\r
+    alloc_pos = state->data_stack_base; \\r
+    TRACE(("allocating %s in %d (%d)\n", \\r
+           SFY(type), alloc_pos, sizeof(type))); \\r
+    if (state->data_stack_size < alloc_pos+sizeof(type)) { \\r
+        int j = data_stack_grow(state, sizeof(type)); \\r
+        if (j < 0) return j; \\r
+        if (ctx_pos != -1) \\r
+            DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \\r
+    } \\r
+    ptr = (type*)(state->data_stack+alloc_pos); \\r
+    state->data_stack_base += sizeof(type); \\r
+} while (0)\r
+\r
+#define DATA_STACK_LOOKUP_AT(state, type, ptr, pos) \\r
+do { \\r
+    TRACE(("looking up %s at %d\n", SFY(type), pos)); \\r
+    ptr = (type*)(state->data_stack+pos); \\r
+} while (0)\r
+\r
+#define DATA_STACK_PUSH(state, data, size) \\r
+do { \\r
+    TRACE(("copy data in %p to %d (%d)\n", \\r
+           data, state->data_stack_base, size)); \\r
+    if (state->data_stack_size < state->data_stack_base+size) { \\r
+        int j = data_stack_grow(state, size); \\r
+        if (j < 0) return j; \\r
+        if (ctx_pos != -1) \\r
+            DATA_STACK_LOOKUP_AT(state, SRE_MATCH_CONTEXT, ctx, ctx_pos); \\r
+    } \\r
+    memcpy(state->data_stack+state->data_stack_base, data, size); \\r
+    state->data_stack_base += size; \\r
+} while (0)\r
+\r
+#define DATA_STACK_POP(state, data, size, discard) \\r
+do { \\r
+    TRACE(("copy data to %p from %d (%d)\n", \\r
+           data, state->data_stack_base-size, size)); \\r
+    memcpy(data, state->data_stack+state->data_stack_base-size, size); \\r
+    if (discard) \\r
+        state->data_stack_base -= size; \\r
+} while (0)\r
+\r
+#define DATA_STACK_POP_DISCARD(state, size) \\r
+do { \\r
+    TRACE(("discard data from %d (%d)\n", \\r
+           state->data_stack_base-size, size)); \\r
+    state->data_stack_base -= size; \\r
+} while(0)\r
+\r
+#define DATA_PUSH(x) \\r
+    DATA_STACK_PUSH(state, (x), sizeof(*(x)))\r
+#define DATA_POP(x) \\r
+    DATA_STACK_POP(state, (x), sizeof(*(x)), 1)\r
+#define DATA_POP_DISCARD(x) \\r
+    DATA_STACK_POP_DISCARD(state, sizeof(*(x)))\r
+#define DATA_ALLOC(t,p) \\r
+    DATA_STACK_ALLOC(state, t, p)\r
+#define DATA_LOOKUP_AT(t,p,pos) \\r
+    DATA_STACK_LOOKUP_AT(state,t,p,pos)\r
+\r
+#define MARK_PUSH(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        i = lastmark; /* ctx->lastmark may change if reallocated */ \\r
+        DATA_STACK_PUSH(state, state->mark, (i+1)*sizeof(void*)); \\r
+    } while (0)\r
+#define MARK_POP(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 1); \\r
+    } while (0)\r
+#define MARK_POP_KEEP(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        DATA_STACK_POP(state, state->mark, (lastmark+1)*sizeof(void*), 0); \\r
+    } while (0)\r
+#define MARK_POP_DISCARD(lastmark) \\r
+    do if (lastmark > 0) { \\r
+        DATA_STACK_POP_DISCARD(state, (lastmark+1)*sizeof(void*)); \\r
+    } while (0)\r
+\r
+#define JUMP_NONE            0\r
+#define JUMP_MAX_UNTIL_1     1\r
+#define JUMP_MAX_UNTIL_2     2\r
+#define JUMP_MAX_UNTIL_3     3\r
+#define JUMP_MIN_UNTIL_1     4\r
+#define JUMP_MIN_UNTIL_2     5\r
+#define JUMP_MIN_UNTIL_3     6\r
+#define JUMP_REPEAT          7\r
+#define JUMP_REPEAT_ONE_1    8\r
+#define JUMP_REPEAT_ONE_2    9\r
+#define JUMP_MIN_REPEAT_ONE  10\r
+#define JUMP_BRANCH          11\r
+#define JUMP_ASSERT          12\r
+#define JUMP_ASSERT_NOT      13\r
+\r
+#define DO_JUMP(jumpvalue, jumplabel, nextpattern) \\r
+    DATA_ALLOC(SRE_MATCH_CONTEXT, nextctx); \\r
+    nextctx->last_ctx_pos = ctx_pos; \\r
+    nextctx->jump = jumpvalue; \\r
+    nextctx->pattern = nextpattern; \\r
+    ctx_pos = alloc_pos; \\r
+    ctx = nextctx; \\r
+    goto entrance; \\r
+    jumplabel: \\r
+    while (0) /* gcc doesn't like labels at end of scopes */ \\r
+\r
+typedef struct {\r
+    Py_ssize_t last_ctx_pos;\r
+    Py_ssize_t jump;\r
+    SRE_CHAR* ptr;\r
+    SRE_CODE* pattern;\r
+    Py_ssize_t count;\r
+    Py_ssize_t lastmark;\r
+    Py_ssize_t lastindex;\r
+    union {\r
+        SRE_CODE chr;\r
+        SRE_REPEAT* rep;\r
+    } u;\r
+} SRE_MATCH_CONTEXT;\r
+\r
+/* check if string matches the given pattern.  returns <0 for\r
+   error, 0 for failure, and 1 for success */\r
+LOCAL(Py_ssize_t)\r
+SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern)\r
+{\r
+    SRE_CHAR* end = (SRE_CHAR *)state->end;\r
+    Py_ssize_t alloc_pos, ctx_pos = -1;\r
+    Py_ssize_t i, ret = 0;\r
+    Py_ssize_t jump;\r
+    unsigned int sigcount=0;\r
+\r
+    SRE_MATCH_CONTEXT* ctx;\r
+    SRE_MATCH_CONTEXT* nextctx;\r
+\r
+    TRACE(("|%p|%p|ENTER\n", pattern, state->ptr));\r
+\r
+    DATA_ALLOC(SRE_MATCH_CONTEXT, ctx);\r
+    ctx->last_ctx_pos = -1;\r
+    ctx->jump = JUMP_NONE;\r
+    ctx->pattern = pattern;\r
+    ctx_pos = alloc_pos;\r
+\r
+entrance:\r
+\r
+    ctx->ptr = (SRE_CHAR *)state->ptr;\r
+\r
+    if (ctx->pattern[0] == SRE_OP_INFO) {\r
+        /* optimization info block */\r
+        /* <INFO> <1=skip> <2=flags> <3=min> ... */\r
+        if (ctx->pattern[3] && (end - ctx->ptr) < ctx->pattern[3]) {\r
+            TRACE(("reject (got %d chars, need %d)\n",\r
+                   (end - ctx->ptr), ctx->pattern[3]));\r
+            RETURN_FAILURE;\r
+        }\r
+        ctx->pattern += ctx->pattern[1] + 1;\r
+    }\r
+\r
+    for (;;) {\r
+        ++sigcount;\r
+        if ((0 == (sigcount & 0xfff)) && PyErr_CheckSignals())\r
+            RETURN_ERROR(SRE_ERROR_INTERRUPTED);\r
+\r
+        switch (*ctx->pattern++) {\r
+\r
+        case SRE_OP_MARK:\r
+            /* set mark */\r
+            /* <MARK> <gid> */\r
+            TRACE(("|%p|%p|MARK %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            i = ctx->pattern[0];\r
+            if (i & 1)\r
+                state->lastindex = i/2 + 1;\r
+            if (i > state->lastmark) {\r
+                /* state->lastmark is the highest valid index in the\r
+                   state->mark array.  If it is increased by more than 1,\r
+                   the intervening marks must be set to NULL to signal\r
+                   that these marks have not been encountered. */\r
+                Py_ssize_t j = state->lastmark + 1;\r
+                while (j < i)\r
+                    state->mark[j++] = NULL;\r
+                state->lastmark = i;\r
+            }\r
+            state->mark[i] = ctx->ptr;\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_LITERAL:\r
+            /* match literal string */\r
+            /* <LITERAL> <code> */\r
+            TRACE(("|%p|%p|LITERAL %d\n", ctx->pattern,\r
+                   ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] != ctx->pattern[0])\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_NOT_LITERAL:\r
+            /* match anything that is not literal character */\r
+            /* <NOT_LITERAL> <code> */\r
+            TRACE(("|%p|%p|NOT_LITERAL %d\n", ctx->pattern,\r
+                   ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end || (SRE_CODE) ctx->ptr[0] == ctx->pattern[0])\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_SUCCESS:\r
+            /* end of pattern */\r
+            TRACE(("|%p|%p|SUCCESS\n", ctx->pattern, ctx->ptr));\r
+            state->ptr = ctx->ptr;\r
+            RETURN_SUCCESS;\r
+\r
+        case SRE_OP_AT:\r
+            /* match at given position */\r
+            /* <AT> <code> */\r
+            TRACE(("|%p|%p|AT %d\n", ctx->pattern, ctx->ptr, *ctx->pattern));\r
+            if (!SRE_AT(state, ctx->ptr, *ctx->pattern))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_CATEGORY:\r
+            /* match at given category */\r
+            /* <CATEGORY> <code> */\r
+            TRACE(("|%p|%p|CATEGORY %d\n", ctx->pattern,\r
+                   ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end || !sre_category(ctx->pattern[0], ctx->ptr[0]))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_ANY:\r
+            /* match anything (except a newline) */\r
+            /* <ANY> */\r
+            TRACE(("|%p|%p|ANY\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end || SRE_IS_LINEBREAK(ctx->ptr[0]))\r
+                RETURN_FAILURE;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_ANY_ALL:\r
+            /* match anything */\r
+            /* <ANY_ALL> */\r
+            TRACE(("|%p|%p|ANY_ALL\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end)\r
+                RETURN_FAILURE;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_IN:\r
+            /* match set member (or non_member) */\r
+            /* <IN> <skip> <set> */\r
+            TRACE(("|%p|%p|IN\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end || !SRE_CHARSET(ctx->pattern + 1, *ctx->ptr))\r
+                RETURN_FAILURE;\r
+            ctx->pattern += ctx->pattern[0];\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_LITERAL_IGNORE:\r
+            TRACE(("|%p|%p|LITERAL_IGNORE %d\n",\r
+                   ctx->pattern, ctx->ptr, ctx->pattern[0]));\r
+            if (ctx->ptr >= end ||\r
+                state->lower(*ctx->ptr) != state->lower(*ctx->pattern))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_NOT_LITERAL_IGNORE:\r
+            TRACE(("|%p|%p|NOT_LITERAL_IGNORE %d\n",\r
+                   ctx->pattern, ctx->ptr, *ctx->pattern));\r
+            if (ctx->ptr >= end ||\r
+                state->lower(*ctx->ptr) == state->lower(*ctx->pattern))\r
+                RETURN_FAILURE;\r
+            ctx->pattern++;\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_IN_IGNORE:\r
+            TRACE(("|%p|%p|IN_IGNORE\n", ctx->pattern, ctx->ptr));\r
+            if (ctx->ptr >= end\r
+                || !SRE_CHARSET(ctx->pattern+1,\r
+                                (SRE_CODE)state->lower(*ctx->ptr)))\r
+                RETURN_FAILURE;\r
+            ctx->pattern += ctx->pattern[0];\r
+            ctx->ptr++;\r
+            break;\r
+\r
+        case SRE_OP_JUMP:\r
+        case SRE_OP_INFO:\r
+            /* jump forward */\r
+            /* <JUMP> <offset> */\r
+            TRACE(("|%p|%p|JUMP %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            ctx->pattern += ctx->pattern[0];\r
+            break;\r
+\r
+        case SRE_OP_BRANCH:\r
+            /* alternation */\r
+            /* <BRANCH> <0=skip> code <JUMP> ... <NULL> */\r
+            TRACE(("|%p|%p|BRANCH\n", ctx->pattern, ctx->ptr));\r
+            LASTMARK_SAVE();\r
+            ctx->u.rep = state->repeat;\r
+            if (ctx->u.rep)\r
+                MARK_PUSH(ctx->lastmark);\r
+            for (; ctx->pattern[0]; ctx->pattern += ctx->pattern[0]) {\r
+                if (ctx->pattern[1] == SRE_OP_LITERAL &&\r
+                    (ctx->ptr >= end ||\r
+                     (SRE_CODE) *ctx->ptr != ctx->pattern[2]))\r
+                    continue;\r
+                if (ctx->pattern[1] == SRE_OP_IN &&\r
+                    (ctx->ptr >= end ||\r
+                     !SRE_CHARSET(ctx->pattern + 3, (SRE_CODE) *ctx->ptr)))\r
+                    continue;\r
+                state->ptr = ctx->ptr;\r
+                DO_JUMP(JUMP_BRANCH, jump_branch, ctx->pattern+1);\r
+                if (ret) {\r
+                    if (ctx->u.rep)\r
+                        MARK_POP_DISCARD(ctx->lastmark);\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                if (ctx->u.rep)\r
+                    MARK_POP_KEEP(ctx->lastmark);\r
+                LASTMARK_RESTORE();\r
+            }\r
+            if (ctx->u.rep)\r
+                MARK_POP_DISCARD(ctx->lastmark);\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_REPEAT_ONE:\r
+            /* match repeated sequence (maximizing regexp) */\r
+\r
+            /* this operator only works if the repeated item is\r
+               exactly one character wide, and we're not already\r
+               collecting backtracking points.  for other cases,\r
+               use the MAX_REPEAT operator */\r
+\r
+            /* <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */\r
+\r
+            TRACE(("|%p|%p|REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[1], ctx->pattern[2]));\r
+\r
+            if (ctx->ptr + ctx->pattern[1] > end)\r
+                RETURN_FAILURE; /* cannot match */\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[2]);\r
+            RETURN_ON_ERROR(ret);\r
+            DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+            ctx->count = ret;\r
+            ctx->ptr += ctx->count;\r
+\r
+            /* when we arrive here, count contains the number of\r
+               matches, and ctx->ptr points to the tail of the target\r
+               string.  check if the rest of the pattern matches,\r
+               and backtrack if not. */\r
+\r
+            if (ctx->count < (Py_ssize_t) ctx->pattern[1])\r
+                RETURN_FAILURE;\r
+\r
+            if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) {\r
+                /* tail is empty.  we're finished */\r
+                state->ptr = ctx->ptr;\r
+                RETURN_SUCCESS;\r
+            }\r
+\r
+            LASTMARK_SAVE();\r
+\r
+            if (ctx->pattern[ctx->pattern[0]] == SRE_OP_LITERAL) {\r
+                /* tail starts with a literal. skip positions where\r
+                   the rest of the pattern cannot possibly match */\r
+                ctx->u.chr = ctx->pattern[ctx->pattern[0]+1];\r
+                for (;;) {\r
+                    while (ctx->count >= (Py_ssize_t) ctx->pattern[1] &&\r
+                           (ctx->ptr >= end || *ctx->ptr != ctx->u.chr)) {\r
+                        ctx->ptr--;\r
+                        ctx->count--;\r
+                    }\r
+                    if (ctx->count < (Py_ssize_t) ctx->pattern[1])\r
+                        break;\r
+                    state->ptr = ctx->ptr;\r
+                    DO_JUMP(JUMP_REPEAT_ONE_1, jump_repeat_one_1,\r
+                            ctx->pattern+ctx->pattern[0]);\r
+                    if (ret) {\r
+                        RETURN_ON_ERROR(ret);\r
+                        RETURN_SUCCESS;\r
+                    }\r
+\r
+                    LASTMARK_RESTORE();\r
+\r
+                    ctx->ptr--;\r
+                    ctx->count--;\r
+                }\r
+\r
+            } else {\r
+                /* general case */\r
+                while (ctx->count >= (Py_ssize_t) ctx->pattern[1]) {\r
+                    state->ptr = ctx->ptr;\r
+                    DO_JUMP(JUMP_REPEAT_ONE_2, jump_repeat_one_2,\r
+                            ctx->pattern+ctx->pattern[0]);\r
+                    if (ret) {\r
+                        RETURN_ON_ERROR(ret);\r
+                        RETURN_SUCCESS;\r
+                    }\r
+                    ctx->ptr--;\r
+                    ctx->count--;\r
+                    LASTMARK_RESTORE();\r
+                }\r
+            }\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_MIN_REPEAT_ONE:\r
+            /* match repeated sequence (minimizing regexp) */\r
+\r
+            /* this operator only works if the repeated item is\r
+               exactly one character wide, and we're not already\r
+               collecting backtracking points.  for other cases,\r
+               use the MIN_REPEAT operator */\r
+\r
+            /* <MIN_REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */\r
+\r
+            TRACE(("|%p|%p|MIN_REPEAT_ONE %d %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[1], ctx->pattern[2]));\r
+\r
+            if (ctx->ptr + ctx->pattern[1] > end)\r
+                RETURN_FAILURE; /* cannot match */\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            if (ctx->pattern[1] == 0)\r
+                ctx->count = 0;\r
+            else {\r
+                /* count using pattern min as the maximum */\r
+                ret = SRE_COUNT(state, ctx->pattern+3, ctx->pattern[1]);\r
+                RETURN_ON_ERROR(ret);\r
+                DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+                if (ret < (Py_ssize_t) ctx->pattern[1])\r
+                    /* didn't match minimum number of times */\r
+                    RETURN_FAILURE;\r
+                /* advance past minimum matches of repeat */\r
+                ctx->count = ret;\r
+                ctx->ptr += ctx->count;\r
+            }\r
+\r
+            if (ctx->pattern[ctx->pattern[0]] == SRE_OP_SUCCESS) {\r
+                /* tail is empty.  we're finished */\r
+                state->ptr = ctx->ptr;\r
+                RETURN_SUCCESS;\r
+\r
+            } else {\r
+                /* general case */\r
+                LASTMARK_SAVE();\r
+                while ((Py_ssize_t)ctx->pattern[2] == 65535\r
+                       || ctx->count <= (Py_ssize_t)ctx->pattern[2]) {\r
+                    state->ptr = ctx->ptr;\r
+                    DO_JUMP(JUMP_MIN_REPEAT_ONE,jump_min_repeat_one,\r
+                            ctx->pattern+ctx->pattern[0]);\r
+                    if (ret) {\r
+                        RETURN_ON_ERROR(ret);\r
+                        RETURN_SUCCESS;\r
+                    }\r
+                    state->ptr = ctx->ptr;\r
+                    ret = SRE_COUNT(state, ctx->pattern+3, 1);\r
+                    RETURN_ON_ERROR(ret);\r
+                    DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+                    if (ret == 0)\r
+                        break;\r
+                    assert(ret == 1);\r
+                    ctx->ptr++;\r
+                    ctx->count++;\r
+                    LASTMARK_RESTORE();\r
+                }\r
+            }\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_REPEAT:\r
+            /* create repeat context.  all the hard work is done\r
+               by the UNTIL operator (MAX_UNTIL, MIN_UNTIL) */\r
+            /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */\r
+            TRACE(("|%p|%p|REPEAT %d %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[1], ctx->pattern[2]));\r
+\r
+            /* install new repeat context */\r
+            ctx->u.rep = (SRE_REPEAT*) PyObject_MALLOC(sizeof(*ctx->u.rep));\r
+            if (!ctx->u.rep) {\r
+                PyErr_NoMemory();\r
+                RETURN_FAILURE;\r
+            }\r
+            ctx->u.rep->count = -1;\r
+            ctx->u.rep->pattern = ctx->pattern;\r
+            ctx->u.rep->prev = state->repeat;\r
+            ctx->u.rep->last_ptr = NULL;\r
+            state->repeat = ctx->u.rep;\r
+\r
+            state->ptr = ctx->ptr;\r
+            DO_JUMP(JUMP_REPEAT, jump_repeat, ctx->pattern+ctx->pattern[0]);\r
+            state->repeat = ctx->u.rep->prev;\r
+            PyObject_FREE(ctx->u.rep);\r
+\r
+            if (ret) {\r
+                RETURN_ON_ERROR(ret);\r
+                RETURN_SUCCESS;\r
+            }\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_MAX_UNTIL:\r
+            /* maximizing repeat */\r
+            /* <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail */\r
+\r
+            /* FIXME: we probably need to deal with zero-width\r
+               matches in here... */\r
+\r
+            ctx->u.rep = state->repeat;\r
+            if (!ctx->u.rep)\r
+                RETURN_ERROR(SRE_ERROR_STATE);\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            ctx->count = ctx->u.rep->count+1;\r
+\r
+            TRACE(("|%p|%p|MAX_UNTIL %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->count));\r
+\r
+            if (ctx->count < ctx->u.rep->pattern[1]) {\r
+                /* not enough matches */\r
+                ctx->u.rep->count = ctx->count;\r
+                DO_JUMP(JUMP_MAX_UNTIL_1, jump_max_until_1,\r
+                        ctx->u.rep->pattern+3);\r
+                if (ret) {\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                ctx->u.rep->count = ctx->count-1;\r
+                state->ptr = ctx->ptr;\r
+                RETURN_FAILURE;\r
+            }\r
+\r
+            if ((ctx->count < ctx->u.rep->pattern[2] ||\r
+                ctx->u.rep->pattern[2] == 65535) &&\r
+                state->ptr != ctx->u.rep->last_ptr) {\r
+                /* we may have enough matches, but if we can\r
+                   match another item, do so */\r
+                ctx->u.rep->count = ctx->count;\r
+                LASTMARK_SAVE();\r
+                MARK_PUSH(ctx->lastmark);\r
+                /* zero-width match protection */\r
+                DATA_PUSH(&ctx->u.rep->last_ptr);\r
+                ctx->u.rep->last_ptr = state->ptr;\r
+                DO_JUMP(JUMP_MAX_UNTIL_2, jump_max_until_2,\r
+                        ctx->u.rep->pattern+3);\r
+                DATA_POP(&ctx->u.rep->last_ptr);\r
+                if (ret) {\r
+                    MARK_POP_DISCARD(ctx->lastmark);\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                MARK_POP(ctx->lastmark);\r
+                LASTMARK_RESTORE();\r
+                ctx->u.rep->count = ctx->count-1;\r
+                state->ptr = ctx->ptr;\r
+            }\r
+\r
+            /* cannot match more repeated items here.  make sure the\r
+               tail matches */\r
+            state->repeat = ctx->u.rep->prev;\r
+            DO_JUMP(JUMP_MAX_UNTIL_3, jump_max_until_3, ctx->pattern);\r
+            RETURN_ON_SUCCESS(ret);\r
+            state->repeat = ctx->u.rep;\r
+            state->ptr = ctx->ptr;\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_MIN_UNTIL:\r
+            /* minimizing repeat */\r
+            /* <REPEAT> <skip> <1=min> <2=max> item <MIN_UNTIL> tail */\r
+\r
+            ctx->u.rep = state->repeat;\r
+            if (!ctx->u.rep)\r
+                RETURN_ERROR(SRE_ERROR_STATE);\r
+\r
+            state->ptr = ctx->ptr;\r
+\r
+            ctx->count = ctx->u.rep->count+1;\r
+\r
+            TRACE(("|%p|%p|MIN_UNTIL %d %p\n", ctx->pattern,\r
+                   ctx->ptr, ctx->count, ctx->u.rep->pattern));\r
+\r
+            if (ctx->count < ctx->u.rep->pattern[1]) {\r
+                /* not enough matches */\r
+                ctx->u.rep->count = ctx->count;\r
+                DO_JUMP(JUMP_MIN_UNTIL_1, jump_min_until_1,\r
+                        ctx->u.rep->pattern+3);\r
+                if (ret) {\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_SUCCESS;\r
+                }\r
+                ctx->u.rep->count = ctx->count-1;\r
+                state->ptr = ctx->ptr;\r
+                RETURN_FAILURE;\r
+            }\r
+\r
+            LASTMARK_SAVE();\r
+\r
+            /* see if the tail matches */\r
+            state->repeat = ctx->u.rep->prev;\r
+            DO_JUMP(JUMP_MIN_UNTIL_2, jump_min_until_2, ctx->pattern);\r
+            if (ret) {\r
+                RETURN_ON_ERROR(ret);\r
+                RETURN_SUCCESS;\r
+            }\r
+\r
+            state->repeat = ctx->u.rep;\r
+            state->ptr = ctx->ptr;\r
+\r
+            LASTMARK_RESTORE();\r
+\r
+            if (ctx->count >= ctx->u.rep->pattern[2]\r
+                && ctx->u.rep->pattern[2] != 65535)\r
+                RETURN_FAILURE;\r
+\r
+            ctx->u.rep->count = ctx->count;\r
+            DO_JUMP(JUMP_MIN_UNTIL_3,jump_min_until_3,\r
+                    ctx->u.rep->pattern+3);\r
+            if (ret) {\r
+                RETURN_ON_ERROR(ret);\r
+                RETURN_SUCCESS;\r
+            }\r
+            ctx->u.rep->count = ctx->count-1;\r
+            state->ptr = ctx->ptr;\r
+            RETURN_FAILURE;\r
+\r
+        case SRE_OP_GROUPREF:\r
+            /* match backreference */\r
+            TRACE(("|%p|%p|GROUPREF %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            i = ctx->pattern[0];\r
+            {\r
+                Py_ssize_t groupref = i+i;\r
+                if (groupref >= state->lastmark) {\r
+                    RETURN_FAILURE;\r
+                } else {\r
+                    SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];\r
+                    SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];\r
+                    if (!p || !e || e < p)\r
+                        RETURN_FAILURE;\r
+                    while (p < e) {\r
+                        if (ctx->ptr >= end || *ctx->ptr != *p)\r
+                            RETURN_FAILURE;\r
+                        p++; ctx->ptr++;\r
+                    }\r
+                }\r
+            }\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF_IGNORE:\r
+            /* match backreference */\r
+            TRACE(("|%p|%p|GROUPREF_IGNORE %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            i = ctx->pattern[0];\r
+            {\r
+                Py_ssize_t groupref = i+i;\r
+                if (groupref >= state->lastmark) {\r
+                    RETURN_FAILURE;\r
+                } else {\r
+                    SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];\r
+                    SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];\r
+                    if (!p || !e || e < p)\r
+                        RETURN_FAILURE;\r
+                    while (p < e) {\r
+                        if (ctx->ptr >= end ||\r
+                            state->lower(*ctx->ptr) != state->lower(*p))\r
+                            RETURN_FAILURE;\r
+                        p++; ctx->ptr++;\r
+                    }\r
+                }\r
+            }\r
+            ctx->pattern++;\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF_EXISTS:\r
+            TRACE(("|%p|%p|GROUPREF_EXISTS %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[0]));\r
+            /* <GROUPREF_EXISTS> <group> <skip> codeyes <JUMP> codeno ... */\r
+            i = ctx->pattern[0];\r
+            {\r
+                Py_ssize_t groupref = i+i;\r
+                if (groupref >= state->lastmark) {\r
+                    ctx->pattern += ctx->pattern[1];\r
+                    break;\r
+                } else {\r
+                    SRE_CHAR* p = (SRE_CHAR*) state->mark[groupref];\r
+                    SRE_CHAR* e = (SRE_CHAR*) state->mark[groupref+1];\r
+                    if (!p || !e || e < p) {\r
+                        ctx->pattern += ctx->pattern[1];\r
+                        break;\r
+                    }\r
+                }\r
+            }\r
+            ctx->pattern += 2;\r
+            break;\r
+\r
+        case SRE_OP_ASSERT:\r
+            /* assert subpattern */\r
+            /* <ASSERT> <skip> <back> <pattern> */\r
+            TRACE(("|%p|%p|ASSERT %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[1]));\r
+            state->ptr = ctx->ptr - ctx->pattern[1];\r
+            if (state->ptr < state->beginning)\r
+                RETURN_FAILURE;\r
+            DO_JUMP(JUMP_ASSERT, jump_assert, ctx->pattern+2);\r
+            RETURN_ON_FAILURE(ret);\r
+            ctx->pattern += ctx->pattern[0];\r
+            break;\r
+\r
+        case SRE_OP_ASSERT_NOT:\r
+            /* assert not subpattern */\r
+            /* <ASSERT_NOT> <skip> <back> <pattern> */\r
+            TRACE(("|%p|%p|ASSERT_NOT %d\n", ctx->pattern,\r
+                   ctx->ptr, ctx->pattern[1]));\r
+            state->ptr = ctx->ptr - ctx->pattern[1];\r
+            if (state->ptr >= state->beginning) {\r
+                DO_JUMP(JUMP_ASSERT_NOT, jump_assert_not, ctx->pattern+2);\r
+                if (ret) {\r
+                    RETURN_ON_ERROR(ret);\r
+                    RETURN_FAILURE;\r
+                }\r
+            }\r
+            ctx->pattern += ctx->pattern[0];\r
+            break;\r
+\r
+        case SRE_OP_FAILURE:\r
+            /* immediate failure */\r
+            TRACE(("|%p|%p|FAILURE\n", ctx->pattern, ctx->ptr));\r
+            RETURN_FAILURE;\r
+\r
+        default:\r
+            TRACE(("|%p|%p|UNKNOWN %d\n", ctx->pattern, ctx->ptr,\r
+                   ctx->pattern[-1]));\r
+            RETURN_ERROR(SRE_ERROR_ILLEGAL);\r
+        }\r
+    }\r
+\r
+exit:\r
+    ctx_pos = ctx->last_ctx_pos;\r
+    jump = ctx->jump;\r
+    DATA_POP_DISCARD(ctx);\r
+    if (ctx_pos == -1)\r
+        return ret;\r
+    DATA_LOOKUP_AT(SRE_MATCH_CONTEXT, ctx, ctx_pos);\r
+\r
+    switch (jump) {\r
+        case JUMP_MAX_UNTIL_2:\r
+            TRACE(("|%p|%p|JUMP_MAX_UNTIL_2\n", ctx->pattern, ctx->ptr));\r
+            goto jump_max_until_2;\r
+        case JUMP_MAX_UNTIL_3:\r
+            TRACE(("|%p|%p|JUMP_MAX_UNTIL_3\n", ctx->pattern, ctx->ptr));\r
+            goto jump_max_until_3;\r
+        case JUMP_MIN_UNTIL_2:\r
+            TRACE(("|%p|%p|JUMP_MIN_UNTIL_2\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_until_2;\r
+        case JUMP_MIN_UNTIL_3:\r
+            TRACE(("|%p|%p|JUMP_MIN_UNTIL_3\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_until_3;\r
+        case JUMP_BRANCH:\r
+            TRACE(("|%p|%p|JUMP_BRANCH\n", ctx->pattern, ctx->ptr));\r
+            goto jump_branch;\r
+        case JUMP_MAX_UNTIL_1:\r
+            TRACE(("|%p|%p|JUMP_MAX_UNTIL_1\n", ctx->pattern, ctx->ptr));\r
+            goto jump_max_until_1;\r
+        case JUMP_MIN_UNTIL_1:\r
+            TRACE(("|%p|%p|JUMP_MIN_UNTIL_1\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_until_1;\r
+        case JUMP_REPEAT:\r
+            TRACE(("|%p|%p|JUMP_REPEAT\n", ctx->pattern, ctx->ptr));\r
+            goto jump_repeat;\r
+        case JUMP_REPEAT_ONE_1:\r
+            TRACE(("|%p|%p|JUMP_REPEAT_ONE_1\n", ctx->pattern, ctx->ptr));\r
+            goto jump_repeat_one_1;\r
+        case JUMP_REPEAT_ONE_2:\r
+            TRACE(("|%p|%p|JUMP_REPEAT_ONE_2\n", ctx->pattern, ctx->ptr));\r
+            goto jump_repeat_one_2;\r
+        case JUMP_MIN_REPEAT_ONE:\r
+            TRACE(("|%p|%p|JUMP_MIN_REPEAT_ONE\n", ctx->pattern, ctx->ptr));\r
+            goto jump_min_repeat_one;\r
+        case JUMP_ASSERT:\r
+            TRACE(("|%p|%p|JUMP_ASSERT\n", ctx->pattern, ctx->ptr));\r
+            goto jump_assert;\r
+        case JUMP_ASSERT_NOT:\r
+            TRACE(("|%p|%p|JUMP_ASSERT_NOT\n", ctx->pattern, ctx->ptr));\r
+            goto jump_assert_not;\r
+        case JUMP_NONE:\r
+            TRACE(("|%p|%p|RETURN %d\n", ctx->pattern, ctx->ptr, ret));\r
+            break;\r
+    }\r
+\r
+    return ret; /* should never get here */\r
+}\r
+\r
+LOCAL(Py_ssize_t)\r
+SRE_SEARCH(SRE_STATE* state, SRE_CODE* pattern)\r
+{\r
+    SRE_CHAR* ptr = (SRE_CHAR *)state->start;\r
+    SRE_CHAR* end = (SRE_CHAR *)state->end;\r
+    Py_ssize_t status = 0;\r
+    Py_ssize_t prefix_len = 0;\r
+    Py_ssize_t prefix_skip = 0;\r
+    SRE_CODE* prefix = NULL;\r
+    SRE_CODE* charset = NULL;\r
+    SRE_CODE* overlap = NULL;\r
+    int flags = 0;\r
+\r
+    if (pattern[0] == SRE_OP_INFO) {\r
+        /* optimization info block */\r
+        /* <INFO> <1=skip> <2=flags> <3=min> <4=max> <5=prefix info>  */\r
+\r
+        flags = pattern[2];\r
+\r
+        if (pattern[3] > 1) {\r
+            /* adjust end point (but make sure we leave at least one\r
+               character in there, so literal search will work) */\r
+            end -= pattern[3]-1;\r
+            if (end <= ptr)\r
+                end = ptr+1;\r
+        }\r
+\r
+        if (flags & SRE_INFO_PREFIX) {\r
+            /* pattern starts with a known prefix */\r
+            /* <length> <skip> <prefix data> <overlap data> */\r
+            prefix_len = pattern[5];\r
+            prefix_skip = pattern[6];\r
+            prefix = pattern + 7;\r
+            overlap = prefix + prefix_len - 1;\r
+        } else if (flags & SRE_INFO_CHARSET)\r
+            /* pattern starts with a character from a known set */\r
+            /* <charset> */\r
+            charset = pattern + 5;\r
+\r
+        pattern += 1 + pattern[1];\r
+    }\r
+\r
+    TRACE(("prefix = %p %d %d\n", prefix, prefix_len, prefix_skip));\r
+    TRACE(("charset = %p\n", charset));\r
+\r
+#if defined(USE_FAST_SEARCH)\r
+    if (prefix_len > 1) {\r
+        /* pattern starts with a known prefix.  use the overlap\r
+           table to skip forward as fast as we possibly can */\r
+        Py_ssize_t i = 0;\r
+        end = (SRE_CHAR *)state->end;\r
+        while (ptr < end) {\r
+            for (;;) {\r
+                if ((SRE_CODE) ptr[0] != prefix[i]) {\r
+                    if (!i)\r
+                        break;\r
+                    else\r
+                        i = overlap[i];\r
+                } else {\r
+                    if (++i == prefix_len) {\r
+                        /* found a potential match */\r
+                        TRACE(("|%p|%p|SEARCH SCAN\n", pattern, ptr));\r
+                        state->start = ptr + 1 - prefix_len;\r
+                        state->ptr = ptr + 1 - prefix_len + prefix_skip;\r
+                        if (flags & SRE_INFO_LITERAL)\r
+                            return 1; /* we got all of it */\r
+                        status = SRE_MATCH(state, pattern + 2*prefix_skip);\r
+                        if (status != 0)\r
+                            return status;\r
+                        /* close but no cigar -- try again */\r
+                        i = overlap[i];\r
+                    }\r
+                    break;\r
+                }\r
+            }\r
+            ptr++;\r
+        }\r
+        return 0;\r
+    }\r
+#endif\r
+\r
+    if (pattern[0] == SRE_OP_LITERAL) {\r
+        /* pattern starts with a literal character.  this is used\r
+           for short prefixes, and if fast search is disabled */\r
+        SRE_CODE chr = pattern[1];\r
+        end = (SRE_CHAR *)state->end;\r
+        for (;;) {\r
+            while (ptr < end && (SRE_CODE) ptr[0] != chr)\r
+                ptr++;\r
+            if (ptr >= end)\r
+                return 0;\r
+            TRACE(("|%p|%p|SEARCH LITERAL\n", pattern, ptr));\r
+            state->start = ptr;\r
+            state->ptr = ++ptr;\r
+            if (flags & SRE_INFO_LITERAL)\r
+                return 1; /* we got all of it */\r
+            status = SRE_MATCH(state, pattern + 2);\r
+            if (status != 0)\r
+                break;\r
+        }\r
+    } else if (charset) {\r
+        /* pattern starts with a character from a known set */\r
+        end = (SRE_CHAR *)state->end;\r
+        for (;;) {\r
+            while (ptr < end && !SRE_CHARSET(charset, ptr[0]))\r
+                ptr++;\r
+            if (ptr >= end)\r
+                return 0;\r
+            TRACE(("|%p|%p|SEARCH CHARSET\n", pattern, ptr));\r
+            state->start = ptr;\r
+            state->ptr = ptr;\r
+            status = SRE_MATCH(state, pattern);\r
+            if (status != 0)\r
+                break;\r
+            ptr++;\r
+        }\r
+    } else\r
+        /* general case */\r
+        while (ptr <= end) {\r
+            TRACE(("|%p|%p|SEARCH\n", pattern, ptr));\r
+            state->start = state->ptr = ptr++;\r
+            status = SRE_MATCH(state, pattern);\r
+            if (status != 0)\r
+                break;\r
+        }\r
+\r
+    return status;\r
+}\r
+\r
+LOCAL(int)\r
+SRE_LITERAL_TEMPLATE(SRE_CHAR* ptr, Py_ssize_t len)\r
+{\r
+    /* check if given string is a literal template (i.e. no escapes) */\r
+    while (len-- > 0)\r
+        if (*ptr++ == '\\')\r
+            return 0;\r
+    return 1;\r
+}\r
+\r
+#if !defined(SRE_RECURSIVE)\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* factories and destructors */\r
+\r
+/* see sre.h for object declarations */\r
+static PyObject*pattern_new_match(PatternObject*, SRE_STATE*, int);\r
+static PyObject*pattern_scanner(PatternObject*, PyObject*);\r
+\r
+static PyObject *\r
+sre_codesize(PyObject* self, PyObject *unused)\r
+{\r
+    return Py_BuildValue("l", sizeof(SRE_CODE));\r
+}\r
+\r
+static PyObject *\r
+sre_getlower(PyObject* self, PyObject* args)\r
+{\r
+    int character, flags;\r
+    if (!PyArg_ParseTuple(args, "ii", &character, &flags))\r
+        return NULL;\r
+    if (flags & SRE_FLAG_LOCALE)\r
+        return Py_BuildValue("i", sre_lower_locale(character));\r
+    if (flags & SRE_FLAG_UNICODE)\r
+#if defined(HAVE_UNICODE)\r
+        return Py_BuildValue("i", sre_lower_unicode(character));\r
+#else\r
+        return Py_BuildValue("i", sre_lower_locale(character));\r
+#endif\r
+    return Py_BuildValue("i", sre_lower(character));\r
+}\r
+\r
+LOCAL(void)\r
+state_reset(SRE_STATE* state)\r
+{\r
+    /* FIXME: dynamic! */\r
+    /*memset(state->mark, 0, sizeof(*state->mark) * SRE_MARK_SIZE);*/\r
+\r
+    state->lastmark = -1;\r
+    state->lastindex = -1;\r
+\r
+    state->repeat = NULL;\r
+\r
+    data_stack_dealloc(state);\r
+}\r
+\r
+static void*\r
+getstring(PyObject* string, Py_ssize_t* p_length, int* p_charsize)\r
+{\r
+    /* given a python object, return a data pointer, a length (in\r
+       characters), and a character size.  return NULL if the object\r
+       is not a string (or not compatible) */\r
+\r
+    PyBufferProcs *buffer;\r
+    Py_ssize_t size, bytes;\r
+    int charsize;\r
+    void* ptr;\r
+\r
+#if defined(HAVE_UNICODE)\r
+    if (PyUnicode_Check(string)) {\r
+        /* unicode strings doesn't always support the buffer interface */\r
+        ptr = (void*) PyUnicode_AS_DATA(string);\r
+        /* bytes = PyUnicode_GET_DATA_SIZE(string); */\r
+        size = PyUnicode_GET_SIZE(string);\r
+        charsize = sizeof(Py_UNICODE);\r
+\r
+    } else {\r
+#endif\r
+\r
+    /* get pointer to string buffer */\r
+    buffer = Py_TYPE(string)->tp_as_buffer;\r
+    if (!buffer || !buffer->bf_getreadbuffer || !buffer->bf_getsegcount ||\r
+        buffer->bf_getsegcount(string, NULL) != 1) {\r
+        PyErr_SetString(PyExc_TypeError, "expected string or buffer");\r
+        return NULL;\r
+    }\r
+\r
+    /* determine buffer size */\r
+    bytes = buffer->bf_getreadbuffer(string, 0, &ptr);\r
+    if (bytes < 0) {\r
+        PyErr_SetString(PyExc_TypeError, "buffer has negative size");\r
+        return NULL;\r
+    }\r
+\r
+    /* determine character size */\r
+#if PY_VERSION_HEX >= 0x01060000\r
+    size = PyObject_Size(string);\r
+#else\r
+    size = PyObject_Length(string);\r
+#endif\r
+\r
+    if (PyString_Check(string) || bytes == size)\r
+        charsize = 1;\r
+#if defined(HAVE_UNICODE)\r
+    else if (bytes == (Py_ssize_t) (size * sizeof(Py_UNICODE)))\r
+        charsize = sizeof(Py_UNICODE);\r
+#endif\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError, "buffer size mismatch");\r
+        return NULL;\r
+    }\r
+\r
+#if defined(HAVE_UNICODE)\r
+    }\r
+#endif\r
+\r
+    *p_length = size;\r
+    *p_charsize = charsize;\r
+\r
+    return ptr;\r
+}\r
+\r
+LOCAL(PyObject*)\r
+state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,\r
+           Py_ssize_t start, Py_ssize_t end)\r
+{\r
+    /* prepare state object */\r
+\r
+    Py_ssize_t length;\r
+    int charsize;\r
+    void* ptr;\r
+\r
+    memset(state, 0, sizeof(SRE_STATE));\r
+\r
+    state->lastmark = -1;\r
+    state->lastindex = -1;\r
+\r
+    ptr = getstring(string, &length, &charsize);\r
+    if (!ptr)\r
+        return NULL;\r
+\r
+    /* adjust boundaries */\r
+    if (start < 0)\r
+        start = 0;\r
+    else if (start > length)\r
+        start = length;\r
+\r
+    if (end < 0)\r
+        end = 0;\r
+    else if (end > length)\r
+        end = length;\r
+\r
+    state->charsize = charsize;\r
+\r
+    state->beginning = ptr;\r
+\r
+    state->start = (void*) ((char*) ptr + start * state->charsize);\r
+    state->end = (void*) ((char*) ptr + end * state->charsize);\r
+\r
+    Py_INCREF(string);\r
+    state->string = string;\r
+    state->pos = start;\r
+    state->endpos = end;\r
+\r
+    if (pattern->flags & SRE_FLAG_LOCALE)\r
+        state->lower = sre_lower_locale;\r
+    else if (pattern->flags & SRE_FLAG_UNICODE)\r
+#if defined(HAVE_UNICODE)\r
+        state->lower = sre_lower_unicode;\r
+#else\r
+        state->lower = sre_lower_locale;\r
+#endif\r
+    else\r
+        state->lower = sre_lower;\r
+\r
+    return string;\r
+}\r
+\r
+LOCAL(void)\r
+state_fini(SRE_STATE* state)\r
+{\r
+    Py_XDECREF(state->string);\r
+    data_stack_dealloc(state);\r
+}\r
+\r
+/* calculate offset from start of string */\r
+#define STATE_OFFSET(state, member)\\r
+    (((char*)(member) - (char*)(state)->beginning) / (state)->charsize)\r
+\r
+LOCAL(PyObject*)\r
+state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty)\r
+{\r
+    Py_ssize_t i, j;\r
+\r
+    index = (index - 1) * 2;\r
+\r
+    if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) {\r
+        if (empty)\r
+            /* want empty string */\r
+            i = j = 0;\r
+        else {\r
+            Py_INCREF(Py_None);\r
+            return Py_None;\r
+        }\r
+    } else {\r
+        i = STATE_OFFSET(state, state->mark[index]);\r
+        j = STATE_OFFSET(state, state->mark[index+1]);\r
+    }\r
+\r
+    return PySequence_GetSlice(string, i, j);\r
+}\r
+\r
+static void\r
+pattern_error(int status)\r
+{\r
+    switch (status) {\r
+    case SRE_ERROR_RECURSION_LIMIT:\r
+        PyErr_SetString(\r
+            PyExc_RuntimeError,\r
+            "maximum recursion limit exceeded"\r
+            );\r
+        break;\r
+    case SRE_ERROR_MEMORY:\r
+        PyErr_NoMemory();\r
+        break;\r
+    case SRE_ERROR_INTERRUPTED:\r
+    /* An exception has already been raised, so let it fly */\r
+        break;\r
+    default:\r
+        /* other error codes indicate compiler/engine bugs */\r
+        PyErr_SetString(\r
+            PyExc_RuntimeError,\r
+            "internal error in regular expression engine"\r
+            );\r
+    }\r
+}\r
+\r
+static void\r
+pattern_dealloc(PatternObject* self)\r
+{\r
+    if (self->weakreflist != NULL)\r
+        PyObject_ClearWeakRefs((PyObject *) self);\r
+    Py_XDECREF(self->pattern);\r
+    Py_XDECREF(self->groupindex);\r
+    Py_XDECREF(self->indexgroup);\r
+    PyObject_DEL(self);\r
+}\r
+\r
+static PyObject*\r
+pattern_match(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    int status;\r
+\r
+    PyObject* string;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    static char* kwlist[] = { "pattern", "pos", "endpos", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:match", kwlist,\r
+                                     &string, &start, &end))\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, start, end);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    state.ptr = state.start;\r
+\r
+    TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));\r
+\r
+    if (state.charsize == 1) {\r
+        status = sre_match(&state, PatternObject_GetCode(self));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_umatch(&state, PatternObject_GetCode(self));\r
+#endif\r
+    }\r
+\r
+    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    state_fini(&state);\r
+\r
+    return pattern_new_match(self, &state, status);\r
+}\r
+\r
+static PyObject*\r
+pattern_search(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    int status;\r
+\r
+    PyObject* string;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    static char* kwlist[] = { "pattern", "pos", "endpos", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:search", kwlist,\r
+                                     &string, &start, &end))\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, start, end);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));\r
+\r
+    if (state.charsize == 1) {\r
+        status = sre_search(&state, PatternObject_GetCode(self));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+    }\r
+\r
+    TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));\r
+\r
+    state_fini(&state);\r
+\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    return pattern_new_match(self, &state, status);\r
+}\r
+\r
+static PyObject*\r
+call(char* module, char* function, PyObject* args)\r
+{\r
+    PyObject* name;\r
+    PyObject* mod;\r
+    PyObject* func;\r
+    PyObject* result;\r
+\r
+    if (!args)\r
+        return NULL;\r
+    name = PyString_FromString(module);\r
+    if (!name)\r
+        return NULL;\r
+    mod = PyImport_Import(name);\r
+    Py_DECREF(name);\r
+    if (!mod)\r
+        return NULL;\r
+    func = PyObject_GetAttrString(mod, function);\r
+    Py_DECREF(mod);\r
+    if (!func)\r
+        return NULL;\r
+    result = PyObject_CallObject(func, args);\r
+    Py_DECREF(func);\r
+    Py_DECREF(args);\r
+    return result;\r
+}\r
+\r
+#ifdef USE_BUILTIN_COPY\r
+static int\r
+deepcopy(PyObject** object, PyObject* memo)\r
+{\r
+    PyObject* copy;\r
+\r
+    copy = call(\r
+        "copy", "deepcopy",\r
+        PyTuple_Pack(2, *object, memo)\r
+        );\r
+    if (!copy)\r
+        return 0;\r
+\r
+    Py_DECREF(*object);\r
+    *object = copy;\r
+\r
+    return 1; /* success */\r
+}\r
+#endif\r
+\r
+static PyObject*\r
+join_list(PyObject* list, PyObject* string)\r
+{\r
+    /* join list elements */\r
+\r
+    PyObject* joiner;\r
+#if PY_VERSION_HEX >= 0x01060000\r
+    PyObject* function;\r
+    PyObject* args;\r
+#endif\r
+    PyObject* result;\r
+\r
+    joiner = PySequence_GetSlice(string, 0, 0);\r
+    if (!joiner)\r
+        return NULL;\r
+\r
+    if (PyList_GET_SIZE(list) == 0) {\r
+        Py_DECREF(list);\r
+        return joiner;\r
+    }\r
+\r
+#if PY_VERSION_HEX >= 0x01060000\r
+    function = PyObject_GetAttrString(joiner, "join");\r
+    if (!function) {\r
+        Py_DECREF(joiner);\r
+        return NULL;\r
+    }\r
+    args = PyTuple_New(1);\r
+    if (!args) {\r
+        Py_DECREF(function);\r
+        Py_DECREF(joiner);\r
+        return NULL;\r
+    }\r
+    PyTuple_SET_ITEM(args, 0, list);\r
+    result = PyObject_CallObject(function, args);\r
+    Py_DECREF(args); /* also removes list */\r
+    Py_DECREF(function);\r
+#else\r
+    result = call(\r
+        "string", "join",\r
+        PyTuple_Pack(2, list, joiner)\r
+        );\r
+#endif\r
+    Py_DECREF(joiner);\r
+\r
+    return result;\r
+}\r
+\r
+static PyObject*\r
+pattern_findall(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    PyObject* list;\r
+    int status;\r
+    Py_ssize_t i, b, e;\r
+\r
+    PyObject* string;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    static char* kwlist[] = { "source", "pos", "endpos", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:findall", kwlist,\r
+                                     &string, &start, &end))\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, start, end);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    list = PyList_New(0);\r
+    if (!list) {\r
+        state_fini(&state);\r
+        return NULL;\r
+    }\r
+\r
+    while (state.start <= state.end) {\r
+\r
+        PyObject* item;\r
+\r
+        state_reset(&state);\r
+\r
+        state.ptr = state.start;\r
+\r
+        if (state.charsize == 1) {\r
+            status = sre_search(&state, PatternObject_GetCode(self));\r
+        } else {\r
+#if defined(HAVE_UNICODE)\r
+            status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+        }\r
+\r
+        if (PyErr_Occurred())\r
+            goto error;\r
+\r
+        if (status <= 0) {\r
+            if (status == 0)\r
+                break;\r
+            pattern_error(status);\r
+            goto error;\r
+        }\r
+\r
+        /* don't bother to build a match object */\r
+        switch (self->groups) {\r
+        case 0:\r
+            b = STATE_OFFSET(&state, state.start);\r
+            e = STATE_OFFSET(&state, state.ptr);\r
+            item = PySequence_GetSlice(string, b, e);\r
+            if (!item)\r
+                goto error;\r
+            break;\r
+        case 1:\r
+            item = state_getslice(&state, 1, string, 1);\r
+            if (!item)\r
+                goto error;\r
+            break;\r
+        default:\r
+            item = PyTuple_New(self->groups);\r
+            if (!item)\r
+                goto error;\r
+            for (i = 0; i < self->groups; i++) {\r
+                PyObject* o = state_getslice(&state, i+1, string, 1);\r
+                if (!o) {\r
+                    Py_DECREF(item);\r
+                    goto error;\r
+                }\r
+                PyTuple_SET_ITEM(item, i, o);\r
+            }\r
+            break;\r
+        }\r
+\r
+        status = PyList_Append(list, item);\r
+        Py_DECREF(item);\r
+        if (status < 0)\r
+            goto error;\r
+\r
+        if (state.ptr == state.start)\r
+            state.start = (void*) ((char*) state.ptr + state.charsize);\r
+        else\r
+            state.start = state.ptr;\r
+\r
+    }\r
+\r
+    state_fini(&state);\r
+    return list;\r
+\r
+error:\r
+    Py_DECREF(list);\r
+    state_fini(&state);\r
+    return NULL;\r
+\r
+}\r
+\r
+#if PY_VERSION_HEX >= 0x02020000\r
+static PyObject*\r
+pattern_finditer(PatternObject* pattern, PyObject* args)\r
+{\r
+    PyObject* scanner;\r
+    PyObject* search;\r
+    PyObject* iterator;\r
+\r
+    scanner = pattern_scanner(pattern, args);\r
+    if (!scanner)\r
+        return NULL;\r
+\r
+    search = PyObject_GetAttrString(scanner, "search");\r
+    Py_DECREF(scanner);\r
+    if (!search)\r
+        return NULL;\r
+\r
+    iterator = PyCallIter_New(search, Py_None);\r
+    Py_DECREF(search);\r
+\r
+    return iterator;\r
+}\r
+#endif\r
+\r
+static PyObject*\r
+pattern_split(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    SRE_STATE state;\r
+    PyObject* list;\r
+    PyObject* item;\r
+    int status;\r
+    Py_ssize_t n;\r
+    Py_ssize_t i;\r
+    void* last;\r
+\r
+    PyObject* string;\r
+    Py_ssize_t maxsplit = 0;\r
+    static char* kwlist[] = { "source", "maxsplit", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|n:split", kwlist,\r
+                                     &string, &maxsplit))\r
+        return NULL;\r
+\r
+    string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX);\r
+    if (!string)\r
+        return NULL;\r
+\r
+    list = PyList_New(0);\r
+    if (!list) {\r
+        state_fini(&state);\r
+        return NULL;\r
+    }\r
+\r
+    n = 0;\r
+    last = state.start;\r
+\r
+    while (!maxsplit || n < maxsplit) {\r
+\r
+        state_reset(&state);\r
+\r
+        state.ptr = state.start;\r
+\r
+        if (state.charsize == 1) {\r
+            status = sre_search(&state, PatternObject_GetCode(self));\r
+        } else {\r
+#if defined(HAVE_UNICODE)\r
+            status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+        }\r
+\r
+        if (PyErr_Occurred())\r
+            goto error;\r
+\r
+        if (status <= 0) {\r
+            if (status == 0)\r
+                break;\r
+            pattern_error(status);\r
+            goto error;\r
+        }\r
+\r
+        if (state.start == state.ptr) {\r
+            if (last == state.end)\r
+                break;\r
+            /* skip one character */\r
+            state.start = (void*) ((char*) state.ptr + state.charsize);\r
+            continue;\r
+        }\r
+\r
+        /* get segment before this match */\r
+        item = PySequence_GetSlice(\r
+            string, STATE_OFFSET(&state, last),\r
+            STATE_OFFSET(&state, state.start)\r
+            );\r
+        if (!item)\r
+            goto error;\r
+        status = PyList_Append(list, item);\r
+        Py_DECREF(item);\r
+        if (status < 0)\r
+            goto error;\r
+\r
+        /* add groups (if any) */\r
+        for (i = 0; i < self->groups; i++) {\r
+            item = state_getslice(&state, i+1, string, 0);\r
+            if (!item)\r
+                goto error;\r
+            status = PyList_Append(list, item);\r
+            Py_DECREF(item);\r
+            if (status < 0)\r
+                goto error;\r
+        }\r
+\r
+        n = n + 1;\r
+\r
+        last = state.start = state.ptr;\r
+\r
+    }\r
+\r
+    /* get segment following last match (even if empty) */\r
+    item = PySequence_GetSlice(\r
+        string, STATE_OFFSET(&state, last), state.endpos\r
+        );\r
+    if (!item)\r
+        goto error;\r
+    status = PyList_Append(list, item);\r
+    Py_DECREF(item);\r
+    if (status < 0)\r
+        goto error;\r
+\r
+    state_fini(&state);\r
+    return list;\r
+\r
+error:\r
+    Py_DECREF(list);\r
+    state_fini(&state);\r
+    return NULL;\r
+\r
+}\r
+\r
+static PyObject*\r
+pattern_subx(PatternObject* self, PyObject* ptemplate, PyObject* string,\r
+             Py_ssize_t count, Py_ssize_t subn)\r
+{\r
+    SRE_STATE state;\r
+    PyObject* list;\r
+    PyObject* item;\r
+    PyObject* filter;\r
+    PyObject* args;\r
+    PyObject* match;\r
+    void* ptr;\r
+    int status;\r
+    Py_ssize_t n;\r
+    Py_ssize_t i, b, e;\r
+    int bint;\r
+    int filter_is_callable;\r
+\r
+    if (PyCallable_Check(ptemplate)) {\r
+        /* sub/subn takes either a function or a template */\r
+        filter = ptemplate;\r
+        Py_INCREF(filter);\r
+        filter_is_callable = 1;\r
+    } else {\r
+        /* if not callable, check if it's a literal string */\r
+        int literal;\r
+        ptr = getstring(ptemplate, &n, &bint);\r
+        b = bint;\r
+        if (ptr) {\r
+            if (b == 1) {\r
+                literal = sre_literal_template((unsigned char *)ptr, n);\r
+            } else {\r
+#if defined(HAVE_UNICODE)\r
+                literal = sre_uliteral_template((Py_UNICODE *)ptr, n);\r
+#endif\r
+            }\r
+        } else {\r
+            PyErr_Clear();\r
+            literal = 0;\r
+        }\r
+        if (literal) {\r
+            filter = ptemplate;\r
+            Py_INCREF(filter);\r
+            filter_is_callable = 0;\r
+        } else {\r
+            /* not a literal; hand it over to the template compiler */\r
+            filter = call(\r
+                SRE_PY_MODULE, "_subx",\r
+                PyTuple_Pack(2, self, ptemplate)\r
+                );\r
+            if (!filter)\r
+                return NULL;\r
+            filter_is_callable = PyCallable_Check(filter);\r
+        }\r
+    }\r
+\r
+    string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX);\r
+    if (!string) {\r
+        Py_DECREF(filter);\r
+        return NULL;\r
+    }\r
+\r
+    list = PyList_New(0);\r
+    if (!list) {\r
+        Py_DECREF(filter);\r
+        state_fini(&state);\r
+        return NULL;\r
+    }\r
+\r
+    n = i = 0;\r
+\r
+    while (!count || n < count) {\r
+\r
+        state_reset(&state);\r
+\r
+        state.ptr = state.start;\r
+\r
+        if (state.charsize == 1) {\r
+            status = sre_search(&state, PatternObject_GetCode(self));\r
+        } else {\r
+#if defined(HAVE_UNICODE)\r
+            status = sre_usearch(&state, PatternObject_GetCode(self));\r
+#endif\r
+        }\r
+\r
+        if (PyErr_Occurred())\r
+            goto error;\r
+\r
+        if (status <= 0) {\r
+            if (status == 0)\r
+                break;\r
+            pattern_error(status);\r
+            goto error;\r
+        }\r
+\r
+        b = STATE_OFFSET(&state, state.start);\r
+        e = STATE_OFFSET(&state, state.ptr);\r
+\r
+        if (i < b) {\r
+            /* get segment before this match */\r
+            item = PySequence_GetSlice(string, i, b);\r
+            if (!item)\r
+                goto error;\r
+            status = PyList_Append(list, item);\r
+            Py_DECREF(item);\r
+            if (status < 0)\r
+                goto error;\r
+\r
+        } else if (i == b && i == e && n > 0)\r
+            /* ignore empty match on latest position */\r
+            goto next;\r
+\r
+        if (filter_is_callable) {\r
+            /* pass match object through filter */\r
+            match = pattern_new_match(self, &state, 1);\r
+            if (!match)\r
+                goto error;\r
+            args = PyTuple_Pack(1, match);\r
+            if (!args) {\r
+                Py_DECREF(match);\r
+                goto error;\r
+            }\r
+            item = PyObject_CallObject(filter, args);\r
+            Py_DECREF(args);\r
+            Py_DECREF(match);\r
+            if (!item)\r
+                goto error;\r
+        } else {\r
+            /* filter is literal string */\r
+            item = filter;\r
+            Py_INCREF(item);\r
+        }\r
+\r
+        /* add to list */\r
+        if (item != Py_None) {\r
+            status = PyList_Append(list, item);\r
+            Py_DECREF(item);\r
+            if (status < 0)\r
+                goto error;\r
+        }\r
+\r
+        i = e;\r
+        n = n + 1;\r
+\r
+next:\r
+        /* move on */\r
+        if (state.ptr == state.start)\r
+            state.start = (void*) ((char*) state.ptr + state.charsize);\r
+        else\r
+            state.start = state.ptr;\r
+\r
+    }\r
+\r
+    /* get segment following last match */\r
+    if (i < state.endpos) {\r
+        item = PySequence_GetSlice(string, i, state.endpos);\r
+        if (!item)\r
+            goto error;\r
+        status = PyList_Append(list, item);\r
+        Py_DECREF(item);\r
+        if (status < 0)\r
+            goto error;\r
+    }\r
+\r
+    state_fini(&state);\r
+\r
+    Py_DECREF(filter);\r
+\r
+    /* convert list to single string (also removes list) */\r
+    item = join_list(list, string);\r
+\r
+    if (!item)\r
+        return NULL;\r
+\r
+    if (subn)\r
+        return Py_BuildValue("Ni", item, n);\r
+\r
+    return item;\r
+\r
+error:\r
+    Py_DECREF(list);\r
+    state_fini(&state);\r
+    Py_DECREF(filter);\r
+    return NULL;\r
+\r
+}\r
+\r
+static PyObject*\r
+pattern_sub(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* ptemplate;\r
+    PyObject* string;\r
+    Py_ssize_t count = 0;\r
+    static char* kwlist[] = { "repl", "string", "count", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:sub", kwlist,\r
+                                     &ptemplate, &string, &count))\r
+        return NULL;\r
+\r
+    return pattern_subx(self, ptemplate, string, count, 0);\r
+}\r
+\r
+static PyObject*\r
+pattern_subn(PatternObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* ptemplate;\r
+    PyObject* string;\r
+    Py_ssize_t count = 0;\r
+    static char* kwlist[] = { "repl", "string", "count", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|n:subn", kwlist,\r
+                                     &ptemplate, &string, &count))\r
+        return NULL;\r
+\r
+    return pattern_subx(self, ptemplate, string, count, 1);\r
+}\r
+\r
+static PyObject*\r
+pattern_copy(PatternObject* self, PyObject *unused)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    PatternObject* copy;\r
+    int offset;\r
+\r
+    copy = PyObject_NEW_VAR(PatternObject, &Pattern_Type, self->codesize);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    offset = offsetof(PatternObject, groups);\r
+\r
+    Py_XINCREF(self->groupindex);\r
+    Py_XINCREF(self->indexgroup);\r
+    Py_XINCREF(self->pattern);\r
+\r
+    memcpy((char*) copy + offset, (char*) self + offset,\r
+           sizeof(PatternObject) + self->codesize * sizeof(SRE_CODE) - offset);\r
+    copy->weakreflist = NULL;\r
+\r
+    return (PyObject*) copy;\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot copy this pattern object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+static PyObject*\r
+pattern_deepcopy(PatternObject* self, PyObject* memo)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    PatternObject* copy;\r
+\r
+    copy = (PatternObject*) pattern_copy(self);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    if (!deepcopy(&copy->groupindex, memo) ||\r
+        !deepcopy(&copy->indexgroup, memo) ||\r
+        !deepcopy(&copy->pattern, memo)) {\r
+        Py_DECREF(copy);\r
+        return NULL;\r
+    }\r
+\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot deepcopy this pattern object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+PyDoc_STRVAR(pattern_match_doc,\r
+"match(string[, pos[, endpos]]) --> match object or None.\n\\r
+    Matches zero or more characters at the beginning of the string");\r
+\r
+PyDoc_STRVAR(pattern_search_doc,\r
+"search(string[, pos[, endpos]]) --> match object or None.\n\\r
+    Scan through string looking for a match, and return a corresponding\n\\r
+    MatchObject instance. Return None if no position in the string matches.");\r
+\r
+PyDoc_STRVAR(pattern_split_doc,\r
+"split(string[, maxsplit = 0])  --> list.\n\\r
+    Split string by the occurrences of pattern.");\r
+\r
+PyDoc_STRVAR(pattern_findall_doc,\r
+"findall(string[, pos[, endpos]]) --> list.\n\\r
+   Return a list of all non-overlapping matches of pattern in string.");\r
+\r
+PyDoc_STRVAR(pattern_finditer_doc,\r
+"finditer(string[, pos[, endpos]]) --> iterator.\n\\r
+    Return an iterator over all non-overlapping matches for the \n\\r
+    RE pattern in string. For each match, the iterator returns a\n\\r
+    match object.");\r
+\r
+PyDoc_STRVAR(pattern_sub_doc,\r
+"sub(repl, string[, count = 0]) --> newstring\n\\r
+    Return the string obtained by replacing the leftmost non-overlapping\n\\r
+    occurrences of pattern in string by the replacement repl.");\r
+\r
+PyDoc_STRVAR(pattern_subn_doc,\r
+"subn(repl, string[, count = 0]) --> (newstring, number of subs)\n\\r
+    Return the tuple (new_string, number_of_subs_made) found by replacing\n\\r
+    the leftmost non-overlapping occurrences of pattern with the\n\\r
+    replacement repl.");\r
+\r
+PyDoc_STRVAR(pattern_doc, "Compiled regular expression objects");\r
+\r
+static PyMethodDef pattern_methods[] = {\r
+    {"match", (PyCFunction) pattern_match, METH_VARARGS|METH_KEYWORDS,\r
+        pattern_match_doc},\r
+    {"search", (PyCFunction) pattern_search, METH_VARARGS|METH_KEYWORDS,\r
+        pattern_search_doc},\r
+    {"sub", (PyCFunction) pattern_sub, METH_VARARGS|METH_KEYWORDS,\r
+        pattern_sub_doc},\r
+    {"subn", (PyCFunction) pattern_subn, METH_VARARGS|METH_KEYWORDS,\r
+        pattern_subn_doc},\r
+    {"split", (PyCFunction) pattern_split, METH_VARARGS|METH_KEYWORDS,\r
+        pattern_split_doc},\r
+    {"findall", (PyCFunction) pattern_findall, METH_VARARGS|METH_KEYWORDS,\r
+        pattern_findall_doc},\r
+#if PY_VERSION_HEX >= 0x02020000\r
+    {"finditer", (PyCFunction) pattern_finditer, METH_VARARGS,\r
+        pattern_finditer_doc},\r
+#endif\r
+    {"scanner", (PyCFunction) pattern_scanner, METH_VARARGS},\r
+    {"__copy__", (PyCFunction) pattern_copy, METH_NOARGS},\r
+    {"__deepcopy__", (PyCFunction) pattern_deepcopy, METH_O},\r
+    {NULL, NULL}\r
+};\r
+\r
+#define PAT_OFF(x) offsetof(PatternObject, x)\r
+static PyMemberDef pattern_members[] = {\r
+    {"pattern",    T_OBJECT,    PAT_OFF(pattern),       READONLY},\r
+    {"flags",      T_INT,       PAT_OFF(flags),         READONLY},\r
+    {"groups",     T_PYSSIZET,  PAT_OFF(groups),        READONLY},\r
+    {"groupindex", T_OBJECT,    PAT_OFF(groupindex),    READONLY},\r
+    {NULL}  /* Sentinel */\r
+};\r
+\r
+statichere PyTypeObject Pattern_Type = {\r
+    PyObject_HEAD_INIT(NULL)\r
+    0, "_" SRE_MODULE ".SRE_Pattern",\r
+    sizeof(PatternObject), sizeof(SRE_CODE),\r
+    (destructor)pattern_dealloc, /*tp_dealloc*/\r
+    0,                                  /* tp_print */\r
+    0,                                  /* tp_getattrn */\r
+    0,          /* tp_setattr */\r
+    0,          /* tp_compare */\r
+    0,          /* tp_repr */\r
+    0,          /* tp_as_number */\r
+    0,          /* tp_as_sequence */\r
+    0,          /* tp_as_mapping */\r
+    0,          /* tp_hash */\r
+    0,          /* tp_call */\r
+    0,          /* tp_str */\r
+    0,          /* tp_getattro */\r
+    0,          /* tp_setattro */\r
+    0,          /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,           /* tp_flags */\r
+    pattern_doc,      /* tp_doc */\r
+    0,          /* tp_traverse */\r
+    0,          /* tp_clear */\r
+    0,          /* tp_richcompare */\r
+    offsetof(PatternObject, weakreflist), /* tp_weaklistoffset */\r
+    0,          /* tp_iter */\r
+    0,          /* tp_iternext */\r
+    pattern_methods,      /* tp_methods */\r
+    pattern_members,      /* tp_members */\r
+};\r
+\r
+static int _validate(PatternObject *self); /* Forward */\r
+\r
+static PyObject *\r
+_compile(PyObject* self_, PyObject* args)\r
+{\r
+    /* "compile" pattern descriptor to pattern object */\r
+\r
+    PatternObject* self;\r
+    Py_ssize_t i, n;\r
+\r
+    PyObject* pattern;\r
+    int flags = 0;\r
+    PyObject* code;\r
+    Py_ssize_t groups = 0;\r
+    PyObject* groupindex = NULL;\r
+    PyObject* indexgroup = NULL;\r
+    if (!PyArg_ParseTuple(args, "OiO!|nOO", &pattern, &flags,\r
+                          &PyList_Type, &code, &groups,\r
+                          &groupindex, &indexgroup))\r
+        return NULL;\r
+\r
+    n = PyList_GET_SIZE(code);\r
+    /* coverity[ampersand_in_size] */\r
+    self = PyObject_NEW_VAR(PatternObject, &Pattern_Type, n);\r
+    if (!self)\r
+        return NULL;\r
+    self->weakreflist = NULL;\r
+    self->pattern = NULL;\r
+    self->groupindex = NULL;\r
+    self->indexgroup = NULL;\r
+\r
+    self->codesize = n;\r
+\r
+    for (i = 0; i < n; i++) {\r
+        PyObject *o = PyList_GET_ITEM(code, i);\r
+        unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o)\r
+                                              : PyLong_AsUnsignedLong(o);\r
+        self->code[i] = (SRE_CODE) value;\r
+        if ((unsigned long) self->code[i] != value) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "regular expression code size limit exceeded");\r
+            break;\r
+        }\r
+    }\r
+\r
+    if (PyErr_Occurred()) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+\r
+    Py_INCREF(pattern);\r
+    self->pattern = pattern;\r
+\r
+    self->flags = flags;\r
+\r
+    self->groups = groups;\r
+\r
+    Py_XINCREF(groupindex);\r
+    self->groupindex = groupindex;\r
+\r
+    Py_XINCREF(indexgroup);\r
+    self->indexgroup = indexgroup;\r
+\r
+    self->weakreflist = NULL;\r
+\r
+    if (!_validate(self)) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+\r
+    return (PyObject*) self;\r
+}\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* Code validation */\r
+\r
+/* To learn more about this code, have a look at the _compile() function in\r
+   Lib/sre_compile.py.  The validation functions below checks the code array\r
+   for conformance with the code patterns generated there.\r
+\r
+   The nice thing about the generated code is that it is position-independent:\r
+   all jumps are relative jumps forward.  Also, jumps don't cross each other:\r
+   the target of a later jump is always earlier than the target of an earlier\r
+   jump.  IOW, this is okay:\r
+\r
+   J---------J-------T--------T\r
+    \         \_____/        /\r
+     \______________________/\r
+\r
+   but this is not:\r
+\r
+   J---------J-------T--------T\r
+    \_________\_____/        /\r
+               \____________/\r
+\r
+   It also helps that SRE_CODE is always an unsigned type, either 2 bytes or 4\r
+   bytes wide (the latter if Python is compiled for "wide" unicode support).\r
+*/\r
+\r
+/* Defining this one enables tracing of the validator */\r
+#undef VVERBOSE\r
+\r
+/* Trace macro for the validator */\r
+#if defined(VVERBOSE)\r
+#define VTRACE(v) printf v\r
+#else\r
+#define VTRACE(v)\r
+#endif\r
+\r
+/* Report failure */\r
+#define FAIL do { VTRACE(("FAIL: %d\n", __LINE__)); return 0; } while (0)\r
+\r
+/* Extract opcode, argument, or skip count from code array */\r
+#define GET_OP                                          \\r
+    do {                                                \\r
+        VTRACE(("%p: ", code));                         \\r
+        if (code >= end) FAIL;                          \\r
+        op = *code++;                                   \\r
+        VTRACE(("%lu (op)\n", (unsigned long)op));      \\r
+    } while (0)\r
+#define GET_ARG                                         \\r
+    do {                                                \\r
+        VTRACE(("%p= ", code));                         \\r
+        if (code >= end) FAIL;                          \\r
+        arg = *code++;                                  \\r
+        VTRACE(("%lu (arg)\n", (unsigned long)arg));    \\r
+    } while (0)\r
+#define GET_SKIP_ADJ(adj)                               \\r
+    do {                                                \\r
+        VTRACE(("%p= ", code));                         \\r
+        if (code >= end) FAIL;                          \\r
+        skip = *code;                                   \\r
+        VTRACE(("%lu (skip to %p)\n",                   \\r
+               (unsigned long)skip, code+skip));        \\r
+        if (code+skip-adj < code || code+skip-adj > end)\\r
+            FAIL;                                       \\r
+        code++;                                         \\r
+    } while (0)\r
+#define GET_SKIP GET_SKIP_ADJ(0)\r
+\r
+static int\r
+_validate_charset(SRE_CODE *code, SRE_CODE *end)\r
+{\r
+    /* Some variables are manipulated by the macros above */\r
+    SRE_CODE op;\r
+    SRE_CODE arg;\r
+    SRE_CODE offset;\r
+    int i;\r
+\r
+    while (code < end) {\r
+        GET_OP;\r
+        switch (op) {\r
+\r
+        case SRE_OP_NEGATE:\r
+            break;\r
+\r
+        case SRE_OP_LITERAL:\r
+            GET_ARG;\r
+            break;\r
+\r
+        case SRE_OP_RANGE:\r
+            GET_ARG;\r
+            GET_ARG;\r
+            break;\r
+\r
+        case SRE_OP_CHARSET:\r
+            offset = 32/sizeof(SRE_CODE); /* 32-byte bitmap */\r
+            if (code+offset < code || code+offset > end)\r
+                FAIL;\r
+            code += offset;\r
+            break;\r
+\r
+        case SRE_OP_BIGCHARSET:\r
+            GET_ARG; /* Number of blocks */\r
+            offset = 256/sizeof(SRE_CODE); /* 256-byte table */\r
+            if (code+offset < code || code+offset > end)\r
+                FAIL;\r
+            /* Make sure that each byte points to a valid block */\r
+            for (i = 0; i < 256; i++) {\r
+                if (((unsigned char *)code)[i] >= arg)\r
+                    FAIL;\r
+            }\r
+            code += offset;\r
+            offset = arg * 32/sizeof(SRE_CODE); /* 32-byte bitmap times arg */\r
+            if (code+offset < code || code+offset > end)\r
+                FAIL;\r
+            code += offset;\r
+            break;\r
+\r
+        case SRE_OP_CATEGORY:\r
+            GET_ARG;\r
+            switch (arg) {\r
+            case SRE_CATEGORY_DIGIT:\r
+            case SRE_CATEGORY_NOT_DIGIT:\r
+            case SRE_CATEGORY_SPACE:\r
+            case SRE_CATEGORY_NOT_SPACE:\r
+            case SRE_CATEGORY_WORD:\r
+            case SRE_CATEGORY_NOT_WORD:\r
+            case SRE_CATEGORY_LINEBREAK:\r
+            case SRE_CATEGORY_NOT_LINEBREAK:\r
+            case SRE_CATEGORY_LOC_WORD:\r
+            case SRE_CATEGORY_LOC_NOT_WORD:\r
+            case SRE_CATEGORY_UNI_DIGIT:\r
+            case SRE_CATEGORY_UNI_NOT_DIGIT:\r
+            case SRE_CATEGORY_UNI_SPACE:\r
+            case SRE_CATEGORY_UNI_NOT_SPACE:\r
+            case SRE_CATEGORY_UNI_WORD:\r
+            case SRE_CATEGORY_UNI_NOT_WORD:\r
+            case SRE_CATEGORY_UNI_LINEBREAK:\r
+            case SRE_CATEGORY_UNI_NOT_LINEBREAK:\r
+                break;\r
+            default:\r
+                FAIL;\r
+            }\r
+            break;\r
+\r
+        default:\r
+            FAIL;\r
+\r
+        }\r
+    }\r
+\r
+    return 1;\r
+}\r
+\r
+static int\r
+_validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)\r
+{\r
+    /* Some variables are manipulated by the macros above */\r
+    SRE_CODE op;\r
+    SRE_CODE arg;\r
+    SRE_CODE skip;\r
+\r
+    VTRACE(("code=%p, end=%p\n", code, end));\r
+\r
+    if (code > end)\r
+        FAIL;\r
+\r
+    while (code < end) {\r
+        GET_OP;\r
+        switch (op) {\r
+\r
+        case SRE_OP_MARK:\r
+            /* We don't check whether marks are properly nested; the\r
+               sre_match() code is robust even if they don't, and the worst\r
+               you can get is nonsensical match results. */\r
+            GET_ARG;\r
+            if (arg > 2*groups+1) {\r
+                VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups));\r
+                FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_LITERAL:\r
+        case SRE_OP_NOT_LITERAL:\r
+        case SRE_OP_LITERAL_IGNORE:\r
+        case SRE_OP_NOT_LITERAL_IGNORE:\r
+            GET_ARG;\r
+            /* The arg is just a character, nothing to check */\r
+            break;\r
+\r
+        case SRE_OP_SUCCESS:\r
+        case SRE_OP_FAILURE:\r
+            /* Nothing to check; these normally end the matching process */\r
+            break;\r
+\r
+        case SRE_OP_AT:\r
+            GET_ARG;\r
+            switch (arg) {\r
+            case SRE_AT_BEGINNING:\r
+            case SRE_AT_BEGINNING_STRING:\r
+            case SRE_AT_BEGINNING_LINE:\r
+            case SRE_AT_END:\r
+            case SRE_AT_END_LINE:\r
+            case SRE_AT_END_STRING:\r
+            case SRE_AT_BOUNDARY:\r
+            case SRE_AT_NON_BOUNDARY:\r
+            case SRE_AT_LOC_BOUNDARY:\r
+            case SRE_AT_LOC_NON_BOUNDARY:\r
+            case SRE_AT_UNI_BOUNDARY:\r
+            case SRE_AT_UNI_NON_BOUNDARY:\r
+                break;\r
+            default:\r
+                FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_ANY:\r
+        case SRE_OP_ANY_ALL:\r
+            /* These have no operands */\r
+            break;\r
+\r
+        case SRE_OP_IN:\r
+        case SRE_OP_IN_IGNORE:\r
+            GET_SKIP;\r
+            /* Stop 1 before the end; we check the FAILURE below */\r
+            if (!_validate_charset(code, code+skip-2))\r
+                FAIL;\r
+            if (code[skip-2] != SRE_OP_FAILURE)\r
+                FAIL;\r
+            code += skip-1;\r
+            break;\r
+\r
+        case SRE_OP_INFO:\r
+            {\r
+                /* A minimal info field is\r
+                   <INFO> <1=skip> <2=flags> <3=min> <4=max>;\r
+                   If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags,\r
+                   more follows. */\r
+                SRE_CODE flags, i;\r
+                SRE_CODE *newcode;\r
+                GET_SKIP;\r
+                newcode = code+skip-1;\r
+                GET_ARG; flags = arg;\r
+                GET_ARG; /* min */\r
+                GET_ARG; /* max */\r
+                /* Check that only valid flags are present */\r
+                if ((flags & ~(SRE_INFO_PREFIX |\r
+                               SRE_INFO_LITERAL |\r
+                               SRE_INFO_CHARSET)) != 0)\r
+                    FAIL;\r
+                /* PREFIX and CHARSET are mutually exclusive */\r
+                if ((flags & SRE_INFO_PREFIX) &&\r
+                    (flags & SRE_INFO_CHARSET))\r
+                    FAIL;\r
+                /* LITERAL implies PREFIX */\r
+                if ((flags & SRE_INFO_LITERAL) &&\r
+                    !(flags & SRE_INFO_PREFIX))\r
+                    FAIL;\r
+                /* Validate the prefix */\r
+                if (flags & SRE_INFO_PREFIX) {\r
+                    SRE_CODE prefix_len;\r
+                    GET_ARG; prefix_len = arg;\r
+                    GET_ARG; /* prefix skip */\r
+                    /* Here comes the prefix string */\r
+                    if (code+prefix_len < code || code+prefix_len > newcode)\r
+                        FAIL;\r
+                    code += prefix_len;\r
+                    /* And here comes the overlap table */\r
+                    if (code+prefix_len < code || code+prefix_len > newcode)\r
+                        FAIL;\r
+                    /* Each overlap value should be < prefix_len */\r
+                    for (i = 0; i < prefix_len; i++) {\r
+                        if (code[i] >= prefix_len)\r
+                            FAIL;\r
+                    }\r
+                    code += prefix_len;\r
+                }\r
+                /* Validate the charset */\r
+                if (flags & SRE_INFO_CHARSET) {\r
+                    if (!_validate_charset(code, newcode-1))\r
+                        FAIL;\r
+                    if (newcode[-1] != SRE_OP_FAILURE)\r
+                        FAIL;\r
+                    code = newcode;\r
+                }\r
+                else if (code != newcode) {\r
+                  VTRACE(("code=%p, newcode=%p\n", code, newcode));\r
+                    FAIL;\r
+                }\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_BRANCH:\r
+            {\r
+                SRE_CODE *target = NULL;\r
+                for (;;) {\r
+                    GET_SKIP;\r
+                    if (skip == 0)\r
+                        break;\r
+                    /* Stop 2 before the end; we check the JUMP below */\r
+                    if (!_validate_inner(code, code+skip-3, groups))\r
+                        FAIL;\r
+                    code += skip-3;\r
+                    /* Check that it ends with a JUMP, and that each JUMP\r
+                       has the same target */\r
+                    GET_OP;\r
+                    if (op != SRE_OP_JUMP)\r
+                        FAIL;\r
+                    GET_SKIP;\r
+                    if (target == NULL)\r
+                        target = code+skip-1;\r
+                    else if (code+skip-1 != target)\r
+                        FAIL;\r
+                }\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_REPEAT_ONE:\r
+        case SRE_OP_MIN_REPEAT_ONE:\r
+            {\r
+                SRE_CODE min, max;\r
+                GET_SKIP;\r
+                GET_ARG; min = arg;\r
+                GET_ARG; max = arg;\r
+                if (min > max)\r
+                    FAIL;\r
+#ifdef Py_UNICODE_WIDE\r
+                if (max > 65535)\r
+                    FAIL;\r
+#endif\r
+                if (!_validate_inner(code, code+skip-4, groups))\r
+                    FAIL;\r
+                code += skip-4;\r
+                GET_OP;\r
+                if (op != SRE_OP_SUCCESS)\r
+                    FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_REPEAT:\r
+            {\r
+                SRE_CODE min, max;\r
+                GET_SKIP;\r
+                GET_ARG; min = arg;\r
+                GET_ARG; max = arg;\r
+                if (min > max)\r
+                    FAIL;\r
+#ifdef Py_UNICODE_WIDE\r
+                if (max > 65535)\r
+                    FAIL;\r
+#endif\r
+                if (!_validate_inner(code, code+skip-3, groups))\r
+                    FAIL;\r
+                code += skip-3;\r
+                GET_OP;\r
+                if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL)\r
+                    FAIL;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF:\r
+        case SRE_OP_GROUPREF_IGNORE:\r
+            GET_ARG;\r
+            if (arg >= groups)\r
+                FAIL;\r
+            break;\r
+\r
+        case SRE_OP_GROUPREF_EXISTS:\r
+            /* The regex syntax for this is: '(?(group)then|else)', where\r
+               'group' is either an integer group number or a group name,\r
+               'then' and 'else' are sub-regexes, and 'else' is optional. */\r
+            GET_ARG;\r
+            if (arg >= groups)\r
+                FAIL;\r
+            GET_SKIP_ADJ(1);\r
+            code--; /* The skip is relative to the first arg! */\r
+            /* There are two possibilities here: if there is both a 'then'\r
+               part and an 'else' part, the generated code looks like:\r
+\r
+               GROUPREF_EXISTS\r
+               <group>\r
+               <skipyes>\r
+               ...then part...\r
+               JUMP\r
+               <skipno>\r
+               (<skipyes> jumps here)\r
+               ...else part...\r
+               (<skipno> jumps here)\r
+\r
+               If there is only a 'then' part, it looks like:\r
+\r
+               GROUPREF_EXISTS\r
+               <group>\r
+               <skip>\r
+               ...then part...\r
+               (<skip> jumps here)\r
+\r
+               There is no direct way to decide which it is, and we don't want\r
+               to allow arbitrary jumps anywhere in the code; so we just look\r
+               for a JUMP opcode preceding our skip target.\r
+            */\r
+            if (skip >= 3 && code+skip-3 >= code &&\r
+                code[skip-3] == SRE_OP_JUMP)\r
+            {\r
+                VTRACE(("both then and else parts present\n"));\r
+                if (!_validate_inner(code+1, code+skip-3, groups))\r
+                    FAIL;\r
+                code += skip-2; /* Position after JUMP, at <skipno> */\r
+                GET_SKIP;\r
+                if (!_validate_inner(code, code+skip-1, groups))\r
+                    FAIL;\r
+                code += skip-1;\r
+            }\r
+            else {\r
+                VTRACE(("only a then part present\n"));\r
+                if (!_validate_inner(code+1, code+skip-1, groups))\r
+                    FAIL;\r
+                code += skip-1;\r
+            }\r
+            break;\r
+\r
+        case SRE_OP_ASSERT:\r
+        case SRE_OP_ASSERT_NOT:\r
+            GET_SKIP;\r
+            GET_ARG; /* 0 for lookahead, width for lookbehind */\r
+            code--; /* Back up over arg to simplify math below */\r
+            if (arg & 0x80000000)\r
+                FAIL; /* Width too large */\r
+            /* Stop 1 before the end; we check the SUCCESS below */\r
+            if (!_validate_inner(code+1, code+skip-2, groups))\r
+                FAIL;\r
+            code += skip-2;\r
+            GET_OP;\r
+            if (op != SRE_OP_SUCCESS)\r
+                FAIL;\r
+            break;\r
+\r
+        default:\r
+            FAIL;\r
+\r
+        }\r
+    }\r
+\r
+    VTRACE(("okay\n"));\r
+    return 1;\r
+}\r
+\r
+static int\r
+_validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)\r
+{\r
+    if (groups < 0 || groups > 100 || code >= end || end[-1] != SRE_OP_SUCCESS)\r
+        FAIL;\r
+    if (groups == 0)  /* fix for simplejson */\r
+        groups = 100; /* 100 groups should always be safe */\r
+    return _validate_inner(code, end-1, groups);\r
+}\r
+\r
+static int\r
+_validate(PatternObject *self)\r
+{\r
+    if (!_validate_outer(self->code, self->code+self->codesize, self->groups))\r
+    {\r
+        PyErr_SetString(PyExc_RuntimeError, "invalid SRE code");\r
+        return 0;\r
+    }\r
+    else\r
+        VTRACE(("Success!\n"));\r
+    return 1;\r
+}\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* match methods */\r
+\r
+static void\r
+match_dealloc(MatchObject* self)\r
+{\r
+    Py_XDECREF(self->regs);\r
+    Py_XDECREF(self->string);\r
+    Py_DECREF(self->pattern);\r
+    PyObject_DEL(self);\r
+}\r
+\r
+static PyObject*\r
+match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def)\r
+{\r
+    if (index < 0 || index >= self->groups) {\r
+        /* raise IndexError if we were given a bad group number */\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    index *= 2;\r
+\r
+    if (self->string == Py_None || self->mark[index] < 0) {\r
+        /* return default value if the string or group is undefined */\r
+        Py_INCREF(def);\r
+        return def;\r
+    }\r
+\r
+    return PySequence_GetSlice(\r
+        self->string, self->mark[index], self->mark[index+1]\r
+        );\r
+}\r
+\r
+static Py_ssize_t\r
+match_getindex(MatchObject* self, PyObject* index)\r
+{\r
+    Py_ssize_t i;\r
+\r
+    if (PyInt_Check(index))\r
+        return PyInt_AsSsize_t(index);\r
+\r
+    i = -1;\r
+\r
+    if (self->pattern->groupindex) {\r
+        index = PyObject_GetItem(self->pattern->groupindex, index);\r
+        if (index) {\r
+            if (PyInt_Check(index) || PyLong_Check(index))\r
+                i = PyInt_AsSsize_t(index);\r
+            Py_DECREF(index);\r
+        } else\r
+            PyErr_Clear();\r
+    }\r
+\r
+    return i;\r
+}\r
+\r
+static PyObject*\r
+match_getslice(MatchObject* self, PyObject* index, PyObject* def)\r
+{\r
+    return match_getslice_by_index(self, match_getindex(self, index), def);\r
+}\r
+\r
+static PyObject*\r
+match_expand(MatchObject* self, PyObject* ptemplate)\r
+{\r
+    /* delegate to Python code */\r
+    return call(\r
+        SRE_PY_MODULE, "_expand",\r
+        PyTuple_Pack(3, self->pattern, self, ptemplate)\r
+        );\r
+}\r
+\r
+static PyObject*\r
+match_group(MatchObject* self, PyObject* args)\r
+{\r
+    PyObject* result;\r
+    Py_ssize_t i, size;\r
+\r
+    size = PyTuple_GET_SIZE(args);\r
+\r
+    switch (size) {\r
+    case 0:\r
+        result = match_getslice(self, Py_False, Py_None);\r
+        break;\r
+    case 1:\r
+        result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);\r
+        break;\r
+    default:\r
+        /* fetch multiple items */\r
+        result = PyTuple_New(size);\r
+        if (!result)\r
+            return NULL;\r
+        for (i = 0; i < size; i++) {\r
+            PyObject* item = match_getslice(\r
+                self, PyTuple_GET_ITEM(args, i), Py_None\r
+                );\r
+            if (!item) {\r
+                Py_DECREF(result);\r
+                return NULL;\r
+            }\r
+            PyTuple_SET_ITEM(result, i, item);\r
+        }\r
+        break;\r
+    }\r
+    return result;\r
+}\r
+\r
+static PyObject*\r
+match_groups(MatchObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* result;\r
+    Py_ssize_t index;\r
+\r
+    PyObject* def = Py_None;\r
+    static char* kwlist[] = { "default", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groups", kwlist, &def))\r
+        return NULL;\r
+\r
+    result = PyTuple_New(self->groups-1);\r
+    if (!result)\r
+        return NULL;\r
+\r
+    for (index = 1; index < self->groups; index++) {\r
+        PyObject* item;\r
+        item = match_getslice_by_index(self, index, def);\r
+        if (!item) {\r
+            Py_DECREF(result);\r
+            return NULL;\r
+        }\r
+        PyTuple_SET_ITEM(result, index-1, item);\r
+    }\r
+\r
+    return result;\r
+}\r
+\r
+static PyObject*\r
+match_groupdict(MatchObject* self, PyObject* args, PyObject* kw)\r
+{\r
+    PyObject* result;\r
+    PyObject* keys;\r
+    Py_ssize_t index;\r
+\r
+    PyObject* def = Py_None;\r
+    static char* kwlist[] = { "default", NULL };\r
+    if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:groupdict", kwlist, &def))\r
+        return NULL;\r
+\r
+    result = PyDict_New();\r
+    if (!result || !self->pattern->groupindex)\r
+        return result;\r
+\r
+    keys = PyMapping_Keys(self->pattern->groupindex);\r
+    if (!keys)\r
+        goto failed;\r
+\r
+    for (index = 0; index < PyList_GET_SIZE(keys); index++) {\r
+        int status;\r
+        PyObject* key;\r
+        PyObject* value;\r
+        key = PyList_GET_ITEM(keys, index);\r
+        if (!key)\r
+            goto failed;\r
+        value = match_getslice(self, key, def);\r
+        if (!value) {\r
+            Py_DECREF(key);\r
+            goto failed;\r
+        }\r
+        status = PyDict_SetItem(result, key, value);\r
+        Py_DECREF(value);\r
+        if (status < 0)\r
+            goto failed;\r
+    }\r
+\r
+    Py_DECREF(keys);\r
+\r
+    return result;\r
+\r
+failed:\r
+    Py_XDECREF(keys);\r
+    Py_DECREF(result);\r
+    return NULL;\r
+}\r
+\r
+static PyObject*\r
+match_start(MatchObject* self, PyObject* args)\r
+{\r
+    Py_ssize_t index;\r
+\r
+    PyObject* index_ = Py_False; /* zero */\r
+    if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_))\r
+        return NULL;\r
+\r
+    index = match_getindex(self, index_);\r
+\r
+    if (index < 0 || index >= self->groups) {\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    /* mark is -1 if group is undefined */\r
+    return Py_BuildValue("i", self->mark[index*2]);\r
+}\r
+\r
+static PyObject*\r
+match_end(MatchObject* self, PyObject* args)\r
+{\r
+    Py_ssize_t index;\r
+\r
+    PyObject* index_ = Py_False; /* zero */\r
+    if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_))\r
+        return NULL;\r
+\r
+    index = match_getindex(self, index_);\r
+\r
+    if (index < 0 || index >= self->groups) {\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    /* mark is -1 if group is undefined */\r
+    return Py_BuildValue("i", self->mark[index*2+1]);\r
+}\r
+\r
+LOCAL(PyObject*)\r
+_pair(Py_ssize_t i1, Py_ssize_t i2)\r
+{\r
+    PyObject* pair;\r
+    PyObject* item;\r
+\r
+    pair = PyTuple_New(2);\r
+    if (!pair)\r
+        return NULL;\r
+\r
+    item = PyInt_FromSsize_t(i1);\r
+    if (!item)\r
+        goto error;\r
+    PyTuple_SET_ITEM(pair, 0, item);\r
+\r
+    item = PyInt_FromSsize_t(i2);\r
+    if (!item)\r
+        goto error;\r
+    PyTuple_SET_ITEM(pair, 1, item);\r
+\r
+    return pair;\r
+\r
+  error:\r
+    Py_DECREF(pair);\r
+    return NULL;\r
+}\r
+\r
+static PyObject*\r
+match_span(MatchObject* self, PyObject* args)\r
+{\r
+    Py_ssize_t index;\r
+\r
+    PyObject* index_ = Py_False; /* zero */\r
+    if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_))\r
+        return NULL;\r
+\r
+    index = match_getindex(self, index_);\r
+\r
+    if (index < 0 || index >= self->groups) {\r
+        PyErr_SetString(\r
+            PyExc_IndexError,\r
+            "no such group"\r
+            );\r
+        return NULL;\r
+    }\r
+\r
+    /* marks are -1 if group is undefined */\r
+    return _pair(self->mark[index*2], self->mark[index*2+1]);\r
+}\r
+\r
+static PyObject*\r
+match_regs(MatchObject* self)\r
+{\r
+    PyObject* regs;\r
+    PyObject* item;\r
+    Py_ssize_t index;\r
+\r
+    regs = PyTuple_New(self->groups);\r
+    if (!regs)\r
+        return NULL;\r
+\r
+    for (index = 0; index < self->groups; index++) {\r
+        item = _pair(self->mark[index*2], self->mark[index*2+1]);\r
+        if (!item) {\r
+            Py_DECREF(regs);\r
+            return NULL;\r
+        }\r
+        PyTuple_SET_ITEM(regs, index, item);\r
+    }\r
+\r
+    Py_INCREF(regs);\r
+    self->regs = regs;\r
+\r
+    return regs;\r
+}\r
+\r
+static PyObject*\r
+match_copy(MatchObject* self, PyObject *unused)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    MatchObject* copy;\r
+    Py_ssize_t slots, offset;\r
+\r
+    slots = 2 * (self->pattern->groups+1);\r
+\r
+    copy = PyObject_NEW_VAR(MatchObject, &Match_Type, slots);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    /* this value a constant, but any compiler should be able to\r
+       figure that out all by itself */\r
+    offset = offsetof(MatchObject, string);\r
+\r
+    Py_XINCREF(self->pattern);\r
+    Py_XINCREF(self->string);\r
+    Py_XINCREF(self->regs);\r
+\r
+    memcpy((char*) copy + offset, (char*) self + offset,\r
+           sizeof(MatchObject) + slots * sizeof(Py_ssize_t) - offset);\r
+\r
+    return (PyObject*) copy;\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot copy this match object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+static PyObject*\r
+match_deepcopy(MatchObject* self, PyObject* memo)\r
+{\r
+#ifdef USE_BUILTIN_COPY\r
+    MatchObject* copy;\r
+\r
+    copy = (MatchObject*) match_copy(self);\r
+    if (!copy)\r
+        return NULL;\r
+\r
+    if (!deepcopy((PyObject**) &copy->pattern, memo) ||\r
+        !deepcopy(&copy->string, memo) ||\r
+        !deepcopy(&copy->regs, memo)) {\r
+        Py_DECREF(copy);\r
+        return NULL;\r
+    }\r
+\r
+#else\r
+    PyErr_SetString(PyExc_TypeError, "cannot deepcopy this match object");\r
+    return NULL;\r
+#endif\r
+}\r
+\r
+static struct PyMethodDef match_methods[] = {\r
+    {"group", (PyCFunction) match_group, METH_VARARGS},\r
+    {"start", (PyCFunction) match_start, METH_VARARGS},\r
+    {"end", (PyCFunction) match_end, METH_VARARGS},\r
+    {"span", (PyCFunction) match_span, METH_VARARGS},\r
+    {"groups", (PyCFunction) match_groups, METH_VARARGS|METH_KEYWORDS},\r
+    {"groupdict", (PyCFunction) match_groupdict, METH_VARARGS|METH_KEYWORDS},\r
+    {"expand", (PyCFunction) match_expand, METH_O},\r
+    {"__copy__", (PyCFunction) match_copy, METH_NOARGS},\r
+    {"__deepcopy__", (PyCFunction) match_deepcopy, METH_O},\r
+    {NULL, NULL}\r
+};\r
+\r
+static PyObject *\r
+match_lastindex_get(MatchObject *self)\r
+{\r
+    if (self->lastindex >= 0)\r
+  return Py_BuildValue("i", self->lastindex);\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static PyObject *\r
+match_lastgroup_get(MatchObject *self)\r
+{\r
+    if (self->pattern->indexgroup && self->lastindex >= 0) {\r
+        PyObject* result = PySequence_GetItem(\r
+            self->pattern->indexgroup, self->lastindex\r
+            );\r
+        if (result)\r
+            return result;\r
+        PyErr_Clear();\r
+    }\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+static PyObject *\r
+match_regs_get(MatchObject *self)\r
+{\r
+    if (self->regs) {\r
+        Py_INCREF(self->regs);\r
+        return self->regs;\r
+    } else\r
+        return match_regs(self);\r
+}\r
+\r
+static PyGetSetDef match_getset[] = {\r
+    {"lastindex", (getter)match_lastindex_get, (setter)NULL},\r
+    {"lastgroup", (getter)match_lastgroup_get, (setter)NULL},\r
+    {"regs",      (getter)match_regs_get,      (setter)NULL},\r
+    {NULL}\r
+};\r
+\r
+#define MATCH_OFF(x) offsetof(MatchObject, x)\r
+static PyMemberDef match_members[] = {\r
+    {"string",  T_OBJECT,   MATCH_OFF(string),  READONLY},\r
+    {"re",      T_OBJECT,   MATCH_OFF(pattern), READONLY},\r
+    {"pos",     T_PYSSIZET, MATCH_OFF(pos),     READONLY},\r
+    {"endpos",  T_PYSSIZET, MATCH_OFF(endpos),  READONLY},\r
+    {NULL}\r
+};\r
+\r
+\r
+/* FIXME: implement setattr("string", None) as a special case (to\r
+   detach the associated string, if any */\r
+\r
+static PyTypeObject Match_Type = {\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "_" SRE_MODULE ".SRE_Match",\r
+    sizeof(MatchObject), sizeof(Py_ssize_t),\r
+    (destructor)match_dealloc,  /* tp_dealloc */\r
+    0,                          /* tp_print */\r
+    0,                          /* tp_getattr */\r
+    0,                          /* tp_setattr */\r
+    0,                          /* tp_compare */\r
+    0,                          /* tp_repr */\r
+    0,                          /* tp_as_number */\r
+    0,                          /* tp_as_sequence */\r
+    0,                          /* tp_as_mapping */\r
+    0,                          /* tp_hash */\r
+    0,                          /* tp_call */\r
+    0,                          /* tp_str */\r
+    0,                          /* tp_getattro */\r
+    0,                          /* tp_setattro */\r
+    0,                          /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,\r
+    0,                          /* tp_doc */\r
+    0,                          /* tp_traverse */\r
+    0,                          /* tp_clear */\r
+    0,                          /* tp_richcompare */\r
+    0,                          /* tp_weaklistoffset */\r
+    0,                          /* tp_iter */\r
+    0,                          /* tp_iternext */\r
+    match_methods,    /* tp_methods */\r
+    match_members,    /* tp_members */\r
+    match_getset,           /* tp_getset */\r
+};\r
+\r
+static PyObject*\r
+pattern_new_match(PatternObject* pattern, SRE_STATE* state, int status)\r
+{\r
+    /* create match object (from state object) */\r
+\r
+    MatchObject* match;\r
+    Py_ssize_t i, j;\r
+    char* base;\r
+    int n;\r
+\r
+    if (status > 0) {\r
+\r
+        /* create match object (with room for extra group marks) */\r
+        /* coverity[ampersand_in_size] */\r
+        match = PyObject_NEW_VAR(MatchObject, &Match_Type,\r
+                                 2*(pattern->groups+1));\r
+        if (!match)\r
+            return NULL;\r
+\r
+        Py_INCREF(pattern);\r
+        match->pattern = pattern;\r
+\r
+        Py_INCREF(state->string);\r
+        match->string = state->string;\r
+\r
+        match->regs = NULL;\r
+        match->groups = pattern->groups+1;\r
+\r
+        /* fill in group slices */\r
+\r
+        base = (char*) state->beginning;\r
+        n = state->charsize;\r
+\r
+        match->mark[0] = ((char*) state->start - base) / n;\r
+        match->mark[1] = ((char*) state->ptr - base) / n;\r
+\r
+        for (i = j = 0; i < pattern->groups; i++, j+=2)\r
+            if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {\r
+                match->mark[j+2] = ((char*) state->mark[j] - base) / n;\r
+                match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;\r
+            } else\r
+                match->mark[j+2] = match->mark[j+3] = -1; /* undefined */\r
+\r
+        match->pos = state->pos;\r
+        match->endpos = state->endpos;\r
+\r
+        match->lastindex = state->lastindex;\r
+\r
+        return (PyObject*) match;\r
+\r
+    } else if (status == 0) {\r
+\r
+        /* no match */\r
+        Py_INCREF(Py_None);\r
+        return Py_None;\r
+\r
+    }\r
+\r
+    /* internal error */\r
+    pattern_error(status);\r
+    return NULL;\r
+}\r
+\r
+\r
+/* -------------------------------------------------------------------- */\r
+/* scanner methods (experimental) */\r
+\r
+static void\r
+scanner_dealloc(ScannerObject* self)\r
+{\r
+    state_fini(&self->state);\r
+    Py_XDECREF(self->pattern);\r
+    PyObject_DEL(self);\r
+}\r
+\r
+static PyObject*\r
+scanner_match(ScannerObject* self, PyObject *unused)\r
+{\r
+    SRE_STATE* state = &self->state;\r
+    PyObject* match;\r
+    int status;\r
+\r
+    state_reset(state);\r
+\r
+    state->ptr = state->start;\r
+\r
+    if (state->charsize == 1) {\r
+        status = sre_match(state, PatternObject_GetCode(self->pattern));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_umatch(state, PatternObject_GetCode(self->pattern));\r
+#endif\r
+    }\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    match = pattern_new_match((PatternObject*) self->pattern,\r
+                               state, status);\r
+\r
+    if (status == 0 || state->ptr == state->start)\r
+        state->start = (void*) ((char*) state->ptr + state->charsize);\r
+    else\r
+        state->start = state->ptr;\r
+\r
+    return match;\r
+}\r
+\r
+\r
+static PyObject*\r
+scanner_search(ScannerObject* self, PyObject *unused)\r
+{\r
+    SRE_STATE* state = &self->state;\r
+    PyObject* match;\r
+    int status;\r
+\r
+    state_reset(state);\r
+\r
+    state->ptr = state->start;\r
+\r
+    if (state->charsize == 1) {\r
+        status = sre_search(state, PatternObject_GetCode(self->pattern));\r
+    } else {\r
+#if defined(HAVE_UNICODE)\r
+        status = sre_usearch(state, PatternObject_GetCode(self->pattern));\r
+#endif\r
+    }\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    match = pattern_new_match((PatternObject*) self->pattern,\r
+                               state, status);\r
+\r
+    if (status == 0 || state->ptr == state->start)\r
+        state->start = (void*) ((char*) state->ptr + state->charsize);\r
+    else\r
+        state->start = state->ptr;\r
+\r
+    return match;\r
+}\r
+\r
+static PyMethodDef scanner_methods[] = {\r
+    {"match", (PyCFunction) scanner_match, METH_NOARGS},\r
+    {"search", (PyCFunction) scanner_search, METH_NOARGS},\r
+    {NULL, NULL}\r
+};\r
+\r
+#define SCAN_OFF(x) offsetof(ScannerObject, x)\r
+static PyMemberDef scanner_members[] = {\r
+    {"pattern", T_OBJECT, SCAN_OFF(pattern),  READONLY},\r
+    {NULL}  /* Sentinel */\r
+};\r
+\r
+statichere PyTypeObject Scanner_Type = {\r
+    PyObject_HEAD_INIT(NULL)\r
+    0, "_" SRE_MODULE ".SRE_Scanner",\r
+    sizeof(ScannerObject), 0,\r
+    (destructor)scanner_dealloc, /*tp_dealloc*/\r
+    0,        /* tp_print */\r
+    0,        /* tp_getattr */\r
+    0,        /* tp_setattr */\r
+    0,        /* tp_reserved */\r
+    0,        /* tp_repr */\r
+    0,        /* tp_as_number */\r
+    0,        /* tp_as_sequence */\r
+    0,        /* tp_as_mapping */\r
+    0,        /* tp_hash */\r
+    0,        /* tp_call */\r
+    0,        /* tp_str */\r
+    0,        /* tp_getattro */\r
+    0,        /* tp_setattro */\r
+    0,        /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT,   /* tp_flags */\r
+    0,        /* tp_doc */\r
+    0,        /* tp_traverse */\r
+    0,        /* tp_clear */\r
+    0,        /* tp_richcompare */\r
+    0,        /* tp_weaklistoffset */\r
+    0,        /* tp_iter */\r
+    0,        /* tp_iternext */\r
+    scanner_methods,    /* tp_methods */\r
+    scanner_members,    /* tp_members */\r
+    0,        /* tp_getset */\r
+};\r
+\r
+static PyObject*\r
+pattern_scanner(PatternObject* pattern, PyObject* args)\r
+{\r
+    /* create search state object */\r
+\r
+    ScannerObject* self;\r
+\r
+    PyObject* string;\r
+    Py_ssize_t start = 0;\r
+    Py_ssize_t end = PY_SSIZE_T_MAX;\r
+    if (!PyArg_ParseTuple(args, "O|nn:scanner", &string, &start, &end))\r
+        return NULL;\r
+\r
+    /* create scanner object */\r
+    self = PyObject_NEW(ScannerObject, &Scanner_Type);\r
+    if (!self)\r
+        return NULL;\r
+    self->pattern = NULL;\r
+\r
+    string = state_init(&self->state, pattern, string, start, end);\r
+    if (!string) {\r
+        Py_DECREF(self);\r
+        return NULL;\r
+    }\r
+\r
+    Py_INCREF(pattern);\r
+    self->pattern = (PyObject*) pattern;\r
+\r
+    return (PyObject*) self;\r
+}\r
+\r
+static PyMethodDef _functions[] = {\r
+    {"compile", _compile, METH_VARARGS},\r
+    {"getcodesize", sre_codesize, METH_NOARGS},\r
+    {"getlower", sre_getlower, METH_VARARGS},\r
+    {NULL, NULL}\r
+};\r
+\r
+#if PY_VERSION_HEX < 0x02030000\r
+DL_EXPORT(void) init_sre(void)\r
+#else\r
+PyMODINIT_FUNC init_sre(void)\r
+#endif\r
+{\r
+    PyObject* m;\r
+    PyObject* d;\r
+    PyObject* x;\r
+\r
+    /* Patch object types */\r
+    if (PyType_Ready(&Pattern_Type) || PyType_Ready(&Match_Type) ||\r
+        PyType_Ready(&Scanner_Type))\r
+        return;\r
+\r
+    m = Py_InitModule("_" SRE_MODULE, _functions);\r
+    if (m == NULL)\r
+        return;\r
+    d = PyModule_GetDict(m);\r
+\r
+    x = PyInt_FromLong(SRE_MAGIC);\r
+    if (x) {\r
+        PyDict_SetItemString(d, "MAGIC", x);\r
+        Py_DECREF(x);\r
+    }\r
+\r
+    x = PyInt_FromLong(sizeof(SRE_CODE));\r
+    if (x) {\r
+        PyDict_SetItemString(d, "CODESIZE", x);\r
+        Py_DECREF(x);\r
+    }\r
+\r
+    x = PyString_FromString(copyright);\r
+    if (x) {\r
+        PyDict_SetItemString(d, "copyright", x);\r
+        Py_DECREF(x);\r
+    }\r
+}\r
+\r
+#endif /* !defined(SRE_RECURSIVE) */\r
+\r
+/* vim:ts=4:sw=4:et\r
+*/\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h b/AppPkg/Applications/Python/PyMod-2.7.2/Modules/zlib/zutil.h
new file mode 100644 (file)
index 0000000..4cee621
--- /dev/null
@@ -0,0 +1,269 @@
+/* zutil.h -- internal interface and configuration of the compression library\r
+ * Copyright (C) 1995-2005 Jean-loup Gailly.\r
+ * For conditions of distribution and use, see copyright notice in zlib.h\r
+ */\r
+\r
+/* WARNING: this file should *not* be used by applications. It is\r
+   part of the implementation of the compression library and is\r
+   subject to change. Applications should only use zlib.h.\r
+ */\r
+\r
+/* @(#) $Id$ */\r
+\r
+#ifndef ZUTIL_H\r
+#define ZUTIL_H\r
+\r
+#define ZLIB_INTERNAL\r
+#include "zlib.h"\r
+\r
+#ifdef STDC\r
+#  ifndef _WIN32_WCE\r
+#    include <stddef.h>\r
+#  endif\r
+#  include <string.h>\r
+#  include <stdlib.h>\r
+#endif\r
+#ifdef NO_ERRNO_H\r
+#   ifdef _WIN32_WCE\r
+      /* The Microsoft C Run-Time Library for Windows CE doesn't have\r
+       * errno.  We define it as a global variable to simplify porting.\r
+       * Its value is always 0 and should not be used.  We rename it to\r
+       * avoid conflict with other libraries that use the same workaround.\r
+       */\r
+#     define errno z_errno\r
+#   endif\r
+    extern int errno;\r
+#else\r
+#  ifndef _WIN32_WCE\r
+#    include <errno.h>\r
+#  endif\r
+#endif\r
+\r
+#ifndef local\r
+#  define local static\r
+#endif\r
+/* compile with -Dlocal if your debugger can't find static symbols */\r
+\r
+typedef unsigned char  uch;\r
+typedef uch FAR uchf;\r
+typedef unsigned short ush;\r
+typedef ush FAR ushf;\r
+typedef unsigned long  ulg;\r
+\r
+extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */\r
+/* (size given to avoid silly warnings with Visual C++) */\r
+\r
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]\r
+\r
+#define ERR_RETURN(strm,err) \\r
+  return (strm->msg = (char*)ERR_MSG(err), (err))\r
+/* To be used only when the state is known to be valid */\r
+\r
+        /* common constants */\r
+\r
+#ifndef DEF_WBITS\r
+#  define DEF_WBITS MAX_WBITS\r
+#endif\r
+/* default windowBits for decompression. MAX_WBITS is for compression only */\r
+\r
+#if MAX_MEM_LEVEL >= 8\r
+#  define DEF_MEM_LEVEL 8\r
+#else\r
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL\r
+#endif\r
+/* default memLevel */\r
+\r
+#define STORED_BLOCK 0\r
+#define STATIC_TREES 1\r
+#define DYN_TREES    2\r
+/* The three kinds of block type */\r
+\r
+#define MIN_MATCH  3\r
+#define MAX_MATCH  258\r
+/* The minimum and maximum match lengths */\r
+\r
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */\r
+\r
+        /* target dependencies */\r
+\r
+#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))\r
+#  define OS_CODE  0x00\r
+#  if defined(__TURBOC__) || defined(__BORLANDC__)\r
+#    if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))\r
+       /* Allow compilation with ANSI keywords only enabled */\r
+       void _Cdecl farfree( void *block );\r
+       void *_Cdecl farmalloc( unsigned long nbytes );\r
+#    else\r
+#      include <alloc.h>\r
+#    endif\r
+#  else /* MSC or DJGPP */\r
+#    include <malloc.h>\r
+#  endif\r
+#endif\r
+\r
+#ifdef AMIGA\r
+#  define OS_CODE  0x01\r
+#endif\r
+\r
+#if defined(VAXC) || defined(VMS)\r
+#  define OS_CODE  0x02\r
+#  define F_OPEN(name, mode) \\r
+     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")\r
+#endif\r
+\r
+#if defined(ATARI) || defined(atarist)\r
+#  define OS_CODE  0x05\r
+#endif\r
+\r
+#ifdef OS2\r
+#  define OS_CODE  0x06\r
+#  ifdef M_I86\r
+     #include <malloc.h>\r
+#  endif\r
+#endif\r
+\r
+#if defined(MACOS) || defined(TARGET_OS_MAC)\r
+#  define OS_CODE  0x07\r
+#  if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os\r
+#    include <unix.h> /* for fdopen */\r
+#  else\r
+#    ifndef fdopen\r
+#      define fdopen(fd,mode) NULL /* No fdopen() */\r
+#    endif\r
+#  endif\r
+#endif\r
+\r
+#ifdef TOPS20\r
+#  define OS_CODE  0x0a\r
+#endif\r
+\r
+#ifdef WIN32\r
+#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */\r
+#    define OS_CODE  0x0b\r
+#  endif\r
+#endif\r
+\r
+#ifdef __50SERIES /* Prime/PRIMOS */\r
+#  define OS_CODE  0x0f\r
+#endif\r
+\r
+#if defined(_BEOS_) || defined(RISCOS)\r
+#  define fdopen(fd,mode) NULL /* No fdopen() */\r
+#endif\r
+\r
+#if (defined(_MSC_VER) && (_MSC_VER > 600))\r
+#  if defined(_WIN32_WCE) || defined(_EFI_STDLIB)\r
+#    define fdopen(fd,mode) NULL /* No fdopen() */\r
+#    ifndef _PTRDIFF_T_DEFINED\r
+       typedef int ptrdiff_t;\r
+#      define _PTRDIFF_T_DEFINED\r
+#    endif\r
+#  else\r
+#    define fdopen(fd,type)  _fdopen(fd,type)\r
+#  endif\r
+#endif\r
+\r
+        /* common defaults */\r
+\r
+#ifndef OS_CODE\r
+#  define OS_CODE  0x03  /* assume Unix */\r
+#endif\r
+\r
+#ifndef F_OPEN\r
+#  define F_OPEN(name, mode) fopen((name), (mode))\r
+#endif\r
+\r
+         /* functions */\r
+\r
+#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)\r
+#  ifndef HAVE_VSNPRINTF\r
+#    define HAVE_VSNPRINTF\r
+#  endif\r
+#endif\r
+#if defined(__CYGWIN__)\r
+#  ifndef HAVE_VSNPRINTF\r
+#    define HAVE_VSNPRINTF\r
+#  endif\r
+#endif\r
+#ifndef HAVE_VSNPRINTF\r
+#  ifdef MSDOS\r
+     /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),\r
+        but for now we just assume it doesn't. */\r
+#    define NO_vsnprintf\r
+#  endif\r
+#  ifdef __TURBOC__\r
+#    define NO_vsnprintf\r
+#  endif\r
+#  ifdef WIN32\r
+     /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */\r
+#    if !defined(vsnprintf) && !defined(NO_vsnprintf)\r
+#      define vsnprintf _vsnprintf\r
+#    endif\r
+#  endif\r
+#  ifdef __SASC\r
+#    define NO_vsnprintf\r
+#  endif\r
+#endif\r
+#ifdef VMS\r
+#  define NO_vsnprintf\r
+#endif\r
+\r
+#if defined(pyr)\r
+#  define NO_MEMCPY\r
+#endif\r
+#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)\r
+ /* Use our own functions for small and medium model with MSC <= 5.0.\r
+  * You may have to use the same strategy for Borland C (untested).\r
+  * The __SC__ check is for Symantec.\r
+  */\r
+#  define NO_MEMCPY\r
+#endif\r
+#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)\r
+#  define HAVE_MEMCPY\r
+#endif\r
+#ifdef HAVE_MEMCPY\r
+#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */\r
+#    define zmemcpy _fmemcpy\r
+#    define zmemcmp _fmemcmp\r
+#    define zmemzero(dest, len) _fmemset(dest, 0, len)\r
+#  else\r
+#    define zmemcpy memcpy\r
+#    define zmemcmp memcmp\r
+#    define zmemzero(dest, len) memset(dest, 0, len)\r
+#  endif\r
+#else\r
+   extern void zmemcpy  OF((Bytef* dest, const Bytef* source, uInt len));\r
+   extern int  zmemcmp  OF((const Bytef* s1, const Bytef* s2, uInt len));\r
+   extern void zmemzero OF((Bytef* dest, uInt len));\r
+#endif\r
+\r
+/* Diagnostic functions */\r
+#ifdef DEBUG\r
+#  include <stdio.h>\r
+   extern int z_verbose;\r
+   extern void z_error    OF((char *m));\r
+#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}\r
+#  define Trace(x) {if (z_verbose>=0) fprintf x ;}\r
+#  define Tracev(x) {if (z_verbose>0) fprintf x ;}\r
+#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}\r
+#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}\r
+#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}\r
+#else\r
+#  define Assert(cond,msg)\r
+#  define Trace(x)\r
+#  define Tracev(x)\r
+#  define Tracevv(x)\r
+#  define Tracec(c,x)\r
+#  define Tracecv(c,x)\r
+#endif\r
+\r
+\r
+voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));\r
+void   zcfree  OF((voidpf opaque, voidpf ptr));\r
+\r
+#define ZALLOC(strm, items, size) \\r
+           (*((strm)->zalloc))((strm)->opaque, (items), (size))\r
+#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))\r
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}\r
+\r
+#endif /* ZUTIL_H */\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c b/AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c
new file mode 100644 (file)
index 0000000..1fbc675
--- /dev/null
@@ -0,0 +1,4370 @@
+/* Long (arbitrary precision) integer object implementation */\r
+\r
+/* XXX The functional organization of this file is terrible */\r
+\r
+#include "Python.h"\r
+#include "longintrepr.h"\r
+#include "structseq.h"\r
+\r
+#include <float.h>\r
+#include <ctype.h>\r
+#include <stddef.h>\r
+\r
+/* For long multiplication, use the O(N**2) school algorithm unless\r
+ * both operands contain more than KARATSUBA_CUTOFF digits (this\r
+ * being an internal Python long digit, in base PyLong_BASE).\r
+ */\r
+#define KARATSUBA_CUTOFF 70\r
+#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)\r
+\r
+/* For exponentiation, use the binary left-to-right algorithm\r
+ * unless the exponent contains more than FIVEARY_CUTOFF digits.\r
+ * In that case, do 5 bits at a time.  The potential drawback is that\r
+ * a table of 2**5 intermediate results is computed.\r
+ */\r
+#define FIVEARY_CUTOFF 8\r
+\r
+#ifndef ABS\r
+  #define ABS(x) ((x) < 0 ? -(x) : (x))\r
+#endif\r
+\r
+#ifndef MAX\r
+  #define MAX(x, y) ((x) < (y) ? (y) : (x))\r
+#endif\r
+\r
+#ifndef MIN\r
+  #define MIN(x, y) ((x) > (y) ? (y) : (x))\r
+#endif\r
+\r
+#define SIGCHECK(PyTryBlock)                            \\r
+    do {                                                \\r
+        if (--_Py_Ticker < 0) {                         \\r
+            _Py_Ticker = _Py_CheckInterval;             \\r
+            if (PyErr_CheckSignals()) PyTryBlock        \\r
+                                          }             \\r
+    } while(0)\r
+\r
+/* Normalize (remove leading zeros from) a long int object.\r
+   Doesn't attempt to free the storage--in most cases, due to the nature\r
+   of the algorithms used, this could save at most be one word anyway. */\r
+\r
+static PyLongObject *\r
+long_normalize(register PyLongObject *v)\r
+{\r
+    Py_ssize_t j = ABS(Py_SIZE(v));\r
+    Py_ssize_t i = j;\r
+\r
+    while (i > 0 && v->ob_digit[i-1] == 0)\r
+        --i;\r
+    if (i != j)\r
+        Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;\r
+    return v;\r
+}\r
+\r
+/* Allocate a new long int object with size digits.\r
+   Return NULL and set exception if we run out of memory. */\r
+\r
+#define MAX_LONG_DIGITS \\r
+    ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))\r
+\r
+PyLongObject *\r
+_PyLong_New(Py_ssize_t size)\r
+{\r
+    if (size > (Py_ssize_t)MAX_LONG_DIGITS) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "too many digits in integer");\r
+        return NULL;\r
+    }\r
+    /* coverity[ampersand_in_size] */\r
+    /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect\r
+       overflow */\r
+    return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);\r
+}\r
+\r
+PyObject *\r
+_PyLong_Copy(PyLongObject *src)\r
+{\r
+    PyLongObject *result;\r
+    Py_ssize_t i;\r
+\r
+    assert(src != NULL);\r
+    i = src->ob_size;\r
+    if (i < 0)\r
+        i = -(i);\r
+    result = _PyLong_New(i);\r
+    if (result != NULL) {\r
+        result->ob_size = src->ob_size;\r
+        while (--i >= 0)\r
+            result->ob_digit[i] = src->ob_digit[i];\r
+    }\r
+    return (PyObject *)result;\r
+}\r
+\r
+/* Create a new long int object from a C long int */\r
+\r
+PyObject *\r
+PyLong_FromLong(long ival)\r
+{\r
+    PyLongObject *v;\r
+    unsigned long abs_ival;\r
+    unsigned long t;  /* unsigned so >> doesn't propagate sign bit */\r
+    int ndigits = 0;\r
+    int negative = 0;\r
+\r
+    if (ival < 0) {\r
+        /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then\r
+           ANSI C says that the result of -ival is undefined when ival\r
+           == LONG_MIN.  Hence the following workaround. */\r
+        abs_ival = (unsigned long)(-1-ival) + 1;\r
+        negative = 1;\r
+    }\r
+    else {\r
+        abs_ival = (unsigned long)ival;\r
+    }\r
+\r
+    /* Count the number of Python digits.\r
+       We used to pick 5 ("big enough for anything"), but that's a\r
+       waste of time and space given that 5*15 = 75 bits are rarely\r
+       needed. */\r
+    t = abs_ival;\r
+    while (t) {\r
+        ++ndigits;\r
+        t >>= PyLong_SHIFT;\r
+    }\r
+    v = _PyLong_New(ndigits);\r
+    if (v != NULL) {\r
+        digit *p = v->ob_digit;\r
+        v->ob_size = negative ? -ndigits : ndigits;\r
+        t = abs_ival;\r
+        while (t) {\r
+            *p++ = (digit)(t & PyLong_MASK);\r
+            t >>= PyLong_SHIFT;\r
+        }\r
+    }\r
+    return (PyObject *)v;\r
+}\r
+\r
+/* Create a new long int object from a C unsigned long int */\r
+\r
+PyObject *\r
+PyLong_FromUnsignedLong(unsigned long ival)\r
+{\r
+    PyLongObject *v;\r
+    unsigned long t;\r
+    int ndigits = 0;\r
+\r
+    /* Count the number of Python digits. */\r
+    t = (unsigned long)ival;\r
+    while (t) {\r
+        ++ndigits;\r
+        t >>= PyLong_SHIFT;\r
+    }\r
+    v = _PyLong_New(ndigits);\r
+    if (v != NULL) {\r
+        digit *p = v->ob_digit;\r
+        Py_SIZE(v) = ndigits;\r
+        while (ival) {\r
+            *p++ = (digit)(ival & PyLong_MASK);\r
+            ival >>= PyLong_SHIFT;\r
+        }\r
+    }\r
+    return (PyObject *)v;\r
+}\r
+\r
+/* Create a new long int object from a C double */\r
+\r
+PyObject *\r
+PyLong_FromDouble(double dval)\r
+{\r
+    PyLongObject *v;\r
+    double frac;\r
+    int i, ndig, expo, neg;\r
+    neg = 0;\r
+    if (Py_IS_INFINITY(dval)) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "cannot convert float infinity to integer");\r
+        return NULL;\r
+    }\r
+    if (Py_IS_NAN(dval)) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "cannot convert float NaN to integer");\r
+        return NULL;\r
+    }\r
+    if (dval < 0.0) {\r
+        neg = 1;\r
+        dval = -dval;\r
+    }\r
+    frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */\r
+    if (expo <= 0)\r
+        return PyLong_FromLong(0L);\r
+    ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */\r
+    v = _PyLong_New(ndig);\r
+    if (v == NULL)\r
+        return NULL;\r
+    frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);\r
+    for (i = ndig; --i >= 0; ) {\r
+        digit bits = (digit)frac;\r
+        v->ob_digit[i] = bits;\r
+        frac = frac - (double)bits;\r
+        frac = ldexp(frac, PyLong_SHIFT);\r
+    }\r
+    if (neg)\r
+        Py_SIZE(v) = -(Py_SIZE(v));\r
+    return (PyObject *)v;\r
+}\r
+\r
+/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define\r
+ * anything about what happens when a signed integer operation overflows,\r
+ * and some compilers think they're doing you a favor by being "clever"\r
+ * then.  The bit pattern for the largest postive signed long is\r
+ * (unsigned long)LONG_MAX, and for the smallest negative signed long\r
+ * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.\r
+ * However, some other compilers warn about applying unary minus to an\r
+ * unsigned operand.  Hence the weird "0-".\r
+ */\r
+#define PY_ABS_LONG_MIN         (0-(unsigned long)LONG_MIN)\r
+#define PY_ABS_SSIZE_T_MIN      (0-(size_t)PY_SSIZE_T_MIN)\r
+\r
+/* Get a C long int from a Python long or Python int object.\r
+   On overflow, returns -1 and sets *overflow to 1 or -1 depending\r
+   on the sign of the result.  Otherwise *overflow is 0.\r
+\r
+   For other errors (e.g., type error), returns -1 and sets an error\r
+   condition.\r
+*/\r
+\r
+long\r
+PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)\r
+{\r
+    /* This version by Tim Peters */\r
+    register PyLongObject *v;\r
+    unsigned long x, prev;\r
+    long res;\r
+    Py_ssize_t i;\r
+    int sign;\r
+    int do_decref = 0; /* if nb_int was called */\r
+\r
+    *overflow = 0;\r
+    if (vv == NULL) {\r
+        PyErr_BadInternalCall();\r
+        return -1;\r
+    }\r
+\r
+    if(PyInt_Check(vv))\r
+        return PyInt_AsLong(vv);\r
+\r
+    if (!PyLong_Check(vv)) {\r
+        PyNumberMethods *nb;\r
+        nb = vv->ob_type->tp_as_number;\r
+        if (nb == NULL || nb->nb_int == NULL) {\r
+            PyErr_SetString(PyExc_TypeError,\r
+                            "an integer is required");\r
+            return -1;\r
+        }\r
+        vv = (*nb->nb_int) (vv);\r
+        if (vv == NULL)\r
+            return -1;\r
+        do_decref = 1;\r
+        if(PyInt_Check(vv)) {\r
+            res = PyInt_AsLong(vv);\r
+            goto exit;\r
+        }\r
+        if (!PyLong_Check(vv)) {\r
+            Py_DECREF(vv);\r
+            PyErr_SetString(PyExc_TypeError,\r
+                            "nb_int should return int object");\r
+            return -1;\r
+        }\r
+    }\r
+\r
+    res = -1;\r
+    v = (PyLongObject *)vv;\r
+    i = Py_SIZE(v);\r
+\r
+    switch (i) {\r
+    case -1:\r
+        res = -(sdigit)v->ob_digit[0];\r
+        break;\r
+    case 0:\r
+        res = 0;\r
+        break;\r
+    case 1:\r
+        res = v->ob_digit[0];\r
+        break;\r
+    default:\r
+        sign = 1;\r
+        x = 0;\r
+        if (i < 0) {\r
+            sign = -1;\r
+            i = -(i);\r
+        }\r
+        while (--i >= 0) {\r
+            prev = x;\r
+            x = (x << PyLong_SHIFT) + v->ob_digit[i];\r
+            if ((x >> PyLong_SHIFT) != prev) {\r
+                *overflow = sign;\r
+                goto exit;\r
+            }\r
+        }\r
+        /* Haven't lost any bits, but casting to long requires extra\r
+         * care (see comment above).\r
+         */\r
+        if (x <= (unsigned long)LONG_MAX) {\r
+            res = (long)x * sign;\r
+        }\r
+        else if (sign < 0 && x == PY_ABS_LONG_MIN) {\r
+            res = LONG_MIN;\r
+        }\r
+        else {\r
+            *overflow = sign;\r
+            /* res is already set to -1 */\r
+        }\r
+    }\r
+  exit:\r
+    if (do_decref) {\r
+        Py_DECREF(vv);\r
+    }\r
+    return res;\r
+}\r
+\r
+/* Get a C long int from a long int object.\r
+   Returns -1 and sets an error condition if overflow occurs. */\r
+\r
+long\r
+PyLong_AsLong(PyObject *obj)\r
+{\r
+    int overflow;\r
+    long result = PyLong_AsLongAndOverflow(obj, &overflow);\r
+    if (overflow) {\r
+        /* XXX: could be cute and give a different\r
+           message for overflow == -1 */\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "Python int too large to convert to C long");\r
+    }\r
+    return result;\r
+}\r
+\r
+/* Get a Py_ssize_t from a long int object.\r
+   Returns -1 and sets an error condition if overflow occurs. */\r
+\r
+Py_ssize_t\r
+PyLong_AsSsize_t(PyObject *vv) {\r
+    register PyLongObject *v;\r
+    size_t x, prev;\r
+    Py_ssize_t i;\r
+    int sign;\r
+\r
+    if (vv == NULL || !PyLong_Check(vv)) {\r
+        PyErr_BadInternalCall();\r
+        return -1;\r
+    }\r
+    v = (PyLongObject *)vv;\r
+    i = v->ob_size;\r
+    sign = 1;\r
+    x = 0;\r
+    if (i < 0) {\r
+        sign = -1;\r
+        i = -(i);\r
+    }\r
+    while (--i >= 0) {\r
+        prev = x;\r
+        x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
+        if ((x >> PyLong_SHIFT) != prev)\r
+            goto overflow;\r
+    }\r
+    /* Haven't lost any bits, but casting to a signed type requires\r
+     * extra care (see comment above).\r
+     */\r
+    if (x <= (size_t)PY_SSIZE_T_MAX) {\r
+        return (Py_ssize_t)x * sign;\r
+    }\r
+    else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {\r
+        return PY_SSIZE_T_MIN;\r
+    }\r
+    /* else overflow */\r
+\r
+  overflow:\r
+    PyErr_SetString(PyExc_OverflowError,\r
+                    "long int too large to convert to int");\r
+    return -1;\r
+}\r
+\r
+/* Get a C unsigned long int from a long int object.\r
+   Returns -1 and sets an error condition if overflow occurs. */\r
+\r
+unsigned long\r
+PyLong_AsUnsignedLong(PyObject *vv)\r
+{\r
+    register PyLongObject *v;\r
+    unsigned long x, prev;\r
+    Py_ssize_t i;\r
+\r
+    if (vv == NULL || !PyLong_Check(vv)) {\r
+        if (vv != NULL && PyInt_Check(vv)) {\r
+            long val = PyInt_AsLong(vv);\r
+            if (val < 0) {\r
+                PyErr_SetString(PyExc_OverflowError,\r
+                                "can't convert negative value "\r
+                                "to unsigned long");\r
+                return (unsigned long) -1;\r
+            }\r
+            return val;\r
+        }\r
+        PyErr_BadInternalCall();\r
+        return (unsigned long) -1;\r
+    }\r
+    v = (PyLongObject *)vv;\r
+    i = Py_SIZE(v);\r
+    x = 0;\r
+    if (i < 0) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "can't convert negative value to unsigned long");\r
+        return (unsigned long) -1;\r
+    }\r
+    while (--i >= 0) {\r
+        prev = x;\r
+        x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
+        if ((x >> PyLong_SHIFT) != prev) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "long int too large to convert");\r
+            return (unsigned long) -1;\r
+        }\r
+    }\r
+    return x;\r
+}\r
+\r
+/* Get a C unsigned long int from a long int object, ignoring the high bits.\r
+   Returns -1 and sets an error condition if an error occurs. */\r
+\r
+unsigned long\r
+PyLong_AsUnsignedLongMask(PyObject *vv)\r
+{\r
+    register PyLongObject *v;\r
+    unsigned long x;\r
+    Py_ssize_t i;\r
+    int sign;\r
+\r
+    if (vv == NULL || !PyLong_Check(vv)) {\r
+        if (vv != NULL && PyInt_Check(vv))\r
+            return PyInt_AsUnsignedLongMask(vv);\r
+        PyErr_BadInternalCall();\r
+        return (unsigned long) -1;\r
+    }\r
+    v = (PyLongObject *)vv;\r
+    i = v->ob_size;\r
+    sign = 1;\r
+    x = 0;\r
+    if (i < 0) {\r
+        sign = -1;\r
+        i = -i;\r
+    }\r
+    while (--i >= 0) {\r
+        x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
+    }\r
+    return x * sign;\r
+}\r
+\r
+int\r
+_PyLong_Sign(PyObject *vv)\r
+{\r
+    PyLongObject *v = (PyLongObject *)vv;\r
+\r
+    assert(v != NULL);\r
+    assert(PyLong_Check(v));\r
+\r
+    return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);\r
+}\r
+\r
+size_t\r
+_PyLong_NumBits(PyObject *vv)\r
+{\r
+    PyLongObject *v = (PyLongObject *)vv;\r
+    size_t result = 0;\r
+    Py_ssize_t ndigits;\r
+\r
+    assert(v != NULL);\r
+    assert(PyLong_Check(v));\r
+    ndigits = ABS(Py_SIZE(v));\r
+    assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);\r
+    if (ndigits > 0) {\r
+        digit msd = v->ob_digit[ndigits - 1];\r
+\r
+        result = (ndigits - 1) * PyLong_SHIFT;\r
+        if (result / PyLong_SHIFT != (size_t)(ndigits - 1))\r
+            goto Overflow;\r
+        do {\r
+            ++result;\r
+            if (result == 0)\r
+                goto Overflow;\r
+            msd >>= 1;\r
+        } while (msd);\r
+    }\r
+    return result;\r
+\r
+  Overflow:\r
+    PyErr_SetString(PyExc_OverflowError, "long has too many bits "\r
+                    "to express in a platform size_t");\r
+    return (size_t)-1;\r
+}\r
+\r
+PyObject *\r
+_PyLong_FromByteArray(const unsigned char* bytes, size_t n,\r
+                      int little_endian, int is_signed)\r
+{\r
+    const unsigned char* pstartbyte;    /* LSB of bytes */\r
+    int incr;                           /* direction to move pstartbyte */\r
+    const unsigned char* pendbyte;      /* MSB of bytes */\r
+    size_t numsignificantbytes;         /* number of bytes that matter */\r
+    Py_ssize_t ndigits;                 /* number of Python long digits */\r
+    PyLongObject* v;                    /* result */\r
+    Py_ssize_t idigit = 0;              /* next free index in v->ob_digit */\r
+\r
+    if (n == 0)\r
+        return PyLong_FromLong(0L);\r
+\r
+    if (little_endian) {\r
+        pstartbyte = bytes;\r
+        pendbyte = bytes + n - 1;\r
+        incr = 1;\r
+    }\r
+    else {\r
+        pstartbyte = bytes + n - 1;\r
+        pendbyte = bytes;\r
+        incr = -1;\r
+    }\r
+\r
+    if (is_signed)\r
+        is_signed = *pendbyte >= 0x80;\r
+\r
+    /* Compute numsignificantbytes.  This consists of finding the most\r
+       significant byte.  Leading 0 bytes are insignificant if the number\r
+       is positive, and leading 0xff bytes if negative. */\r
+    {\r
+        size_t i;\r
+        const unsigned char* p = pendbyte;\r
+        const int pincr = -incr;  /* search MSB to LSB */\r
+        const unsigned char insignficant = is_signed ? 0xff : 0x00;\r
+\r
+        for (i = 0; i < n; ++i, p += pincr) {\r
+            if (*p != insignficant)\r
+                break;\r
+        }\r
+        numsignificantbytes = n - i;\r
+        /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so\r
+           actually has 2 significant bytes.  OTOH, 0xff0001 ==\r
+           -0x00ffff, so we wouldn't *need* to bump it there; but we\r
+           do for 0xffff = -0x0001.  To be safe without bothering to\r
+           check every case, bump it regardless. */\r
+        if (is_signed && numsignificantbytes < n)\r
+            ++numsignificantbytes;\r
+    }\r
+\r
+    /* How many Python long digits do we need?  We have\r
+       8*numsignificantbytes bits, and each Python long digit has\r
+       PyLong_SHIFT bits, so it's the ceiling of the quotient. */\r
+    /* catch overflow before it happens */\r
+    if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "byte array too long to convert to int");\r
+        return NULL;\r
+    }\r
+    ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;\r
+    v = _PyLong_New(ndigits);\r
+    if (v == NULL)\r
+        return NULL;\r
+\r
+    /* Copy the bits over.  The tricky parts are computing 2's-comp on\r
+       the fly for signed numbers, and dealing with the mismatch between\r
+       8-bit bytes and (probably) 15-bit Python digits.*/\r
+    {\r
+        size_t i;\r
+        twodigits carry = 1;                    /* for 2's-comp calculation */\r
+        twodigits accum = 0;                    /* sliding register */\r
+        unsigned int accumbits = 0;             /* number of bits in accum */\r
+        const unsigned char* p = pstartbyte;\r
+\r
+        for (i = 0; i < numsignificantbytes; ++i, p += incr) {\r
+            twodigits thisbyte = *p;\r
+            /* Compute correction for 2's comp, if needed. */\r
+            if (is_signed) {\r
+                thisbyte = (0xff ^ thisbyte) + carry;\r
+                carry = thisbyte >> 8;\r
+                thisbyte &= 0xff;\r
+            }\r
+            /* Because we're going LSB to MSB, thisbyte is\r
+               more significant than what's already in accum,\r
+               so needs to be prepended to accum. */\r
+            accum |= (twodigits)thisbyte << accumbits;\r
+            accumbits += 8;\r
+            if (accumbits >= PyLong_SHIFT) {\r
+                /* There's enough to fill a Python digit. */\r
+                assert(idigit < ndigits);\r
+                v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);\r
+                ++idigit;\r
+                accum >>= PyLong_SHIFT;\r
+                accumbits -= PyLong_SHIFT;\r
+                assert(accumbits < PyLong_SHIFT);\r
+            }\r
+        }\r
+        assert(accumbits < PyLong_SHIFT);\r
+        if (accumbits) {\r
+            assert(idigit < ndigits);\r
+            v->ob_digit[idigit] = (digit)accum;\r
+            ++idigit;\r
+        }\r
+    }\r
+\r
+    Py_SIZE(v) = is_signed ? -idigit : idigit;\r
+    return (PyObject *)long_normalize(v);\r
+}\r
+\r
+int\r
+_PyLong_AsByteArray(PyLongObject* v,\r
+                    unsigned char* bytes, size_t n,\r
+                    int little_endian, int is_signed)\r
+{\r
+    Py_ssize_t i;               /* index into v->ob_digit */\r
+    Py_ssize_t ndigits;         /* |v->ob_size| */\r
+    twodigits accum;            /* sliding register */\r
+    unsigned int accumbits;     /* # bits in accum */\r
+    int do_twos_comp;           /* store 2's-comp?  is_signed and v < 0 */\r
+    digit carry;                /* for computing 2's-comp */\r
+    size_t j;                   /* # bytes filled */\r
+    unsigned char* p;           /* pointer to next byte in bytes */\r
+    int pincr;                  /* direction to move p */\r
+\r
+    assert(v != NULL && PyLong_Check(v));\r
+\r
+    if (Py_SIZE(v) < 0) {\r
+        ndigits = -(Py_SIZE(v));\r
+        if (!is_signed) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "can't convert negative long to unsigned");\r
+            return -1;\r
+        }\r
+        do_twos_comp = 1;\r
+    }\r
+    else {\r
+        ndigits = Py_SIZE(v);\r
+        do_twos_comp = 0;\r
+    }\r
+\r
+    if (little_endian) {\r
+        p = bytes;\r
+        pincr = 1;\r
+    }\r
+    else {\r
+        p = bytes + n - 1;\r
+        pincr = -1;\r
+    }\r
+\r
+    /* Copy over all the Python digits.\r
+       It's crucial that every Python digit except for the MSD contribute\r
+       exactly PyLong_SHIFT bits to the total, so first assert that the long is\r
+       normalized. */\r
+    assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);\r
+    j = 0;\r
+    accum = 0;\r
+    accumbits = 0;\r
+    carry = do_twos_comp ? 1 : 0;\r
+    for (i = 0; i < ndigits; ++i) {\r
+        digit thisdigit = v->ob_digit[i];\r
+        if (do_twos_comp) {\r
+            thisdigit = (thisdigit ^ PyLong_MASK) + carry;\r
+            carry = thisdigit >> PyLong_SHIFT;\r
+            thisdigit &= PyLong_MASK;\r
+        }\r
+        /* Because we're going LSB to MSB, thisdigit is more\r
+           significant than what's already in accum, so needs to be\r
+           prepended to accum. */\r
+        accum |= (twodigits)thisdigit << accumbits;\r
+\r
+        /* The most-significant digit may be (probably is) at least\r
+           partly empty. */\r
+        if (i == ndigits - 1) {\r
+            /* Count # of sign bits -- they needn't be stored,\r
+             * although for signed conversion we need later to\r
+             * make sure at least one sign bit gets stored. */\r
+            digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;\r
+            while (s != 0) {\r
+                s >>= 1;\r
+                accumbits++;\r
+            }\r
+        }\r
+        else\r
+            accumbits += PyLong_SHIFT;\r
+\r
+        /* Store as many bytes as possible. */\r
+        while (accumbits >= 8) {\r
+            if (j >= n)\r
+                goto Overflow;\r
+            ++j;\r
+            *p = (unsigned char)(accum & 0xff);\r
+            p += pincr;\r
+            accumbits -= 8;\r
+            accum >>= 8;\r
+        }\r
+    }\r
+\r
+    /* Store the straggler (if any). */\r
+    assert(accumbits < 8);\r
+    assert(carry == 0);  /* else do_twos_comp and *every* digit was 0 */\r
+    if (accumbits > 0) {\r
+        if (j >= n)\r
+            goto Overflow;\r
+        ++j;\r
+        if (do_twos_comp) {\r
+            /* Fill leading bits of the byte with sign bits\r
+               (appropriately pretending that the long had an\r
+               infinite supply of sign bits). */\r
+            accum |= (~(twodigits)0) << accumbits;\r
+        }\r
+        *p = (unsigned char)(accum & 0xff);\r
+        p += pincr;\r
+    }\r
+    else if (j == n && n > 0 && is_signed) {\r
+        /* The main loop filled the byte array exactly, so the code\r
+           just above didn't get to ensure there's a sign bit, and the\r
+           loop below wouldn't add one either.  Make sure a sign bit\r
+           exists. */\r
+        unsigned char msb = *(p - pincr);\r
+        int sign_bit_set = msb >= 0x80;\r
+        assert(accumbits == 0);\r
+        if (sign_bit_set == do_twos_comp)\r
+            return 0;\r
+        else\r
+            goto Overflow;\r
+    }\r
+\r
+    /* Fill remaining bytes with copies of the sign bit. */\r
+    {\r
+        unsigned char signbyte = do_twos_comp ? 0xffU : 0U;\r
+        for ( ; j < n; ++j, p += pincr)\r
+            *p = signbyte;\r
+    }\r
+\r
+    return 0;\r
+\r
+  Overflow:\r
+    PyErr_SetString(PyExc_OverflowError, "long too big to convert");\r
+    return -1;\r
+\r
+}\r
+\r
+/* Create a new long (or int) object from a C pointer */\r
+\r
+PyObject *\r
+PyLong_FromVoidPtr(void *p)\r
+{\r
+#if SIZEOF_VOID_P <= SIZEOF_LONG\r
+    if ((long)p < 0)\r
+        return PyLong_FromUnsignedLong((unsigned long)p);\r
+    return PyInt_FromLong((long)p);\r
+#else\r
+\r
+#ifndef HAVE_LONG_LONG\r
+#   error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"\r
+#endif\r
+#if SIZEOF_LONG_LONG < SIZEOF_VOID_P\r
+#   error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"\r
+#endif\r
+    /* optimize null pointers */\r
+    if (p == NULL)\r
+        return PyInt_FromLong(0);\r
+    return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);\r
+\r
+#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */\r
+}\r
+\r
+/* Get a C pointer from a long object (or an int object in some cases) */\r
+\r
+void *\r
+PyLong_AsVoidPtr(PyObject *vv)\r
+{\r
+    /* This function will allow int or long objects. If vv is neither,\r
+       then the PyLong_AsLong*() functions will raise the exception:\r
+       PyExc_SystemError, "bad argument to internal function"\r
+    */\r
+#if SIZEOF_VOID_P <= SIZEOF_LONG\r
+    long x;\r
+\r
+    if (PyInt_Check(vv))\r
+        x = PyInt_AS_LONG(vv);\r
+    else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)\r
+        x = PyLong_AsLong(vv);\r
+    else\r
+        x = PyLong_AsUnsignedLong(vv);\r
+#else\r
+\r
+#ifndef HAVE_LONG_LONG\r
+#   error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"\r
+#endif\r
+#if SIZEOF_LONG_LONG < SIZEOF_VOID_P\r
+#   error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"\r
+#endif\r
+    PY_LONG_LONG x;\r
+\r
+    if (PyInt_Check(vv))\r
+        x = PyInt_AS_LONG(vv);\r
+    else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)\r
+        x = PyLong_AsLongLong(vv);\r
+    else\r
+        x = PyLong_AsUnsignedLongLong(vv);\r
+\r
+#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */\r
+\r
+    if (x == -1 && PyErr_Occurred())\r
+        return NULL;\r
+    return (void *)x;\r
+}\r
+\r
+#ifdef HAVE_LONG_LONG\r
+\r
+/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later\r
+ * rewritten to use the newer PyLong_{As,From}ByteArray API.\r
+ */\r
+\r
+#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one\r
+#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)\r
+\r
+/* Create a new long int object from a C PY_LONG_LONG int. */\r
+\r
+PyObject *\r
+PyLong_FromLongLong(PY_LONG_LONG ival)\r
+{\r
+    PyLongObject *v;\r
+    unsigned PY_LONG_LONG abs_ival;\r
+    unsigned PY_LONG_LONG t;  /* unsigned so >> doesn't propagate sign bit */\r
+    int ndigits = 0;\r
+    int negative = 0;\r
+\r
+    if (ival < 0) {\r
+        /* avoid signed overflow on negation;  see comments\r
+           in PyLong_FromLong above. */\r
+        abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;\r
+        negative = 1;\r
+    }\r
+    else {\r
+        abs_ival = (unsigned PY_LONG_LONG)ival;\r
+    }\r
+\r
+    /* Count the number of Python digits.\r
+       We used to pick 5 ("big enough for anything"), but that's a\r
+       waste of time and space given that 5*15 = 75 bits are rarely\r
+       needed. */\r
+    t = abs_ival;\r
+    while (t) {\r
+        ++ndigits;\r
+        t >>= PyLong_SHIFT;\r
+    }\r
+    v = _PyLong_New(ndigits);\r
+    if (v != NULL) {\r
+        digit *p = v->ob_digit;\r
+        Py_SIZE(v) = negative ? -ndigits : ndigits;\r
+        t = abs_ival;\r
+        while (t) {\r
+            *p++ = (digit)(t & PyLong_MASK);\r
+            t >>= PyLong_SHIFT;\r
+        }\r
+    }\r
+    return (PyObject *)v;\r
+}\r
+\r
+/* Create a new long int object from a C unsigned PY_LONG_LONG int. */\r
+\r
+PyObject *\r
+PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)\r
+{\r
+    PyLongObject *v;\r
+    unsigned PY_LONG_LONG t;\r
+    int ndigits = 0;\r
+\r
+    /* Count the number of Python digits. */\r
+    t = (unsigned PY_LONG_LONG)ival;\r
+    while (t) {\r
+        ++ndigits;\r
+        t >>= PyLong_SHIFT;\r
+    }\r
+    v = _PyLong_New(ndigits);\r
+    if (v != NULL) {\r
+        digit *p = v->ob_digit;\r
+        Py_SIZE(v) = ndigits;\r
+        while (ival) {\r
+            *p++ = (digit)(ival & PyLong_MASK);\r
+            ival >>= PyLong_SHIFT;\r
+        }\r
+    }\r
+    return (PyObject *)v;\r
+}\r
+\r
+/* Create a new long int object from a C Py_ssize_t. */\r
+\r
+PyObject *\r
+PyLong_FromSsize_t(Py_ssize_t ival)\r
+{\r
+    Py_ssize_t bytes = ival;\r
+    int one = 1;\r
+    return _PyLong_FromByteArray((unsigned char *)&bytes,\r
+                                 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);\r
+}\r
+\r
+/* Create a new long int object from a C size_t. */\r
+\r
+PyObject *\r
+PyLong_FromSize_t(size_t ival)\r
+{\r
+    size_t bytes = ival;\r
+    int one = 1;\r
+    return _PyLong_FromByteArray((unsigned char *)&bytes,\r
+                                 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);\r
+}\r
+\r
+/* Get a C PY_LONG_LONG int from a long int object.\r
+   Return -1 and set an error if overflow occurs. */\r
+\r
+PY_LONG_LONG\r
+PyLong_AsLongLong(PyObject *vv)\r
+{\r
+    PY_LONG_LONG bytes;\r
+    int one = 1;\r
+    int res;\r
+\r
+    if (vv == NULL) {\r
+        PyErr_BadInternalCall();\r
+        return -1;\r
+    }\r
+    if (!PyLong_Check(vv)) {\r
+        PyNumberMethods *nb;\r
+        PyObject *io;\r
+        if (PyInt_Check(vv))\r
+            return (PY_LONG_LONG)PyInt_AsLong(vv);\r
+        if ((nb = vv->ob_type->tp_as_number) == NULL ||\r
+            nb->nb_int == NULL) {\r
+            PyErr_SetString(PyExc_TypeError, "an integer is required");\r
+            return -1;\r
+        }\r
+        io = (*nb->nb_int) (vv);\r
+        if (io == NULL)\r
+            return -1;\r
+        if (PyInt_Check(io)) {\r
+            bytes = PyInt_AsLong(io);\r
+            Py_DECREF(io);\r
+            return bytes;\r
+        }\r
+        if (PyLong_Check(io)) {\r
+            bytes = PyLong_AsLongLong(io);\r
+            Py_DECREF(io);\r
+            return bytes;\r
+        }\r
+        Py_DECREF(io);\r
+        PyErr_SetString(PyExc_TypeError, "integer conversion failed");\r
+        return -1;\r
+    }\r
+\r
+    res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,\r
+                              SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);\r
+\r
+    /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */\r
+    if (res < 0)\r
+        return (PY_LONG_LONG)-1;\r
+    else\r
+        return bytes;\r
+}\r
+\r
+/* Get a C unsigned PY_LONG_LONG int from a long int object.\r
+   Return -1 and set an error if overflow occurs. */\r
+\r
+unsigned PY_LONG_LONG\r
+PyLong_AsUnsignedLongLong(PyObject *vv)\r
+{\r
+    unsigned PY_LONG_LONG bytes;\r
+    int one = 1;\r
+    int res;\r
+\r
+    if (vv == NULL || !PyLong_Check(vv)) {\r
+        PyErr_BadInternalCall();\r
+        return (unsigned PY_LONG_LONG)-1;\r
+    }\r
+\r
+    res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,\r
+                              SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);\r
+\r
+    /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */\r
+    if (res < 0)\r
+        return (unsigned PY_LONG_LONG)res;\r
+    else\r
+        return bytes;\r
+}\r
+\r
+/* Get a C unsigned long int from a long int object, ignoring the high bits.\r
+   Returns -1 and sets an error condition if an error occurs. */\r
+\r
+unsigned PY_LONG_LONG\r
+PyLong_AsUnsignedLongLongMask(PyObject *vv)\r
+{\r
+    register PyLongObject *v;\r
+    unsigned PY_LONG_LONG x;\r
+    Py_ssize_t i;\r
+    int sign;\r
+\r
+    if (vv == NULL || !PyLong_Check(vv)) {\r
+        PyErr_BadInternalCall();\r
+        return (unsigned long) -1;\r
+    }\r
+    v = (PyLongObject *)vv;\r
+    i = v->ob_size;\r
+    sign = 1;\r
+    x = 0;\r
+    if (i < 0) {\r
+        sign = -1;\r
+        i = -i;\r
+    }\r
+    while (--i >= 0) {\r
+        x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
+    }\r
+    return x * sign;\r
+}\r
+\r
+/* Get a C long long int from a Python long or Python int object.\r
+   On overflow, returns -1 and sets *overflow to 1 or -1 depending\r
+   on the sign of the result.  Otherwise *overflow is 0.\r
+\r
+   For other errors (e.g., type error), returns -1 and sets an error\r
+   condition.\r
+*/\r
+\r
+PY_LONG_LONG\r
+PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)\r
+{\r
+    /* This version by Tim Peters */\r
+    register PyLongObject *v;\r
+    unsigned PY_LONG_LONG x, prev;\r
+    PY_LONG_LONG res;\r
+    Py_ssize_t i;\r
+    int sign;\r
+    int do_decref = 0; /* if nb_int was called */\r
+\r
+    *overflow = 0;\r
+    if (vv == NULL) {\r
+        PyErr_BadInternalCall();\r
+        return -1;\r
+    }\r
+\r
+    if (PyInt_Check(vv))\r
+        return PyInt_AsLong(vv);\r
+\r
+    if (!PyLong_Check(vv)) {\r
+        PyNumberMethods *nb;\r
+        nb = vv->ob_type->tp_as_number;\r
+        if (nb == NULL || nb->nb_int == NULL) {\r
+            PyErr_SetString(PyExc_TypeError,\r
+                            "an integer is required");\r
+            return -1;\r
+        }\r
+        vv = (*nb->nb_int) (vv);\r
+        if (vv == NULL)\r
+            return -1;\r
+        do_decref = 1;\r
+        if(PyInt_Check(vv)) {\r
+            res = PyInt_AsLong(vv);\r
+            goto exit;\r
+        }\r
+        if (!PyLong_Check(vv)) {\r
+            Py_DECREF(vv);\r
+            PyErr_SetString(PyExc_TypeError,\r
+                            "nb_int should return int object");\r
+            return -1;\r
+        }\r
+    }\r
+\r
+    res = -1;\r
+    v = (PyLongObject *)vv;\r
+    i = Py_SIZE(v);\r
+\r
+    switch (i) {\r
+    case -1:\r
+        res = -(sdigit)v->ob_digit[0];\r
+        break;\r
+    case 0:\r
+        res = 0;\r
+        break;\r
+    case 1:\r
+        res = v->ob_digit[0];\r
+        break;\r
+    default:\r
+        sign = 1;\r
+        x = 0;\r
+        if (i < 0) {\r
+            sign = -1;\r
+            i = -(i);\r
+        }\r
+        while (--i >= 0) {\r
+            prev = x;\r
+            x = (x << PyLong_SHIFT) + v->ob_digit[i];\r
+            if ((x >> PyLong_SHIFT) != prev) {\r
+                *overflow = sign;\r
+                goto exit;\r
+            }\r
+        }\r
+        /* Haven't lost any bits, but casting to long requires extra\r
+         * care (see comment above).\r
+         */\r
+        if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {\r
+            res = (PY_LONG_LONG)x * sign;\r
+        }\r
+        else if (sign < 0 && x == PY_ABS_LLONG_MIN) {\r
+            res = PY_LLONG_MIN;\r
+        }\r
+        else {\r
+            *overflow = sign;\r
+            /* res is already set to -1 */\r
+        }\r
+    }\r
+  exit:\r
+    if (do_decref) {\r
+        Py_DECREF(vv);\r
+    }\r
+    return res;\r
+}\r
+\r
+#undef IS_LITTLE_ENDIAN\r
+\r
+#endif /* HAVE_LONG_LONG */\r
+\r
+\r
+static int\r
+convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {\r
+    if (PyLong_Check(v)) {\r
+        *a = (PyLongObject *) v;\r
+        Py_INCREF(v);\r
+    }\r
+    else if (PyInt_Check(v)) {\r
+        *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));\r
+    }\r
+    else {\r
+        return 0;\r
+    }\r
+    if (PyLong_Check(w)) {\r
+        *b = (PyLongObject *) w;\r
+        Py_INCREF(w);\r
+    }\r
+    else if (PyInt_Check(w)) {\r
+        *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));\r
+    }\r
+    else {\r
+        Py_DECREF(*a);\r
+        return 0;\r
+    }\r
+    return 1;\r
+}\r
+\r
+#define CONVERT_BINOP(v, w, a, b)               \\r
+    do {                                        \\r
+        if (!convert_binop(v, w, a, b)) {       \\r
+            Py_INCREF(Py_NotImplemented);       \\r
+            return Py_NotImplemented;           \\r
+        }                                       \\r
+    } while(0)                                  \\r
+\r
+/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <\r
+   2**k if d is nonzero, else 0. */\r
+\r
+static const unsigned char BitLengthTable[32] = {\r
+    0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\r
+    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5\r
+};\r
+\r
+static int\r
+bits_in_digit(digit d)\r
+{\r
+    int d_bits = 0;\r
+    while (d >= 32) {\r
+        d_bits += 6;\r
+        d >>= 6;\r
+    }\r
+    d_bits += (int)BitLengthTable[d];\r
+    return d_bits;\r
+}\r
+\r
+/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required.  x[0:n]\r
+ * is modified in place, by adding y to it.  Carries are propagated as far as\r
+ * x[m-1], and the remaining carry (0 or 1) is returned.\r
+ */\r
+static digit\r
+v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)\r
+{\r
+    Py_ssize_t i;\r
+    digit carry = 0;\r
+\r
+    assert(m >= n);\r
+    for (i = 0; i < n; ++i) {\r
+        carry += x[i] + y[i];\r
+        x[i] = carry & PyLong_MASK;\r
+        carry >>= PyLong_SHIFT;\r
+        assert((carry & 1) == carry);\r
+    }\r
+    for (; carry && i < m; ++i) {\r
+        carry += x[i];\r
+        x[i] = carry & PyLong_MASK;\r
+        carry >>= PyLong_SHIFT;\r
+        assert((carry & 1) == carry);\r
+    }\r
+    return carry;\r
+}\r
+\r
+/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required.  x[0:n]\r
+ * is modified in place, by subtracting y from it.  Borrows are propagated as\r
+ * far as x[m-1], and the remaining borrow (0 or 1) is returned.\r
+ */\r
+static digit\r
+v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)\r
+{\r
+    Py_ssize_t i;\r
+    digit borrow = 0;\r
+\r
+    assert(m >= n);\r
+    for (i = 0; i < n; ++i) {\r
+        borrow = x[i] - y[i] - borrow;\r
+        x[i] = borrow & PyLong_MASK;\r
+        borrow >>= PyLong_SHIFT;\r
+        borrow &= 1;            /* keep only 1 sign bit */\r
+    }\r
+    for (; borrow && i < m; ++i) {\r
+        borrow = x[i] - borrow;\r
+        x[i] = borrow & PyLong_MASK;\r
+        borrow >>= PyLong_SHIFT;\r
+        borrow &= 1;\r
+    }\r
+    return borrow;\r
+}\r
+\r
+/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT.  Put\r
+ * result in z[0:m], and return the d bits shifted out of the top.\r
+ */\r
+static digit\r
+v_lshift(digit *z, digit *a, Py_ssize_t m, int d)\r
+{\r
+    Py_ssize_t i;\r
+    digit carry = 0;\r
+\r
+    assert(0 <= d && d < PyLong_SHIFT);\r
+    for (i=0; i < m; i++) {\r
+        twodigits acc = (twodigits)a[i] << d | carry;\r
+        z[i] = (digit)acc & PyLong_MASK;\r
+        carry = (digit)(acc >> PyLong_SHIFT);\r
+    }\r
+    return carry;\r
+}\r
+\r
+/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT.  Put\r
+ * result in z[0:m], and return the d bits shifted out of the bottom.\r
+ */\r
+static digit\r
+v_rshift(digit *z, digit *a, Py_ssize_t m, int d)\r
+{\r
+    Py_ssize_t i;\r
+    digit carry = 0;\r
+    digit mask = ((digit)1 << d) - 1U;\r
+\r
+    assert(0 <= d && d < PyLong_SHIFT);\r
+    for (i=m; i-- > 0;) {\r
+        twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];\r
+        carry = (digit)acc & mask;\r
+        z[i] = (digit)(acc >> d);\r
+    }\r
+    return carry;\r
+}\r
+\r
+/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient\r
+   in pout, and returning the remainder.  pin and pout point at the LSD.\r
+   It's OK for pin == pout on entry, which saves oodles of mallocs/frees in\r
+   _PyLong_Format, but that should be done with great care since longs are\r
+   immutable. */\r
+\r
+static digit\r
+inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)\r
+{\r
+    twodigits rem = 0;\r
+\r
+    assert(n > 0 && n <= PyLong_MASK);\r
+    pin += size;\r
+    pout += size;\r
+    while (--size >= 0) {\r
+        digit hi;\r
+        rem = (rem << PyLong_SHIFT) | *--pin;\r
+        *--pout = hi = (digit)(rem / n);\r
+        rem -= (twodigits)hi * n;\r
+    }\r
+    return (digit)rem;\r
+}\r
+\r
+/* Divide a long integer by a digit, returning both the quotient\r
+   (as function result) and the remainder (through *prem).\r
+   The sign of a is ignored; n should not be zero. */\r
+\r
+static PyLongObject *\r
+divrem1(PyLongObject *a, digit n, digit *prem)\r
+{\r
+    const Py_ssize_t size = ABS(Py_SIZE(a));\r
+    PyLongObject *z;\r
+\r
+    assert(n > 0 && n <= PyLong_MASK);\r
+    z = _PyLong_New(size);\r
+    if (z == NULL)\r
+        return NULL;\r
+    *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);\r
+    return long_normalize(z);\r
+}\r
+\r
+/* Convert a long integer to a base 10 string.  Returns a new non-shared\r
+   string.  (Return value is non-shared so that callers can modify the\r
+   returned value if necessary.) */\r
+\r
+static PyObject *\r
+long_to_decimal_string(PyObject *aa, int addL)\r
+{\r
+    PyLongObject *scratch, *a;\r
+    PyObject *str;\r
+    Py_ssize_t size, strlen, size_a, i, j;\r
+    digit *pout, *pin, rem, tenpow;\r
+    char *p;\r
+    int negative;\r
+\r
+    a = (PyLongObject *)aa;\r
+    if (a == NULL || !PyLong_Check(a)) {\r
+        PyErr_BadInternalCall();\r
+        return NULL;\r
+    }\r
+    size_a = ABS(Py_SIZE(a));\r
+    negative = Py_SIZE(a) < 0;\r
+\r
+    /* quick and dirty upper bound for the number of digits\r
+       required to express a in base _PyLong_DECIMAL_BASE:\r
+\r
+         #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))\r
+\r
+       But log2(a) < size_a * PyLong_SHIFT, and\r
+       log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT\r
+                                  > 3 * _PyLong_DECIMAL_SHIFT\r
+    */\r
+    if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "long is too large to format");\r
+        return NULL;\r
+    }\r
+    /* the expression size_a * PyLong_SHIFT is now safe from overflow */\r
+    size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);\r
+    scratch = _PyLong_New(size);\r
+    if (scratch == NULL)\r
+        return NULL;\r
+\r
+    /* convert array of base _PyLong_BASE digits in pin to an array of\r
+       base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,\r
+       Volume 2 (3rd edn), section 4.4, Method 1b). */\r
+    pin = a->ob_digit;\r
+    pout = scratch->ob_digit;\r
+    size = 0;\r
+    for (i = size_a; --i >= 0; ) {\r
+        digit hi = pin[i];\r
+        for (j = 0; j < size; j++) {\r
+            twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;\r
+            hi = (digit)(z / _PyLong_DECIMAL_BASE);\r
+            pout[j] = (digit)(z - (twodigits)hi *\r
+                              _PyLong_DECIMAL_BASE);\r
+        }\r
+        while (hi) {\r
+            pout[size++] = hi % _PyLong_DECIMAL_BASE;\r
+            hi /= _PyLong_DECIMAL_BASE;\r
+        }\r
+        /* check for keyboard interrupt */\r
+        SIGCHECK({\r
+                Py_DECREF(scratch);\r
+                return NULL;\r
+            });\r
+    }\r
+    /* pout should have at least one digit, so that the case when a = 0\r
+       works correctly */\r
+    if (size == 0)\r
+        pout[size++] = 0;\r
+\r
+    /* calculate exact length of output string, and allocate */\r
+    strlen = (addL != 0) + negative +\r
+        1 + (size - 1) * _PyLong_DECIMAL_SHIFT;\r
+    tenpow = 10;\r
+    rem = pout[size-1];\r
+    while (rem >= tenpow) {\r
+        tenpow *= 10;\r
+        strlen++;\r
+    }\r
+    str = PyString_FromStringAndSize(NULL, strlen);\r
+    if (str == NULL) {\r
+        Py_DECREF(scratch);\r
+        return NULL;\r
+    }\r
+\r
+    /* fill the string right-to-left */\r
+    p = PyString_AS_STRING(str) + strlen;\r
+    *p = '\0';\r
+    if (addL)\r
+        *--p = 'L';\r
+    /* pout[0] through pout[size-2] contribute exactly\r
+       _PyLong_DECIMAL_SHIFT digits each */\r
+    for (i=0; i < size - 1; i++) {\r
+        rem = pout[i];\r
+        for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {\r
+            *--p = '0' + rem % 10;\r
+            rem /= 10;\r
+        }\r
+    }\r
+    /* pout[size-1]: always produce at least one decimal digit */\r
+    rem = pout[i];\r
+    do {\r
+        *--p = '0' + rem % 10;\r
+        rem /= 10;\r
+    } while (rem != 0);\r
+\r
+    /* and sign */\r
+    if (negative)\r
+        *--p = '-';\r
+\r
+    /* check we've counted correctly */\r
+    assert(p == PyString_AS_STRING(str));\r
+    Py_DECREF(scratch);\r
+    return (PyObject *)str;\r
+}\r
+\r
+/* Convert the long to a string object with given base,\r
+   appending a base prefix of 0[box] if base is 2, 8 or 16.\r
+   Add a trailing "L" if addL is non-zero.\r
+   If newstyle is zero, then use the pre-2.6 behavior of octal having\r
+   a leading "0", instead of the prefix "0o" */\r
+PyAPI_FUNC(PyObject *)\r
+_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)\r
+{\r
+    register PyLongObject *a = (PyLongObject *)aa;\r
+    PyStringObject *str;\r
+    Py_ssize_t i, sz;\r
+    Py_ssize_t size_a;\r
+    char *p;\r
+    int bits;\r
+    char sign = '\0';\r
+\r
+    if (base == 10)\r
+        return long_to_decimal_string((PyObject *)a, addL);\r
+\r
+    if (a == NULL || !PyLong_Check(a)) {\r
+        PyErr_BadInternalCall();\r
+        return NULL;\r
+    }\r
+    assert(base >= 2 && base <= 36);\r
+    size_a = ABS(Py_SIZE(a));\r
+\r
+    /* Compute a rough upper bound for the length of the string */\r
+    i = base;\r
+    bits = 0;\r
+    while (i > 1) {\r
+        ++bits;\r
+        i >>= 1;\r
+    }\r
+    i = 5 + (addL ? 1 : 0);\r
+    /* ensure we don't get signed overflow in sz calculation */\r
+    if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "long is too large to format");\r
+        return NULL;\r
+    }\r
+    sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;\r
+    assert(sz >= 0);\r
+    str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);\r
+    if (str == NULL)\r
+        return NULL;\r
+    p = PyString_AS_STRING(str) + sz;\r
+    *p = '\0';\r
+    if (addL)\r
+        *--p = 'L';\r
+    if (a->ob_size < 0)\r
+        sign = '-';\r
+\r
+    if (a->ob_size == 0) {\r
+        *--p = '0';\r
+    }\r
+    else if ((base & (base - 1)) == 0) {\r
+        /* JRH: special case for power-of-2 bases */\r
+        twodigits accum = 0;\r
+        int accumbits = 0;              /* # of bits in accum */\r
+        int basebits = 1;               /* # of bits in base-1 */\r
+        i = base;\r
+        while ((i >>= 1) > 1)\r
+            ++basebits;\r
+\r
+        for (i = 0; i < size_a; ++i) {\r
+            accum |= (twodigits)a->ob_digit[i] << accumbits;\r
+            accumbits += PyLong_SHIFT;\r
+            assert(accumbits >= basebits);\r
+            do {\r
+                char cdigit = (char)(accum & (base - 1));\r
+                cdigit += (cdigit < 10) ? '0' : 'a'-10;\r
+                assert(p > PyString_AS_STRING(str));\r
+                *--p = cdigit;\r
+                accumbits -= basebits;\r
+                accum >>= basebits;\r
+            } while (i < size_a-1 ? accumbits >= basebits : accum > 0);\r
+        }\r
+    }\r
+    else {\r
+        /* Not 0, and base not a power of 2.  Divide repeatedly by\r
+           base, but for speed use the highest power of base that\r
+           fits in a digit. */\r
+        Py_ssize_t size = size_a;\r
+        digit *pin = a->ob_digit;\r
+        PyLongObject *scratch;\r
+        /* powbasw <- largest power of base that fits in a digit. */\r
+        digit powbase = base;  /* powbase == base ** power */\r
+        int power = 1;\r
+        for (;;) {\r
+            twodigits newpow = powbase * (twodigits)base;\r
+            if (newpow >> PyLong_SHIFT)\r
+                /* doesn't fit in a digit */\r
+                break;\r
+            powbase = (digit)newpow;\r
+            ++power;\r
+        }\r
+\r
+        /* Get a scratch area for repeated division. */\r
+        scratch = _PyLong_New(size);\r
+        if (scratch == NULL) {\r
+            Py_DECREF(str);\r
+            return NULL;\r
+        }\r
+\r
+        /* Repeatedly divide by powbase. */\r
+        do {\r
+            int ntostore = power;\r
+            digit rem = inplace_divrem1(scratch->ob_digit,\r
+                                        pin, size, powbase);\r
+            pin = scratch->ob_digit; /* no need to use a again */\r
+            if (pin[size - 1] == 0)\r
+                --size;\r
+            SIGCHECK({\r
+                    Py_DECREF(scratch);\r
+                    Py_DECREF(str);\r
+                    return NULL;\r
+                });\r
+\r
+            /* Break rem into digits. */\r
+            assert(ntostore > 0);\r
+            do {\r
+                digit nextrem = (digit)(rem / base);\r
+                char c = (char)(rem - nextrem * base);\r
+                assert(p > PyString_AS_STRING(str));\r
+                c += (c < 10) ? '0' : 'a'-10;\r
+                *--p = c;\r
+                rem = nextrem;\r
+                --ntostore;\r
+                /* Termination is a bit delicate:  must not\r
+                   store leading zeroes, so must get out if\r
+                   remaining quotient and rem are both 0. */\r
+            } while (ntostore && (size || rem));\r
+        } while (size != 0);\r
+        Py_DECREF(scratch);\r
+    }\r
+\r
+    if (base == 2) {\r
+        *--p = 'b';\r
+        *--p = '0';\r
+    }\r
+    else if (base == 8) {\r
+        if (newstyle) {\r
+            *--p = 'o';\r
+            *--p = '0';\r
+        }\r
+        else\r
+            if (size_a != 0)\r
+                *--p = '0';\r
+    }\r
+    else if (base == 16) {\r
+        *--p = 'x';\r
+        *--p = '0';\r
+    }\r
+    else if (base != 10) {\r
+        *--p = '#';\r
+        *--p = '0' + base%10;\r
+        if (base > 10)\r
+            *--p = '0' + base/10;\r
+    }\r
+    if (sign)\r
+        *--p = sign;\r
+    if (p != PyString_AS_STRING(str)) {\r
+        char *q = PyString_AS_STRING(str);\r
+        assert(p > q);\r
+        do {\r
+        } while ((*q++ = *p++) != '\0');\r
+        q--;\r
+        _PyString_Resize((PyObject **)&str,\r
+                         (Py_ssize_t) (q - PyString_AS_STRING(str)));\r
+    }\r
+    return (PyObject *)str;\r
+}\r
+\r
+/* Table of digit values for 8-bit string -> integer conversion.\r
+ * '0' maps to 0, ..., '9' maps to 9.\r
+ * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.\r
+ * All other indices map to 37.\r
+ * Note that when converting a base B string, a char c is a legitimate\r
+ * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.\r
+ */\r
+int _PyLong_DigitValue[256] = {\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  37, 37, 37, 37, 37, 37,\r
+    37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\r
+    25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,\r
+    37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\r
+    25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
+};\r
+\r
+/* *str points to the first digit in a string of base `base` digits.  base\r
+ * is a power of 2 (2, 4, 8, 16, or 32).  *str is set to point to the first\r
+ * non-digit (which may be *str!).  A normalized long is returned.\r
+ * The point to this routine is that it takes time linear in the number of\r
+ * string characters.\r
+ */\r
+static PyLongObject *\r
+long_from_binary_base(char **str, int base)\r
+{\r
+    char *p = *str;\r
+    char *start = p;\r
+    int bits_per_char;\r
+    Py_ssize_t n;\r
+    PyLongObject *z;\r
+    twodigits accum;\r
+    int bits_in_accum;\r
+    digit *pdigit;\r
+\r
+    assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);\r
+    n = base;\r
+    for (bits_per_char = -1; n; ++bits_per_char)\r
+        n >>= 1;\r
+    /* n <- total # of bits needed, while setting p to end-of-string */\r
+    while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)\r
+        ++p;\r
+    *str = p;\r
+    /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */\r
+    n = (p - start) * bits_per_char + PyLong_SHIFT - 1;\r
+    if (n / bits_per_char < p - start) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "long string too large to convert");\r
+        return NULL;\r
+    }\r
+    n = n / PyLong_SHIFT;\r
+    z = _PyLong_New(n);\r
+    if (z == NULL)\r
+        return NULL;\r
+    /* Read string from right, and fill in long from left; i.e.,\r
+     * from least to most significant in both.\r
+     */\r
+    accum = 0;\r
+    bits_in_accum = 0;\r
+    pdigit = z->ob_digit;\r
+    while (--p >= start) {\r
+        int k = _PyLong_DigitValue[Py_CHARMASK(*p)];\r
+        assert(k >= 0 && k < base);\r
+        accum |= (twodigits)k << bits_in_accum;\r
+        bits_in_accum += bits_per_char;\r
+        if (bits_in_accum >= PyLong_SHIFT) {\r
+            *pdigit++ = (digit)(accum & PyLong_MASK);\r
+            assert(pdigit - z->ob_digit <= n);\r
+            accum >>= PyLong_SHIFT;\r
+            bits_in_accum -= PyLong_SHIFT;\r
+            assert(bits_in_accum < PyLong_SHIFT);\r
+        }\r
+    }\r
+    if (bits_in_accum) {\r
+        assert(bits_in_accum <= PyLong_SHIFT);\r
+        *pdigit++ = (digit)accum;\r
+        assert(pdigit - z->ob_digit <= n);\r
+    }\r
+    while (pdigit - z->ob_digit < n)\r
+        *pdigit++ = 0;\r
+    return long_normalize(z);\r
+}\r
+\r
+PyObject *\r
+PyLong_FromString(char *str, char **pend, int base)\r
+{\r
+    int sign = 1;\r
+    char *start, *orig_str = str;\r
+    PyLongObject *z;\r
+    PyObject *strobj, *strrepr;\r
+    Py_ssize_t slen;\r
+\r
+    if ((base != 0 && base < 2) || base > 36) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "long() arg 2 must be >= 2 and <= 36");\r
+        return NULL;\r
+    }\r
+    while (*str != '\0' && isspace(Py_CHARMASK(*str)))\r
+        str++;\r
+    if (*str == '+')\r
+        ++str;\r
+    else if (*str == '-') {\r
+        ++str;\r
+        sign = -1;\r
+    }\r
+    while (*str != '\0' && isspace(Py_CHARMASK(*str)))\r
+        str++;\r
+    if (base == 0) {\r
+        /* No base given.  Deduce the base from the contents\r
+           of the string */\r
+        if (str[0] != '0')\r
+            base = 10;\r
+        else if (str[1] == 'x' || str[1] == 'X')\r
+            base = 16;\r
+        else if (str[1] == 'o' || str[1] == 'O')\r
+            base = 8;\r
+        else if (str[1] == 'b' || str[1] == 'B')\r
+            base = 2;\r
+        else\r
+            /* "old" (C-style) octal literal, still valid in\r
+               2.x, although illegal in 3.x */\r
+            base = 8;\r
+    }\r
+    /* Whether or not we were deducing the base, skip leading chars\r
+       as needed */\r
+    if (str[0] == '0' &&\r
+        ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||\r
+         (base == 8  && (str[1] == 'o' || str[1] == 'O')) ||\r
+         (base == 2  && (str[1] == 'b' || str[1] == 'B'))))\r
+        str += 2;\r
+\r
+    start = str;\r
+    if ((base & (base - 1)) == 0)\r
+        z = long_from_binary_base(&str, base);\r
+    else {\r
+/***\r
+Binary bases can be converted in time linear in the number of digits, because\r
+Python's representation base is binary.  Other bases (including decimal!) use\r
+the simple quadratic-time algorithm below, complicated by some speed tricks.\r
+\r
+First some math:  the largest integer that can be expressed in N base-B digits\r
+is B**N-1.  Consequently, if we have an N-digit input in base B, the worst-\r
+case number of Python digits needed to hold it is the smallest integer n s.t.\r
+\r
+    PyLong_BASE**n-1 >= B**N-1  [or, adding 1 to both sides]\r
+    PyLong_BASE**n >= B**N      [taking logs to base PyLong_BASE]\r
+    n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)\r
+\r
+The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so\r
+we can compute this quickly.  A Python long with that much space is reserved\r
+near the start, and the result is computed into it.\r
+\r
+The input string is actually treated as being in base base**i (i.e., i digits\r
+are processed at a time), where two more static arrays hold:\r
+\r
+    convwidth_base[base] = the largest integer i such that\r
+                           base**i <= PyLong_BASE\r
+    convmultmax_base[base] = base ** convwidth_base[base]\r
+\r
+The first of these is the largest i such that i consecutive input digits\r
+must fit in a single Python digit.  The second is effectively the input\r
+base we're really using.\r
+\r
+Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base\r
+convmultmax_base[base], the result is "simply"\r
+\r
+   (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1\r
+\r
+where B = convmultmax_base[base].\r
+\r
+Error analysis:  as above, the number of Python digits `n` needed is worst-\r
+case\r
+\r
+    n >= N * log(B)/log(PyLong_BASE)\r
+\r
+where `N` is the number of input digits in base `B`.  This is computed via\r
+\r
+    size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;\r
+\r
+below.  Two numeric concerns are how much space this can waste, and whether\r
+the computed result can be too small.  To be concrete, assume PyLong_BASE =\r
+2**15, which is the default (and it's unlikely anyone changes that).\r
+\r
+Waste isn't a problem: provided the first input digit isn't 0, the difference\r
+between the worst-case input with N digits and the smallest input with N\r
+digits is about a factor of B, but B is small compared to PyLong_BASE so at\r
+most one allocated Python digit can remain unused on that count.  If\r
+N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating\r
+that and adding 1 returns a result 1 larger than necessary.  However, that\r
+can't happen: whenever B is a power of 2, long_from_binary_base() is called\r
+instead, and it's impossible for B**i to be an integer power of 2**15 when B\r
+is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be\r
+an exact integer when B is not a power of 2, since B**i has a prime factor\r
+other than 2 in that case, but (2**15)**j's only prime factor is 2).\r
+\r
+The computed result can be too small if the true value of\r
+N*log(B)/log(PyLong_BASE) is a little bit larger than an exact integer, but\r
+due to roundoff errors (in computing log(B), log(PyLong_BASE), their quotient,\r
+and/or multiplying that by N) yields a numeric result a little less than that\r
+integer.  Unfortunately, "how close can a transcendental function get to an\r
+integer over some range?"  questions are generally theoretically intractable.\r
+Computer analysis via continued fractions is practical: expand\r
+log(B)/log(PyLong_BASE) via continued fractions, giving a sequence i/j of "the\r
+best" rational approximations.  Then j*log(B)/log(PyLong_BASE) is\r
+approximately equal to (the integer) i.  This shows that we can get very close\r
+to being in trouble, but very rarely.  For example, 76573 is a denominator in\r
+one of the continued-fraction approximations to log(10)/log(2**15), and\r
+indeed:\r
+\r
+    >>> log(10)/log(2**15)*76573\r
+    16958.000000654003\r
+\r
+is very close to an integer.  If we were working with IEEE single-precision,\r
+rounding errors could kill us.  Finding worst cases in IEEE double-precision\r
+requires better-than-double-precision log() functions, and Tim didn't bother.\r
+Instead the code checks to see whether the allocated space is enough as each\r
+new Python digit is added, and copies the whole thing to a larger long if not.\r
+This should happen extremely rarely, and in fact I don't have a test case\r
+that triggers it(!).  Instead the code was tested by artificially allocating\r
+just 1 digit at the start, so that the copying code was exercised for every\r
+digit beyond the first.\r
+***/\r
+        register twodigits c;           /* current input character */\r
+        Py_ssize_t size_z;\r
+        int i;\r
+        int convwidth;\r
+        twodigits convmultmax, convmult;\r
+        digit *pz, *pzstop;\r
+        char* scan;\r
+\r
+        static double log_base_PyLong_BASE[37] = {0.0e0,};\r
+        static int convwidth_base[37] = {0,};\r
+        static twodigits convmultmax_base[37] = {0,};\r
+\r
+        if (log_base_PyLong_BASE[base] == 0.0) {\r
+            twodigits convmax = base;\r
+            int i = 1;\r
+\r
+            log_base_PyLong_BASE[base] = (log((double)base) /\r
+                                          log((double)PyLong_BASE));\r
+            for (;;) {\r
+                twodigits next = convmax * base;\r
+                if (next > PyLong_BASE)\r
+                    break;\r
+                convmax = next;\r
+                ++i;\r
+            }\r
+            convmultmax_base[base] = convmax;\r
+            assert(i > 0);\r
+            convwidth_base[base] = i;\r
+        }\r
+\r
+        /* Find length of the string of numeric characters. */\r
+        scan = str;\r
+        while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)\r
+            ++scan;\r
+\r
+        /* Create a long object that can contain the largest possible\r
+         * integer with this base and length.  Note that there's no\r
+         * need to initialize z->ob_digit -- no slot is read up before\r
+         * being stored into.\r
+         */\r
+        size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;\r
+        /* Uncomment next line to test exceedingly rare copy code */\r
+        /* size_z = 1; */\r
+        assert(size_z > 0);\r
+        z = _PyLong_New(size_z);\r
+        if (z == NULL)\r
+            return NULL;\r
+        Py_SIZE(z) = 0;\r
+\r
+        /* `convwidth` consecutive input digits are treated as a single\r
+         * digit in base `convmultmax`.\r
+         */\r
+        convwidth = convwidth_base[base];\r
+        convmultmax = convmultmax_base[base];\r
+\r
+        /* Work ;-) */\r
+        while (str < scan) {\r
+            /* grab up to convwidth digits from the input string */\r
+            c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];\r
+            for (i = 1; i < convwidth && str != scan; ++i, ++str) {\r
+                c = (twodigits)(c *  base +\r
+                                _PyLong_DigitValue[Py_CHARMASK(*str)]);\r
+                assert(c < PyLong_BASE);\r
+            }\r
+\r
+            convmult = convmultmax;\r
+            /* Calculate the shift only if we couldn't get\r
+             * convwidth digits.\r
+             */\r
+            if (i != convwidth) {\r
+                convmult = base;\r
+                for ( ; i > 1; --i)\r
+                    convmult *= base;\r
+            }\r
+\r
+            /* Multiply z by convmult, and add c. */\r
+            pz = z->ob_digit;\r
+            pzstop = pz + Py_SIZE(z);\r
+            for (; pz < pzstop; ++pz) {\r
+                c += (twodigits)*pz * convmult;\r
+                *pz = (digit)(c & PyLong_MASK);\r
+                c >>= PyLong_SHIFT;\r
+            }\r
+            /* carry off the current end? */\r
+            if (c) {\r
+                assert(c < PyLong_BASE);\r
+                if (Py_SIZE(z) < size_z) {\r
+                    *pz = (digit)c;\r
+                    ++Py_SIZE(z);\r
+                }\r
+                else {\r
+                    PyLongObject *tmp;\r
+                    /* Extremely rare.  Get more space. */\r
+                    assert(Py_SIZE(z) == size_z);\r
+                    tmp = _PyLong_New(size_z + 1);\r
+                    if (tmp == NULL) {\r
+                        Py_DECREF(z);\r
+                        return NULL;\r
+                    }\r
+                    memcpy(tmp->ob_digit,\r
+                           z->ob_digit,\r
+                           sizeof(digit) * size_z);\r
+                    Py_DECREF(z);\r
+                    z = tmp;\r
+                    z->ob_digit[size_z] = (digit)c;\r
+                    ++size_z;\r
+                }\r
+            }\r
+        }\r
+    }\r
+    if (z == NULL)\r
+        return NULL;\r
+    if (str == start)\r
+        goto onError;\r
+    if (sign < 0)\r
+        Py_SIZE(z) = -(Py_SIZE(z));\r
+    if (*str == 'L' || *str == 'l')\r
+        str++;\r
+    while (*str && isspace(Py_CHARMASK(*str)))\r
+        str++;\r
+    if (*str != '\0')\r
+        goto onError;\r
+    if (pend)\r
+        *pend = str;\r
+    return (PyObject *) z;\r
+\r
+  onError:\r
+    Py_XDECREF(z);\r
+    slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;\r
+    strobj = PyString_FromStringAndSize(orig_str, slen);\r
+    if (strobj == NULL)\r
+        return NULL;\r
+    strrepr = PyObject_Repr(strobj);\r
+    Py_DECREF(strobj);\r
+    if (strrepr == NULL)\r
+        return NULL;\r
+    PyErr_Format(PyExc_ValueError,\r
+                 "invalid literal for long() with base %d: %s",\r
+                 base, PyString_AS_STRING(strrepr));\r
+    Py_DECREF(strrepr);\r
+    return NULL;\r
+}\r
+\r
+#ifdef Py_USING_UNICODE\r
+PyObject *\r
+PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)\r
+{\r
+    PyObject *result;\r
+    char *buffer = (char *)PyMem_MALLOC(length+1);\r
+\r
+    if (buffer == NULL)\r
+        return NULL;\r
+\r
+    if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {\r
+        PyMem_FREE(buffer);\r
+        return NULL;\r
+    }\r
+    result = PyLong_FromString(buffer, NULL, base);\r
+    PyMem_FREE(buffer);\r
+    return result;\r
+}\r
+#endif\r
+\r
+/* forward */\r
+static PyLongObject *x_divrem\r
+    (PyLongObject *, PyLongObject *, PyLongObject **);\r
+static PyObject *long_long(PyObject *v);\r
+\r
+/* Long division with remainder, top-level routine */\r
+\r
+static int\r
+long_divrem(PyLongObject *a, PyLongObject *b,\r
+            PyLongObject **pdiv, PyLongObject **prem)\r
+{\r
+    Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));\r
+    PyLongObject *z;\r
+\r
+    if (size_b == 0) {\r
+        PyErr_SetString(PyExc_ZeroDivisionError,\r
+                        "long division or modulo by zero");\r
+        return -1;\r
+    }\r
+    if (size_a < size_b ||\r
+        (size_a == size_b &&\r
+         a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {\r
+        /* |a| < |b|. */\r
+        *pdiv = _PyLong_New(0);\r
+        if (*pdiv == NULL)\r
+            return -1;\r
+        Py_INCREF(a);\r
+        *prem = (PyLongObject *) a;\r
+        return 0;\r
+    }\r
+    if (size_b == 1) {\r
+        digit rem = 0;\r
+        z = divrem1(a, b->ob_digit[0], &rem);\r
+        if (z == NULL)\r
+            return -1;\r
+        *prem = (PyLongObject *) PyLong_FromLong((long)rem);\r
+        if (*prem == NULL) {\r
+            Py_DECREF(z);\r
+            return -1;\r
+        }\r
+    }\r
+    else {\r
+        z = x_divrem(a, b, prem);\r
+        if (z == NULL)\r
+            return -1;\r
+    }\r
+    /* Set the signs.\r
+       The quotient z has the sign of a*b;\r
+       the remainder r has the sign of a,\r
+       so a = b*z + r. */\r
+    if ((a->ob_size < 0) != (b->ob_size < 0))\r
+        z->ob_size = -(z->ob_size);\r
+    if (a->ob_size < 0 && (*prem)->ob_size != 0)\r
+        (*prem)->ob_size = -((*prem)->ob_size);\r
+    *pdiv = z;\r
+    return 0;\r
+}\r
+\r
+/* Unsigned long division with remainder -- the algorithm.  The arguments v1\r
+   and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */\r
+\r
+static PyLongObject *\r
+x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)\r
+{\r
+    PyLongObject *v, *w, *a;\r
+    Py_ssize_t i, k, size_v, size_w;\r
+    int d;\r
+    digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;\r
+    twodigits vv;\r
+    sdigit zhi;\r
+    stwodigits z;\r
+\r
+    /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd\r
+       edn.), section 4.3.1, Algorithm D], except that we don't explicitly\r
+       handle the special case when the initial estimate q for a quotient\r
+       digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and\r
+       that won't overflow a digit. */\r
+\r
+    /* allocate space; w will also be used to hold the final remainder */\r
+    size_v = ABS(Py_SIZE(v1));\r
+    size_w = ABS(Py_SIZE(w1));\r
+    assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */\r
+    v = _PyLong_New(size_v+1);\r
+    if (v == NULL) {\r
+        *prem = NULL;\r
+        return NULL;\r
+    }\r
+    w = _PyLong_New(size_w);\r
+    if (w == NULL) {\r
+        Py_DECREF(v);\r
+        *prem = NULL;\r
+        return NULL;\r
+    }\r
+\r
+    /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.\r
+       shift v1 left by the same amount.  Results go into w and v. */\r
+    d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);\r
+    carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);\r
+    assert(carry == 0);\r
+    carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);\r
+    if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {\r
+        v->ob_digit[size_v] = carry;\r
+        size_v++;\r
+    }\r
+\r
+    /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has\r
+       at most (and usually exactly) k = size_v - size_w digits. */\r
+    k = size_v - size_w;\r
+    assert(k >= 0);\r
+    a = _PyLong_New(k);\r
+    if (a == NULL) {\r
+        Py_DECREF(w);\r
+        Py_DECREF(v);\r
+        *prem = NULL;\r
+        return NULL;\r
+    }\r
+    v0 = v->ob_digit;\r
+    w0 = w->ob_digit;\r
+    wm1 = w0[size_w-1];\r
+    wm2 = w0[size_w-2];\r
+    for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {\r
+        /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving\r
+           single-digit quotient q, remainder in vk[0:size_w]. */\r
+\r
+        SIGCHECK({\r
+                Py_DECREF(a);\r
+                Py_DECREF(w);\r
+                Py_DECREF(v);\r
+                *prem = NULL;\r
+                return NULL;\r
+            });\r
+\r
+        /* estimate quotient digit q; may overestimate by 1 (rare) */\r
+        vtop = vk[size_w];\r
+        assert(vtop <= wm1);\r
+        vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];\r
+        q = (digit)(vv / wm1);\r
+        r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */\r
+        while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)\r
+                                     | vk[size_w-2])) {\r
+            --q;\r
+            r += wm1;\r
+            if (r >= PyLong_BASE)\r
+                break;\r
+        }\r
+        assert(q <= PyLong_BASE);\r
+\r
+        /* subtract q*w0[0:size_w] from vk[0:size_w+1] */\r
+        zhi = 0;\r
+        for (i = 0; i < size_w; ++i) {\r
+            /* invariants: -PyLong_BASE <= -q <= zhi <= 0;\r
+               -PyLong_BASE * q <= z < PyLong_BASE */\r
+            z = (sdigit)vk[i] + zhi -\r
+                (stwodigits)q * (stwodigits)w0[i];\r
+            vk[i] = (digit)z & PyLong_MASK;\r
+            zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,\r
+                                                    z, PyLong_SHIFT);\r
+        }\r
+\r
+        /* add w back if q was too large (this branch taken rarely) */\r
+        assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);\r
+        if ((sdigit)vtop + zhi < 0) {\r
+            carry = 0;\r
+            for (i = 0; i < size_w; ++i) {\r
+                carry += vk[i] + w0[i];\r
+                vk[i] = carry & PyLong_MASK;\r
+                carry >>= PyLong_SHIFT;\r
+            }\r
+            --q;\r
+        }\r
+\r
+        /* store quotient digit */\r
+        assert(q < PyLong_BASE);\r
+        *--ak = q;\r
+    }\r
+\r
+    /* unshift remainder; we reuse w to store the result */\r
+    carry = v_rshift(w0, v0, size_w, d);\r
+    assert(carry==0);\r
+    Py_DECREF(v);\r
+\r
+    *prem = long_normalize(w);\r
+    return long_normalize(a);\r
+}\r
+\r
+/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=\r
+   abs(x) < 1.0 and e >= 0; return x and put e in *e.  Here x is\r
+   rounded to DBL_MANT_DIG significant bits using round-half-to-even.\r
+   If a == 0, return 0.0 and set *e = 0.  If the resulting exponent\r
+   e is larger than PY_SSIZE_T_MAX, raise OverflowError and return\r
+   -1.0. */\r
+\r
+/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */\r
+#if DBL_MANT_DIG == 53\r
+#define EXP2_DBL_MANT_DIG 9007199254740992.0\r
+#else\r
+#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))\r
+#endif\r
+\r
+double\r
+_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)\r
+{\r
+    Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;\r
+    /* See below for why x_digits is always large enough. */\r
+    digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];\r
+    double dx;\r
+    /* Correction term for round-half-to-even rounding.  For a digit x,\r
+       "x + half_even_correction[x & 7]" gives x rounded to the nearest\r
+       multiple of 4, rounding ties to a multiple of 8. */\r
+    static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};\r
+\r
+    a_size = ABS(Py_SIZE(a));\r
+    if (a_size == 0) {\r
+        /* Special case for 0: significand 0.0, exponent 0. */\r
+        *e = 0;\r
+        return 0.0;\r
+    }\r
+    a_bits = bits_in_digit(a->ob_digit[a_size-1]);\r
+    /* The following is an overflow-free version of the check\r
+       "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */\r
+    if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&\r
+        (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||\r
+         a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))\r
+        goto overflow;\r
+    a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;\r
+\r
+    /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]\r
+       (shifting left if a_bits <= DBL_MANT_DIG + 2).\r
+\r
+       Number of digits needed for result: write // for floor division.\r
+       Then if shifting left, we end up using\r
+\r
+         1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT\r
+\r
+       digits.  If shifting right, we use\r
+\r
+         a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT\r
+\r
+       digits.  Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with\r
+       the inequalities\r
+\r
+         m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT\r
+         m // PyLong_SHIFT - n // PyLong_SHIFT <=\r
+                                          1 + (m - n - 1) // PyLong_SHIFT,\r
+\r
+       valid for any integers m and n, we find that x_size satisfies\r
+\r
+         x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT\r
+\r
+       in both cases.\r
+    */\r
+    if (a_bits <= DBL_MANT_DIG + 2) {\r
+        shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;\r
+        shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;\r
+        x_size = 0;\r
+        while (x_size < shift_digits)\r
+            x_digits[x_size++] = 0;\r
+        rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,\r
+                       (int)shift_bits);\r
+        x_size += a_size;\r
+        x_digits[x_size++] = rem;\r
+    }\r
+    else {\r
+        shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;\r
+        shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;\r
+        rem = v_rshift(x_digits, a->ob_digit + shift_digits,\r
+                       a_size - shift_digits, (int)shift_bits);\r
+        x_size = a_size - shift_digits;\r
+        /* For correct rounding below, we need the least significant\r
+           bit of x to be 'sticky' for this shift: if any of the bits\r
+           shifted out was nonzero, we set the least significant bit\r
+           of x. */\r
+        if (rem)\r
+            x_digits[0] |= 1;\r
+        else\r
+            while (shift_digits > 0)\r
+                if (a->ob_digit[--shift_digits]) {\r
+                    x_digits[0] |= 1;\r
+                    break;\r
+                }\r
+    }\r
+    assert(1 <= x_size &&\r
+           x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));\r
+\r
+    /* Round, and convert to double. */\r
+    x_digits[0] += half_even_correction[x_digits[0] & 7];\r
+    dx = x_digits[--x_size];\r
+    while (x_size > 0)\r
+        dx = dx * PyLong_BASE + x_digits[--x_size];\r
+\r
+    /* Rescale;  make correction if result is 1.0. */\r
+    dx /= 4.0 * EXP2_DBL_MANT_DIG;\r
+    if (dx == 1.0) {\r
+        if (a_bits == PY_SSIZE_T_MAX)\r
+            goto overflow;\r
+        dx = 0.5;\r
+        a_bits += 1;\r
+    }\r
+\r
+    *e = a_bits;\r
+    return Py_SIZE(a) < 0 ? -dx : dx;\r
+\r
+  overflow:\r
+    /* exponent > PY_SSIZE_T_MAX */\r
+    PyErr_SetString(PyExc_OverflowError,\r
+                    "huge integer: number of bits overflows a Py_ssize_t");\r
+    *e = 0;\r
+    return -1.0;\r
+}\r
+\r
+/* Get a C double from a long int object.  Rounds to the nearest double,\r
+   using the round-half-to-even rule in the case of a tie. */\r
+\r
+double\r
+PyLong_AsDouble(PyObject *v)\r
+{\r
+    Py_ssize_t exponent;\r
+    double x;\r
+\r
+    if (v == NULL || !PyLong_Check(v)) {\r
+        PyErr_BadInternalCall();\r
+        return -1.0;\r
+    }\r
+    x = _PyLong_Frexp((PyLongObject *)v, &exponent);\r
+    if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {\r
+        PyErr_SetString(PyExc_OverflowError,\r
+                        "long int too large to convert to float");\r
+        return -1.0;\r
+    }\r
+    return ldexp(x, (int)exponent);\r
+}\r
+\r
+/* Methods */\r
+\r
+static void\r
+long_dealloc(PyObject *v)\r
+{\r
+    Py_TYPE(v)->tp_free(v);\r
+}\r
+\r
+static PyObject *\r
+long_repr(PyObject *v)\r
+{\r
+    return _PyLong_Format(v, 10, 1, 0);\r
+}\r
+\r
+static PyObject *\r
+long_str(PyObject *v)\r
+{\r
+    return _PyLong_Format(v, 10, 0, 0);\r
+}\r
+\r
+static int\r
+long_compare(PyLongObject *a, PyLongObject *b)\r
+{\r
+    Py_ssize_t sign;\r
+\r
+    if (Py_SIZE(a) != Py_SIZE(b)) {\r
+        sign = Py_SIZE(a) - Py_SIZE(b);\r
+    }\r
+    else {\r
+        Py_ssize_t i = ABS(Py_SIZE(a));\r
+        while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])\r
+            ;\r
+        if (i < 0)\r
+            sign = 0;\r
+        else {\r
+            sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];\r
+            if (Py_SIZE(a) < 0)\r
+                sign = -sign;\r
+        }\r
+    }\r
+    return sign < 0 ? -1 : sign > 0 ? 1 : 0;\r
+}\r
+\r
+static long\r
+long_hash(PyLongObject *v)\r
+{\r
+    unsigned long x;\r
+    Py_ssize_t i;\r
+    int sign;\r
+\r
+    /* This is designed so that Python ints and longs with the\r
+       same value hash to the same value, otherwise comparisons\r
+       of mapping keys will turn out weird */\r
+    i = v->ob_size;\r
+    sign = 1;\r
+    x = 0;\r
+    if (i < 0) {\r
+        sign = -1;\r
+        i = -(i);\r
+    }\r
+    /* The following loop produces a C unsigned long x such that x is\r
+       congruent to the absolute value of v modulo ULONG_MAX.  The\r
+       resulting x is nonzero if and only if v is. */\r
+    while (--i >= 0) {\r
+        /* Force a native long #-bits (32 or 64) circular shift */\r
+        x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);\r
+        x += v->ob_digit[i];\r
+        /* If the addition above overflowed we compensate by\r
+           incrementing.  This preserves the value modulo\r
+           ULONG_MAX. */\r
+        if (x < v->ob_digit[i])\r
+            x++;\r
+    }\r
+    x = x * sign;\r
+    if (x == (unsigned long)-1)\r
+        x = (unsigned long)-2;\r
+    return (long)x;\r
+}\r
+\r
+\r
+/* Add the absolute values of two long integers. */\r
+\r
+static PyLongObject *\r
+x_add(PyLongObject *a, PyLongObject *b)\r
+{\r
+    Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));\r
+    PyLongObject *z;\r
+    Py_ssize_t i;\r
+    digit carry = 0;\r
+\r
+    /* Ensure a is the larger of the two: */\r
+    if (size_a < size_b) {\r
+        { PyLongObject *temp = a; a = b; b = temp; }\r
+        { Py_ssize_t size_temp = size_a;\r
+            size_a = size_b;\r
+            size_b = size_temp; }\r
+    }\r
+    z = _PyLong_New(size_a+1);\r
+    if (z == NULL)\r
+        return NULL;\r
+    for (i = 0; i < size_b; ++i) {\r
+        carry += a->ob_digit[i] + b->ob_digit[i];\r
+        z->ob_digit[i] = carry & PyLong_MASK;\r
+        carry >>= PyLong_SHIFT;\r
+    }\r
+    for (; i < size_a; ++i) {\r
+        carry += a->ob_digit[i];\r
+        z->ob_digit[i] = carry & PyLong_MASK;\r
+        carry >>= PyLong_SHIFT;\r
+    }\r
+    z->ob_digit[i] = carry;\r
+    return long_normalize(z);\r
+}\r
+\r
+/* Subtract the absolute values of two integers. */\r
+\r
+static PyLongObject *\r
+x_sub(PyLongObject *a, PyLongObject *b)\r
+{\r
+    Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));\r
+    PyLongObject *z;\r
+    Py_ssize_t i;\r
+    int sign = 1;\r
+    digit borrow = 0;\r
+\r
+    /* Ensure a is the larger of the two: */\r
+    if (size_a < size_b) {\r
+        sign = -1;\r
+        { PyLongObject *temp = a; a = b; b = temp; }\r
+        { Py_ssize_t size_temp = size_a;\r
+            size_a = size_b;\r
+            size_b = size_temp; }\r
+    }\r
+    else if (size_a == size_b) {\r
+        /* Find highest digit where a and b differ: */\r
+        i = size_a;\r
+        while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])\r
+            ;\r
+        if (i < 0)\r
+            return _PyLong_New(0);\r
+        if (a->ob_digit[i] < b->ob_digit[i]) {\r
+            sign = -1;\r
+            { PyLongObject *temp = a; a = b; b = temp; }\r
+        }\r
+        size_a = size_b = i+1;\r
+    }\r
+    z = _PyLong_New(size_a);\r
+    if (z == NULL)\r
+        return NULL;\r
+    for (i = 0; i < size_b; ++i) {\r
+        /* The following assumes unsigned arithmetic\r
+           works module 2**N for some N>PyLong_SHIFT. */\r
+        borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;\r
+        z->ob_digit[i] = borrow & PyLong_MASK;\r
+        borrow >>= PyLong_SHIFT;\r
+        borrow &= 1; /* Keep only one sign bit */\r
+    }\r
+    for (; i < size_a; ++i) {\r
+        borrow = a->ob_digit[i] - borrow;\r
+        z->ob_digit[i] = borrow & PyLong_MASK;\r
+        borrow >>= PyLong_SHIFT;\r
+        borrow &= 1; /* Keep only one sign bit */\r
+    }\r
+    assert(borrow == 0);\r
+    if (sign < 0)\r
+        z->ob_size = -(z->ob_size);\r
+    return long_normalize(z);\r
+}\r
+\r
+static PyObject *\r
+long_add(PyLongObject *v, PyLongObject *w)\r
+{\r
+    PyLongObject *a, *b, *z;\r
+\r
+    CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);\r
+\r
+    if (a->ob_size < 0) {\r
+        if (b->ob_size < 0) {\r
+            z = x_add(a, b);\r
+            if (z != NULL && z->ob_size != 0)\r
+                z->ob_size = -(z->ob_size);\r
+        }\r
+        else\r
+            z = x_sub(b, a);\r
+    }\r
+    else {\r
+        if (b->ob_size < 0)\r
+            z = x_sub(a, b);\r
+        else\r
+            z = x_add(a, b);\r
+    }\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)z;\r
+}\r
+\r
+static PyObject *\r
+long_sub(PyLongObject *v, PyLongObject *w)\r
+{\r
+    PyLongObject *a, *b, *z;\r
+\r
+    CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);\r
+\r
+    if (a->ob_size < 0) {\r
+        if (b->ob_size < 0)\r
+            z = x_sub(a, b);\r
+        else\r
+            z = x_add(a, b);\r
+        if (z != NULL && z->ob_size != 0)\r
+            z->ob_size = -(z->ob_size);\r
+    }\r
+    else {\r
+        if (b->ob_size < 0)\r
+            z = x_add(a, b);\r
+        else\r
+            z = x_sub(a, b);\r
+    }\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)z;\r
+}\r
+\r
+/* Grade school multiplication, ignoring the signs.\r
+ * Returns the absolute value of the product, or NULL if error.\r
+ */\r
+static PyLongObject *\r
+x_mul(PyLongObject *a, PyLongObject *b)\r
+{\r
+    PyLongObject *z;\r
+    Py_ssize_t size_a = ABS(Py_SIZE(a));\r
+    Py_ssize_t size_b = ABS(Py_SIZE(b));\r
+    Py_ssize_t i;\r
+\r
+    z = _PyLong_New(size_a + size_b);\r
+    if (z == NULL)\r
+        return NULL;\r
+\r
+    memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));\r
+    if (a == b) {\r
+        /* Efficient squaring per HAC, Algorithm 14.16:\r
+         * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf\r
+         * Gives slightly less than a 2x speedup when a == b,\r
+         * via exploiting that each entry in the multiplication\r
+         * pyramid appears twice (except for the size_a squares).\r
+         */\r
+        for (i = 0; i < size_a; ++i) {\r
+            twodigits carry;\r
+            twodigits f = a->ob_digit[i];\r
+            digit *pz = z->ob_digit + (i << 1);\r
+            digit *pa = a->ob_digit + i + 1;\r
+            digit *paend = a->ob_digit + size_a;\r
+\r
+            SIGCHECK({\r
+                    Py_DECREF(z);\r
+                    return NULL;\r
+                });\r
+\r
+            carry = *pz + f * f;\r
+            *pz++ = (digit)(carry & PyLong_MASK);\r
+            carry >>= PyLong_SHIFT;\r
+            assert(carry <= PyLong_MASK);\r
+\r
+            /* Now f is added in twice in each column of the\r
+             * pyramid it appears.  Same as adding f<<1 once.\r
+             */\r
+            f <<= 1;\r
+            while (pa < paend) {\r
+                carry += *pz + *pa++ * f;\r
+                *pz++ = (digit)(carry & PyLong_MASK);\r
+                carry >>= PyLong_SHIFT;\r
+                assert(carry <= (PyLong_MASK << 1));\r
+            }\r
+            if (carry) {\r
+                carry += *pz;\r
+                *pz++ = (digit)(carry & PyLong_MASK);\r
+                carry >>= PyLong_SHIFT;\r
+            }\r
+            if (carry)\r
+                *pz += (digit)(carry & PyLong_MASK);\r
+            assert((carry >> PyLong_SHIFT) == 0);\r
+        }\r
+    }\r
+    else {      /* a is not the same as b -- gradeschool long mult */\r
+        for (i = 0; i < size_a; ++i) {\r
+            twodigits carry = 0;\r
+            twodigits f = a->ob_digit[i];\r
+            digit *pz = z->ob_digit + i;\r
+            digit *pb = b->ob_digit;\r
+            digit *pbend = b->ob_digit + size_b;\r
+\r
+            SIGCHECK({\r
+                    Py_DECREF(z);\r
+                    return NULL;\r
+                });\r
+\r
+            while (pb < pbend) {\r
+                carry += *pz + *pb++ * f;\r
+                *pz++ = (digit)(carry & PyLong_MASK);\r
+                carry >>= PyLong_SHIFT;\r
+                assert(carry <= PyLong_MASK);\r
+            }\r
+            if (carry)\r
+                *pz += (digit)(carry & PyLong_MASK);\r
+            assert((carry >> PyLong_SHIFT) == 0);\r
+        }\r
+    }\r
+    return long_normalize(z);\r
+}\r
+\r
+/* A helper for Karatsuba multiplication (k_mul).\r
+   Takes a long "n" and an integer "size" representing the place to\r
+   split, and sets low and high such that abs(n) == (high << size) + low,\r
+   viewing the shift as being by digits.  The sign bit is ignored, and\r
+   the return values are >= 0.\r
+   Returns 0 on success, -1 on failure.\r
+*/\r
+static int\r
+kmul_split(PyLongObject *n,\r
+           Py_ssize_t size,\r
+           PyLongObject **high,\r
+           PyLongObject **low)\r
+{\r
+    PyLongObject *hi, *lo;\r
+    Py_ssize_t size_lo, size_hi;\r
+    const Py_ssize_t size_n = ABS(Py_SIZE(n));\r
+\r
+    size_lo = MIN(size_n, size);\r
+    size_hi = size_n - size_lo;\r
+\r
+    if ((hi = _PyLong_New(size_hi)) == NULL)\r
+        return -1;\r
+    if ((lo = _PyLong_New(size_lo)) == NULL) {\r
+        Py_DECREF(hi);\r
+        return -1;\r
+    }\r
+\r
+    memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));\r
+    memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));\r
+\r
+    *high = long_normalize(hi);\r
+    *low = long_normalize(lo);\r
+    return 0;\r
+}\r
+\r
+static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);\r
+\r
+/* Karatsuba multiplication.  Ignores the input signs, and returns the\r
+ * absolute value of the product (or NULL if error).\r
+ * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).\r
+ */\r
+static PyLongObject *\r
+k_mul(PyLongObject *a, PyLongObject *b)\r
+{\r
+    Py_ssize_t asize = ABS(Py_SIZE(a));\r
+    Py_ssize_t bsize = ABS(Py_SIZE(b));\r
+    PyLongObject *ah = NULL;\r
+    PyLongObject *al = NULL;\r
+    PyLongObject *bh = NULL;\r
+    PyLongObject *bl = NULL;\r
+    PyLongObject *ret = NULL;\r
+    PyLongObject *t1, *t2, *t3;\r
+    Py_ssize_t shift;           /* the number of digits we split off */\r
+    Py_ssize_t i;\r
+\r
+    /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl\r
+     * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh  + ah*bh + al*bl\r
+     * Then the original product is\r
+     *     ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl\r
+     * By picking X to be a power of 2, "*X" is just shifting, and it's\r
+     * been reduced to 3 multiplies on numbers half the size.\r
+     */\r
+\r
+    /* We want to split based on the larger number; fiddle so that b\r
+     * is largest.\r
+     */\r
+    if (asize > bsize) {\r
+        t1 = a;\r
+        a = b;\r
+        b = t1;\r
+\r
+        i = asize;\r
+        asize = bsize;\r
+        bsize = i;\r
+    }\r
+\r
+    /* Use gradeschool math when either number is too small. */\r
+    i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;\r
+    if (asize <= i) {\r
+        if (asize == 0)\r
+            return _PyLong_New(0);\r
+        else\r
+            return x_mul(a, b);\r
+    }\r
+\r
+    /* If a is small compared to b, splitting on b gives a degenerate\r
+     * case with ah==0, and Karatsuba may be (even much) less efficient\r
+     * than "grade school" then.  However, we can still win, by viewing\r
+     * b as a string of "big digits", each of width a->ob_size.  That\r
+     * leads to a sequence of balanced calls to k_mul.\r
+     */\r
+    if (2 * asize <= bsize)\r
+        return k_lopsided_mul(a, b);\r
+\r
+    /* Split a & b into hi & lo pieces. */\r
+    shift = bsize >> 1;\r
+    if (kmul_split(a, shift, &ah, &al) < 0) goto fail;\r
+    assert(Py_SIZE(ah) > 0);            /* the split isn't degenerate */\r
+\r
+    if (a == b) {\r
+        bh = ah;\r
+        bl = al;\r
+        Py_INCREF(bh);\r
+        Py_INCREF(bl);\r
+    }\r
+    else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;\r
+\r
+    /* The plan:\r
+     * 1. Allocate result space (asize + bsize digits:  that's always\r
+     *    enough).\r
+     * 2. Compute ah*bh, and copy into result at 2*shift.\r
+     * 3. Compute al*bl, and copy into result at 0.  Note that this\r
+     *    can't overlap with #2.\r
+     * 4. Subtract al*bl from the result, starting at shift.  This may\r
+     *    underflow (borrow out of the high digit), but we don't care:\r
+     *    we're effectively doing unsigned arithmetic mod\r
+     *    PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,\r
+     *    borrows and carries out of the high digit can be ignored.\r
+     * 5. Subtract ah*bh from the result, starting at shift.\r
+     * 6. Compute (ah+al)*(bh+bl), and add it into the result starting\r
+     *    at shift.\r
+     */\r
+\r
+    /* 1. Allocate result space. */\r
+    ret = _PyLong_New(asize + bsize);\r
+    if (ret == NULL) goto fail;\r
+#ifdef Py_DEBUG\r
+    /* Fill with trash, to catch reference to uninitialized digits. */\r
+    memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));\r
+#endif\r
+\r
+    /* 2. t1 <- ah*bh, and copy into high digits of result. */\r
+    if ((t1 = k_mul(ah, bh)) == NULL) goto fail;\r
+    assert(Py_SIZE(t1) >= 0);\r
+    assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));\r
+    memcpy(ret->ob_digit + 2*shift, t1->ob_digit,\r
+           Py_SIZE(t1) * sizeof(digit));\r
+\r
+    /* Zero-out the digits higher than the ah*bh copy. */\r
+    i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);\r
+    if (i)\r
+        memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,\r
+               i * sizeof(digit));\r
+\r
+    /* 3. t2 <- al*bl, and copy into the low digits. */\r
+    if ((t2 = k_mul(al, bl)) == NULL) {\r
+        Py_DECREF(t1);\r
+        goto fail;\r
+    }\r
+    assert(Py_SIZE(t2) >= 0);\r
+    assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */\r
+    memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));\r
+\r
+    /* Zero out remaining digits. */\r
+    i = 2*shift - Py_SIZE(t2);          /* number of uninitialized digits */\r
+    if (i)\r
+        memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));\r
+\r
+    /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2).  We do al*bl first\r
+     * because it's fresher in cache.\r
+     */\r
+    i = Py_SIZE(ret) - shift;  /* # digits after shift */\r
+    (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));\r
+    Py_DECREF(t2);\r
+\r
+    (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));\r
+    Py_DECREF(t1);\r
+\r
+    /* 6. t3 <- (ah+al)(bh+bl), and add into result. */\r
+    if ((t1 = x_add(ah, al)) == NULL) goto fail;\r
+    Py_DECREF(ah);\r
+    Py_DECREF(al);\r
+    ah = al = NULL;\r
+\r
+    if (a == b) {\r
+        t2 = t1;\r
+        Py_INCREF(t2);\r
+    }\r
+    else if ((t2 = x_add(bh, bl)) == NULL) {\r
+        Py_DECREF(t1);\r
+        goto fail;\r
+    }\r
+    Py_DECREF(bh);\r
+    Py_DECREF(bl);\r
+    bh = bl = NULL;\r
+\r
+    t3 = k_mul(t1, t2);\r
+    Py_DECREF(t1);\r
+    Py_DECREF(t2);\r
+    if (t3 == NULL) goto fail;\r
+    assert(Py_SIZE(t3) >= 0);\r
+\r
+    /* Add t3.  It's not obvious why we can't run out of room here.\r
+     * See the (*) comment after this function.\r
+     */\r
+    (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));\r
+    Py_DECREF(t3);\r
+\r
+    return long_normalize(ret);\r
+\r
+  fail:\r
+    Py_XDECREF(ret);\r
+    Py_XDECREF(ah);\r
+    Py_XDECREF(al);\r
+    Py_XDECREF(bh);\r
+    Py_XDECREF(bl);\r
+    return NULL;\r
+}\r
+\r
+/* (*) Why adding t3 can't "run out of room" above.\r
+\r
+Let f(x) mean the floor of x and c(x) mean the ceiling of x.  Some facts\r
+to start with:\r
+\r
+1. For any integer i, i = c(i/2) + f(i/2).  In particular,\r
+   bsize = c(bsize/2) + f(bsize/2).\r
+2. shift = f(bsize/2)\r
+3. asize <= bsize\r
+4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this\r
+   routine, so asize > bsize/2 >= f(bsize/2) in this routine.\r
+\r
+We allocated asize + bsize result digits, and add t3 into them at an offset\r
+of shift.  This leaves asize+bsize-shift allocated digit positions for t3\r
+to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =\r
+asize + c(bsize/2) available digit positions.\r
+\r
+bh has c(bsize/2) digits, and bl at most f(size/2) digits.  So bh+hl has\r
+at most c(bsize/2) digits + 1 bit.\r
+\r
+If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)\r
+digits, and al has at most f(bsize/2) digits in any case.  So ah+al has at\r
+most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.\r
+\r
+The product (ah+al)*(bh+bl) therefore has at most\r
+\r
+    c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits\r
+\r
+and we have asize + c(bsize/2) available digit positions.  We need to show\r
+this is always enough.  An instance of c(bsize/2) cancels out in both, so\r
+the question reduces to whether asize digits is enough to hold\r
+(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits.  If asize < bsize,\r
+then we're asking whether asize digits >= f(bsize/2) digits + 2 bits.  By #4,\r
+asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1\r
+digit is enough to hold 2 bits.  This is so since PyLong_SHIFT=15 >= 2.  If\r
+asize == bsize, then we're asking whether bsize digits is enough to hold\r
+c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits\r
+is enough to hold 2 bits.  This is so if bsize >= 2, which holds because\r
+bsize >= KARATSUBA_CUTOFF >= 2.\r
+\r
+Note that since there's always enough room for (ah+al)*(bh+bl), and that's\r
+clearly >= each of ah*bh and al*bl, there's always enough room to subtract\r
+ah*bh and al*bl too.\r
+*/\r
+\r
+/* b has at least twice the digits of a, and a is big enough that Karatsuba\r
+ * would pay off *if* the inputs had balanced sizes.  View b as a sequence\r
+ * of slices, each with a->ob_size digits, and multiply the slices by a,\r
+ * one at a time.  This gives k_mul balanced inputs to work with, and is\r
+ * also cache-friendly (we compute one double-width slice of the result\r
+ * at a time, then move on, never backtracking except for the helpful\r
+ * single-width slice overlap between successive partial sums).\r
+ */\r
+static PyLongObject *\r
+k_lopsided_mul(PyLongObject *a, PyLongObject *b)\r
+{\r
+    const Py_ssize_t asize = ABS(Py_SIZE(a));\r
+    Py_ssize_t bsize = ABS(Py_SIZE(b));\r
+    Py_ssize_t nbdone;          /* # of b digits already multiplied */\r
+    PyLongObject *ret;\r
+    PyLongObject *bslice = NULL;\r
+\r
+    assert(asize > KARATSUBA_CUTOFF);\r
+    assert(2 * asize <= bsize);\r
+\r
+    /* Allocate result space, and zero it out. */\r
+    ret = _PyLong_New(asize + bsize);\r
+    if (ret == NULL)\r
+        return NULL;\r
+    memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));\r
+\r
+    /* Successive slices of b are copied into bslice. */\r
+    bslice = _PyLong_New(asize);\r
+    if (bslice == NULL)\r
+        goto fail;\r
+\r
+    nbdone = 0;\r
+    while (bsize > 0) {\r
+        PyLongObject *product;\r
+        const Py_ssize_t nbtouse = MIN(bsize, asize);\r
+\r
+        /* Multiply the next slice of b by a. */\r
+        memcpy(bslice->ob_digit, b->ob_digit + nbdone,\r
+               nbtouse * sizeof(digit));\r
+        Py_SIZE(bslice) = nbtouse;\r
+        product = k_mul(a, bslice);\r
+        if (product == NULL)\r
+            goto fail;\r
+\r
+        /* Add into result. */\r
+        (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,\r
+                     product->ob_digit, Py_SIZE(product));\r
+        Py_DECREF(product);\r
+\r
+        bsize -= nbtouse;\r
+        nbdone += nbtouse;\r
+    }\r
+\r
+    Py_DECREF(bslice);\r
+    return long_normalize(ret);\r
+\r
+  fail:\r
+    Py_DECREF(ret);\r
+    Py_XDECREF(bslice);\r
+    return NULL;\r
+}\r
+\r
+static PyObject *\r
+long_mul(PyLongObject *v, PyLongObject *w)\r
+{\r
+    PyLongObject *a, *b, *z;\r
+\r
+    if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {\r
+        Py_INCREF(Py_NotImplemented);\r
+        return Py_NotImplemented;\r
+    }\r
+\r
+    z = k_mul(a, b);\r
+    /* Negate if exactly one of the inputs is negative. */\r
+    if (((a->ob_size ^ b->ob_size) < 0) && z)\r
+        z->ob_size = -(z->ob_size);\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)z;\r
+}\r
+\r
+/* The / and % operators are now defined in terms of divmod().\r
+   The expression a mod b has the value a - b*floor(a/b).\r
+   The long_divrem function gives the remainder after division of\r
+   |a| by |b|, with the sign of a.  This is also expressed\r
+   as a - b*trunc(a/b), if trunc truncates towards zero.\r
+   Some examples:\r
+     a           b      a rem b         a mod b\r
+     13          10      3               3\r
+    -13          10     -3               7\r
+     13         -10      3              -7\r
+    -13         -10     -3              -3\r
+   So, to get from rem to mod, we have to add b if a and b\r
+   have different signs.  We then subtract one from the 'div'\r
+   part of the outcome to keep the invariant intact. */\r
+\r
+/* Compute\r
+ *     *pdiv, *pmod = divmod(v, w)\r
+ * NULL can be passed for pdiv or pmod, in which case that part of\r
+ * the result is simply thrown away.  The caller owns a reference to\r
+ * each of these it requests (does not pass NULL for).\r
+ */\r
+static int\r
+l_divmod(PyLongObject *v, PyLongObject *w,\r
+         PyLongObject **pdiv, PyLongObject **pmod)\r
+{\r
+    PyLongObject *div, *mod;\r
+\r
+    if (long_divrem(v, w, &div, &mod) < 0)\r
+        return -1;\r
+    if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||\r
+        (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {\r
+        PyLongObject *temp;\r
+        PyLongObject *one;\r
+        temp = (PyLongObject *) long_add(mod, w);\r
+        Py_DECREF(mod);\r
+        mod = temp;\r
+        if (mod == NULL) {\r
+            Py_DECREF(div);\r
+            return -1;\r
+        }\r
+        one = (PyLongObject *) PyLong_FromLong(1L);\r
+        if (one == NULL ||\r
+            (temp = (PyLongObject *) long_sub(div, one)) == NULL) {\r
+            Py_DECREF(mod);\r
+            Py_DECREF(div);\r
+            Py_XDECREF(one);\r
+            return -1;\r
+        }\r
+        Py_DECREF(one);\r
+        Py_DECREF(div);\r
+        div = temp;\r
+    }\r
+    if (pdiv != NULL)\r
+        *pdiv = div;\r
+    else\r
+        Py_DECREF(div);\r
+\r
+    if (pmod != NULL)\r
+        *pmod = mod;\r
+    else\r
+        Py_DECREF(mod);\r
+\r
+    return 0;\r
+}\r
+\r
+static PyObject *\r
+long_div(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b, *div;\r
+\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+    if (l_divmod(a, b, &div, NULL) < 0)\r
+        div = NULL;\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)div;\r
+}\r
+\r
+static PyObject *\r
+long_classic_div(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b, *div;\r
+\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+    if (Py_DivisionWarningFlag &&\r
+        PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)\r
+        div = NULL;\r
+    else if (l_divmod(a, b, &div, NULL) < 0)\r
+        div = NULL;\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)div;\r
+}\r
+\r
+/* PyLong/PyLong -> float, with correctly rounded result. */\r
+\r
+#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)\r
+#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)\r
+\r
+static PyObject *\r
+long_true_divide(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b, *x;\r
+    Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;\r
+    digit mask, low;\r
+    int inexact, negate, a_is_small, b_is_small;\r
+    double dx, result;\r
+\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+\r
+    /*\r
+       Method in a nutshell:\r
+\r
+         0. reduce to case a, b > 0; filter out obvious underflow/overflow\r
+         1. choose a suitable integer 'shift'\r
+         2. use integer arithmetic to compute x = floor(2**-shift*a/b)\r
+         3. adjust x for correct rounding\r
+         4. convert x to a double dx with the same value\r
+         5. return ldexp(dx, shift).\r
+\r
+       In more detail:\r
+\r
+       0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b\r
+       returns either 0.0 or -0.0, depending on the sign of b.  For a and\r
+       b both nonzero, ignore signs of a and b, and add the sign back in\r
+       at the end.  Now write a_bits and b_bits for the bit lengths of a\r
+       and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise\r
+       for b).  Then\r
+\r
+          2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).\r
+\r
+       So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and\r
+       so overflows.  Similarly, if a_bits - b_bits < DBL_MIN_EXP -\r
+       DBL_MANT_DIG - 1 then a/b underflows to 0.  With these cases out of\r
+       the way, we can assume that\r
+\r
+          DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.\r
+\r
+       1. The integer 'shift' is chosen so that x has the right number of\r
+       bits for a double, plus two or three extra bits that will be used\r
+       in the rounding decisions.  Writing a_bits and b_bits for the\r
+       number of significant bits in a and b respectively, a\r
+       straightforward formula for shift is:\r
+\r
+          shift = a_bits - b_bits - DBL_MANT_DIG - 2\r
+\r
+       This is fine in the usual case, but if a/b is smaller than the\r
+       smallest normal float then it can lead to double rounding on an\r
+       IEEE 754 platform, giving incorrectly rounded results.  So we\r
+       adjust the formula slightly.  The actual formula used is:\r
+\r
+           shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2\r
+\r
+       2. The quantity x is computed by first shifting a (left -shift bits\r
+       if shift <= 0, right shift bits if shift > 0) and then dividing by\r
+       b.  For both the shift and the division, we keep track of whether\r
+       the result is inexact, in a flag 'inexact'; this information is\r
+       needed at the rounding stage.\r
+\r
+       With the choice of shift above, together with our assumption that\r
+       a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows\r
+       that x >= 1.\r
+\r
+       3. Now x * 2**shift <= a/b < (x+1) * 2**shift.  We want to replace\r
+       this with an exactly representable float of the form\r
+\r
+          round(x/2**extra_bits) * 2**(extra_bits+shift).\r
+\r
+       For float representability, we need x/2**extra_bits <\r
+       2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -\r
+       DBL_MANT_DIG.  This translates to the condition:\r
+\r
+          extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG\r
+\r
+       To round, we just modify the bottom digit of x in-place; this can\r
+       end up giving a digit with value > PyLONG_MASK, but that's not a\r
+       problem since digits can hold values up to 2*PyLONG_MASK+1.\r
+\r
+       With the original choices for shift above, extra_bits will always\r
+       be 2 or 3.  Then rounding under the round-half-to-even rule, we\r
+       round up iff the most significant of the extra bits is 1, and\r
+       either: (a) the computation of x in step 2 had an inexact result,\r
+       or (b) at least one other of the extra bits is 1, or (c) the least\r
+       significant bit of x (above those to be rounded) is 1.\r
+\r
+       4. Conversion to a double is straightforward; all floating-point\r
+       operations involved in the conversion are exact, so there's no\r
+       danger of rounding errors.\r
+\r
+       5. Use ldexp(x, shift) to compute x*2**shift, the final result.\r
+       The result will always be exactly representable as a double, except\r
+       in the case that it overflows.  To avoid dependence on the exact\r
+       behaviour of ldexp on overflow, we check for overflow before\r
+       applying ldexp.  The result of ldexp is adjusted for sign before\r
+       returning.\r
+    */\r
+\r
+    /* Reduce to case where a and b are both positive. */\r
+    a_size = ABS(Py_SIZE(a));\r
+    b_size = ABS(Py_SIZE(b));\r
+    negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);\r
+    if (b_size == 0) {\r
+        PyErr_SetString(PyExc_ZeroDivisionError,\r
+                        "division by zero");\r
+        goto error;\r
+    }\r
+    if (a_size == 0)\r
+        goto underflow_or_zero;\r
+\r
+    /* Fast path for a and b small (exactly representable in a double).\r
+       Relies on floating-point division being correctly rounded; results\r
+       may be subject to double rounding on x86 machines that operate with\r
+       the x87 FPU set to 64-bit precision. */\r
+    a_is_small = a_size <= MANT_DIG_DIGITS ||\r
+        (a_size == MANT_DIG_DIGITS+1 &&\r
+         a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);\r
+    b_is_small = b_size <= MANT_DIG_DIGITS ||\r
+        (b_size == MANT_DIG_DIGITS+1 &&\r
+         b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);\r
+    if (a_is_small && b_is_small) {\r
+        double da, db;\r
+        da = a->ob_digit[--a_size];\r
+        while (a_size > 0)\r
+            da = da * PyLong_BASE + a->ob_digit[--a_size];\r
+        db = b->ob_digit[--b_size];\r
+        while (b_size > 0)\r
+            db = db * PyLong_BASE + b->ob_digit[--b_size];\r
+        result = da / db;\r
+        goto success;\r
+    }\r
+\r
+    /* Catch obvious cases of underflow and overflow */\r
+    diff = a_size - b_size;\r
+    if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)\r
+        /* Extreme overflow */\r
+        goto overflow;\r
+    else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)\r
+        /* Extreme underflow */\r
+        goto underflow_or_zero;\r
+    /* Next line is now safe from overflowing a Py_ssize_t */\r
+    diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -\r
+        bits_in_digit(b->ob_digit[b_size - 1]);\r
+    /* Now diff = a_bits - b_bits. */\r
+    if (diff > DBL_MAX_EXP)\r
+        goto overflow;\r
+    else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)\r
+        goto underflow_or_zero;\r
+\r
+    /* Choose value for shift; see comments for step 1 above. */\r
+    shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;\r
+\r
+    inexact = 0;\r
+\r
+    /* x = abs(a * 2**-shift) */\r
+    if (shift <= 0) {\r
+        Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;\r
+        digit rem;\r
+        /* x = a << -shift */\r
+        if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {\r
+            /* In practice, it's probably impossible to end up\r
+               here.  Both a and b would have to be enormous,\r
+               using close to SIZE_T_MAX bytes of memory each. */\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "intermediate overflow during division");\r
+            goto error;\r
+        }\r
+        x = _PyLong_New(a_size + shift_digits + 1);\r
+        if (x == NULL)\r
+            goto error;\r
+        for (i = 0; i < shift_digits; i++)\r
+            x->ob_digit[i] = 0;\r
+        rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,\r
+                       a_size, -shift % PyLong_SHIFT);\r
+        x->ob_digit[a_size + shift_digits] = rem;\r
+    }\r
+    else {\r
+        Py_ssize_t shift_digits = shift / PyLong_SHIFT;\r
+        digit rem;\r
+        /* x = a >> shift */\r
+        assert(a_size >= shift_digits);\r
+        x = _PyLong_New(a_size - shift_digits);\r
+        if (x == NULL)\r
+            goto error;\r
+        rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,\r
+                       a_size - shift_digits, shift % PyLong_SHIFT);\r
+        /* set inexact if any of the bits shifted out is nonzero */\r
+        if (rem)\r
+            inexact = 1;\r
+        while (!inexact && shift_digits > 0)\r
+            if (a->ob_digit[--shift_digits])\r
+                inexact = 1;\r
+    }\r
+    long_normalize(x);\r
+    x_size = Py_SIZE(x);\r
+\r
+    /* x //= b. If the remainder is nonzero, set inexact.  We own the only\r
+       reference to x, so it's safe to modify it in-place. */\r
+    if (b_size == 1) {\r
+        digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,\r
+                              b->ob_digit[0]);\r
+        long_normalize(x);\r
+        if (rem)\r
+            inexact = 1;\r
+    }\r
+    else {\r
+        PyLongObject *div, *rem;\r
+        div = x_divrem(x, b, &rem);\r
+        Py_DECREF(x);\r
+        x = div;\r
+        if (x == NULL)\r
+            goto error;\r
+        if (Py_SIZE(rem))\r
+            inexact = 1;\r
+        Py_DECREF(rem);\r
+    }\r
+    x_size = ABS(Py_SIZE(x));\r
+    assert(x_size > 0); /* result of division is never zero */\r
+    x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);\r
+\r
+    /* The number of extra bits that have to be rounded away. */\r
+    extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;\r
+    assert(extra_bits == 2 || extra_bits == 3);\r
+\r
+    /* Round by directly modifying the low digit of x. */\r
+    mask = (digit)1 << (extra_bits - 1);\r
+    low = x->ob_digit[0] | inexact;\r
+    if (low & mask && low & (3*mask-1))\r
+        low += mask;\r
+    x->ob_digit[0] = low & ~(mask-1U);\r
+\r
+    /* Convert x to a double dx; the conversion is exact. */\r
+    dx = x->ob_digit[--x_size];\r
+    while (x_size > 0)\r
+        dx = dx * PyLong_BASE + x->ob_digit[--x_size];\r
+    Py_DECREF(x);\r
+\r
+    /* Check whether ldexp result will overflow a double. */\r
+    if (shift + x_bits >= DBL_MAX_EXP &&\r
+        (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))\r
+        goto overflow;\r
+    result = ldexp(dx, (int)shift);\r
+\r
+  success:\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return PyFloat_FromDouble(negate ? -result : result);\r
+\r
+  underflow_or_zero:\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return PyFloat_FromDouble(negate ? -0.0 : 0.0);\r
+\r
+  overflow:\r
+    PyErr_SetString(PyExc_OverflowError,\r
+                    "integer division result too large for a float");\r
+  error:\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return NULL;\r
+}\r
+\r
+static PyObject *\r
+long_mod(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b, *mod;\r
+\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+\r
+    if (l_divmod(a, b, NULL, &mod) < 0)\r
+        mod = NULL;\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)mod;\r
+}\r
+\r
+static PyObject *\r
+long_divmod(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b, *div, *mod;\r
+    PyObject *z;\r
+\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+\r
+    if (l_divmod(a, b, &div, &mod) < 0) {\r
+        Py_DECREF(a);\r
+        Py_DECREF(b);\r
+        return NULL;\r
+    }\r
+    z = PyTuple_New(2);\r
+    if (z != NULL) {\r
+        PyTuple_SetItem(z, 0, (PyObject *) div);\r
+        PyTuple_SetItem(z, 1, (PyObject *) mod);\r
+    }\r
+    else {\r
+        Py_DECREF(div);\r
+        Py_DECREF(mod);\r
+    }\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return z;\r
+}\r
+\r
+/* pow(v, w, x) */\r
+static PyObject *\r
+long_pow(PyObject *v, PyObject *w, PyObject *x)\r
+{\r
+    PyLongObject *a, *b, *c; /* a,b,c = v,w,x */\r
+    int negativeOutput = 0;  /* if x<0 return negative output */\r
+\r
+    PyLongObject *z = NULL;  /* accumulated result */\r
+    Py_ssize_t i, j, k;             /* counters */\r
+    PyLongObject *temp = NULL;\r
+\r
+    /* 5-ary values.  If the exponent is large enough, table is\r
+     * precomputed so that table[i] == a**i % c for i in range(32).\r
+     */\r
+    PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r
+                               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\r
+\r
+    /* a, b, c = v, w, x */\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+    if (PyLong_Check(x)) {\r
+        c = (PyLongObject *)x;\r
+        Py_INCREF(x);\r
+    }\r
+    else if (PyInt_Check(x)) {\r
+        c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));\r
+        if (c == NULL)\r
+            goto Error;\r
+    }\r
+    else if (x == Py_None)\r
+        c = NULL;\r
+    else {\r
+        Py_DECREF(a);\r
+        Py_DECREF(b);\r
+        Py_INCREF(Py_NotImplemented);\r
+        return Py_NotImplemented;\r
+    }\r
+\r
+    if (Py_SIZE(b) < 0) {  /* if exponent is negative */\r
+        if (c) {\r
+            PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "\r
+                            "cannot be negative when 3rd argument specified");\r
+            goto Error;\r
+        }\r
+        else {\r
+            /* else return a float.  This works because we know\r
+               that this calls float_pow() which converts its\r
+               arguments to double. */\r
+            Py_DECREF(a);\r
+            Py_DECREF(b);\r
+            return PyFloat_Type.tp_as_number->nb_power(v, w, x);\r
+        }\r
+    }\r
+\r
+    if (c) {\r
+        /* if modulus == 0:\r
+               raise ValueError() */\r
+        if (Py_SIZE(c) == 0) {\r
+            PyErr_SetString(PyExc_ValueError,\r
+                            "pow() 3rd argument cannot be 0");\r
+            goto Error;\r
+        }\r
+\r
+        /* if modulus < 0:\r
+               negativeOutput = True\r
+               modulus = -modulus */\r
+        if (Py_SIZE(c) < 0) {\r
+            negativeOutput = 1;\r
+            temp = (PyLongObject *)_PyLong_Copy(c);\r
+            if (temp == NULL)\r
+                goto Error;\r
+            Py_DECREF(c);\r
+            c = temp;\r
+            temp = NULL;\r
+            c->ob_size = - c->ob_size;\r
+        }\r
+\r
+        /* if modulus == 1:\r
+               return 0 */\r
+        if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {\r
+            z = (PyLongObject *)PyLong_FromLong(0L);\r
+            goto Done;\r
+        }\r
+\r
+        /* if base < 0:\r
+               base = base % modulus\r
+           Having the base positive just makes things easier. */\r
+        if (Py_SIZE(a) < 0) {\r
+            if (l_divmod(a, c, NULL, &temp) < 0)\r
+                goto Error;\r
+            Py_DECREF(a);\r
+            a = temp;\r
+            temp = NULL;\r
+        }\r
+    }\r
+\r
+    /* At this point a, b, and c are guaranteed non-negative UNLESS\r
+       c is NULL, in which case a may be negative. */\r
+\r
+    z = (PyLongObject *)PyLong_FromLong(1L);\r
+    if (z == NULL)\r
+        goto Error;\r
+\r
+    /* Perform a modular reduction, X = X % c, but leave X alone if c\r
+     * is NULL.\r
+     */\r
+#define REDUCE(X)                                       \\r
+    do {                                                \\r
+        if (c != NULL) {                                \\r
+            if (l_divmod(X, c, NULL, &temp) < 0)        \\r
+                goto Error;                             \\r
+            Py_XDECREF(X);                              \\r
+            X = temp;                                   \\r
+            temp = NULL;                                \\r
+        }                                               \\r
+    } while(0)\r
+\r
+    /* Multiply two values, then reduce the result:\r
+       result = X*Y % c.  If c is NULL, skip the mod. */\r
+#define MULT(X, Y, result)                      \\r
+    do {                                        \\r
+        temp = (PyLongObject *)long_mul(X, Y);  \\r
+        if (temp == NULL)                       \\r
+            goto Error;                         \\r
+        Py_XDECREF(result);                     \\r
+        result = temp;                          \\r
+        temp = NULL;                            \\r
+        REDUCE(result);                         \\r
+    } while(0)\r
+\r
+    if (Py_SIZE(b) <= FIVEARY_CUTOFF) {\r
+        /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */\r
+        /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf    */\r
+        for (i = Py_SIZE(b) - 1; i >= 0; --i) {\r
+            digit bi = b->ob_digit[i];\r
+\r
+            for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {\r
+                MULT(z, z, z);\r
+                if (bi & j)\r
+                    MULT(z, a, z);\r
+            }\r
+        }\r
+    }\r
+    else {\r
+        /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */\r
+        Py_INCREF(z);           /* still holds 1L */\r
+        table[0] = z;\r
+        for (i = 1; i < 32; ++i)\r
+            MULT(table[i-1], a, table[i]);\r
+\r
+        for (i = Py_SIZE(b) - 1; i >= 0; --i) {\r
+            const digit bi = b->ob_digit[i];\r
+\r
+            for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {\r
+                const int index = (bi >> j) & 0x1f;\r
+                for (k = 0; k < 5; ++k)\r
+                    MULT(z, z, z);\r
+                if (index)\r
+                    MULT(z, table[index], z);\r
+            }\r
+        }\r
+    }\r
+\r
+    if (negativeOutput && (Py_SIZE(z) != 0)) {\r
+        temp = (PyLongObject *)long_sub(z, c);\r
+        if (temp == NULL)\r
+            goto Error;\r
+        Py_DECREF(z);\r
+        z = temp;\r
+        temp = NULL;\r
+    }\r
+    goto Done;\r
+\r
+  Error:\r
+    if (z != NULL) {\r
+        Py_DECREF(z);\r
+        z = NULL;\r
+    }\r
+    /* fall through */\r
+  Done:\r
+    if (Py_SIZE(b) > FIVEARY_CUTOFF) {\r
+        for (i = 0; i < 32; ++i)\r
+            Py_XDECREF(table[i]);\r
+    }\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    Py_XDECREF(c);\r
+    Py_XDECREF(temp);\r
+    return (PyObject *)z;\r
+}\r
+\r
+static PyObject *\r
+long_invert(PyLongObject *v)\r
+{\r
+    /* Implement ~x as -(x+1) */\r
+    PyLongObject *x;\r
+    PyLongObject *w;\r
+    w = (PyLongObject *)PyLong_FromLong(1L);\r
+    if (w == NULL)\r
+        return NULL;\r
+    x = (PyLongObject *) long_add(v, w);\r
+    Py_DECREF(w);\r
+    if (x == NULL)\r
+        return NULL;\r
+    Py_SIZE(x) = -(Py_SIZE(x));\r
+    return (PyObject *)x;\r
+}\r
+\r
+static PyObject *\r
+long_neg(PyLongObject *v)\r
+{\r
+    PyLongObject *z;\r
+    if (v->ob_size == 0 && PyLong_CheckExact(v)) {\r
+        /* -0 == 0 */\r
+        Py_INCREF(v);\r
+        return (PyObject *) v;\r
+    }\r
+    z = (PyLongObject *)_PyLong_Copy(v);\r
+    if (z != NULL)\r
+        z->ob_size = -(v->ob_size);\r
+    return (PyObject *)z;\r
+}\r
+\r
+static PyObject *\r
+long_abs(PyLongObject *v)\r
+{\r
+    if (v->ob_size < 0)\r
+        return long_neg(v);\r
+    else\r
+        return long_long((PyObject *)v);\r
+}\r
+\r
+static int\r
+long_nonzero(PyLongObject *v)\r
+{\r
+    return Py_SIZE(v) != 0;\r
+}\r
+\r
+static PyObject *\r
+long_rshift(PyLongObject *v, PyLongObject *w)\r
+{\r
+    PyLongObject *a, *b;\r
+    PyLongObject *z = NULL;\r
+    Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;\r
+    digit lomask, himask;\r
+\r
+    CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);\r
+\r
+    if (Py_SIZE(a) < 0) {\r
+        /* Right shifting negative numbers is harder */\r
+        PyLongObject *a1, *a2;\r
+        a1 = (PyLongObject *) long_invert(a);\r
+        if (a1 == NULL)\r
+            goto rshift_error;\r
+        a2 = (PyLongObject *) long_rshift(a1, b);\r
+        Py_DECREF(a1);\r
+        if (a2 == NULL)\r
+            goto rshift_error;\r
+        z = (PyLongObject *) long_invert(a2);\r
+        Py_DECREF(a2);\r
+    }\r
+    else {\r
+        shiftby = PyLong_AsSsize_t((PyObject *)b);\r
+        if (shiftby == -1L && PyErr_Occurred())\r
+            goto rshift_error;\r
+        if (shiftby < 0) {\r
+            PyErr_SetString(PyExc_ValueError,\r
+                            "negative shift count");\r
+            goto rshift_error;\r
+        }\r
+        wordshift = shiftby / PyLong_SHIFT;\r
+        newsize = ABS(Py_SIZE(a)) - wordshift;\r
+        if (newsize <= 0) {\r
+            z = _PyLong_New(0);\r
+            Py_DECREF(a);\r
+            Py_DECREF(b);\r
+            return (PyObject *)z;\r
+        }\r
+        loshift = shiftby % PyLong_SHIFT;\r
+        hishift = PyLong_SHIFT - loshift;\r
+        lomask = ((digit)1 << hishift) - 1;\r
+        himask = PyLong_MASK ^ lomask;\r
+        z = _PyLong_New(newsize);\r
+        if (z == NULL)\r
+            goto rshift_error;\r
+        if (Py_SIZE(a) < 0)\r
+            Py_SIZE(z) = -(Py_SIZE(z));\r
+        for (i = 0, j = wordshift; i < newsize; i++, j++) {\r
+            z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;\r
+            if (i+1 < newsize)\r
+                z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;\r
+        }\r
+        z = long_normalize(z);\r
+    }\r
+  rshift_error:\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *) z;\r
+\r
+}\r
+\r
+static PyObject *\r
+long_lshift(PyObject *v, PyObject *w)\r
+{\r
+    /* This version due to Tim Peters */\r
+    PyLongObject *a, *b;\r
+    PyLongObject *z = NULL;\r
+    Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;\r
+    twodigits accum;\r
+\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+\r
+    shiftby = PyLong_AsSsize_t((PyObject *)b);\r
+    if (shiftby == -1L && PyErr_Occurred())\r
+        goto lshift_error;\r
+    if (shiftby < 0) {\r
+        PyErr_SetString(PyExc_ValueError, "negative shift count");\r
+        goto lshift_error;\r
+    }\r
+    /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */\r
+    wordshift = shiftby / PyLong_SHIFT;\r
+    remshift  = shiftby - wordshift * PyLong_SHIFT;\r
+\r
+    oldsize = ABS(a->ob_size);\r
+    newsize = oldsize + wordshift;\r
+    if (remshift)\r
+        ++newsize;\r
+    z = _PyLong_New(newsize);\r
+    if (z == NULL)\r
+        goto lshift_error;\r
+    if (a->ob_size < 0)\r
+        z->ob_size = -(z->ob_size);\r
+    for (i = 0; i < wordshift; i++)\r
+        z->ob_digit[i] = 0;\r
+    accum = 0;\r
+    for (i = wordshift, j = 0; j < oldsize; i++, j++) {\r
+        accum |= (twodigits)a->ob_digit[j] << remshift;\r
+        z->ob_digit[i] = (digit)(accum & PyLong_MASK);\r
+        accum >>= PyLong_SHIFT;\r
+    }\r
+    if (remshift)\r
+        z->ob_digit[newsize-1] = (digit)accum;\r
+    else\r
+        assert(!accum);\r
+    z = long_normalize(z);\r
+  lshift_error:\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *) z;\r
+}\r
+\r
+/* Compute two's complement of digit vector a[0:m], writing result to\r
+   z[0:m].  The digit vector a need not be normalized, but should not\r
+   be entirely zero.  a and z may point to the same digit vector. */\r
+\r
+static void\r
+v_complement(digit *z, digit *a, Py_ssize_t m)\r
+{\r
+    Py_ssize_t i;\r
+    digit carry = 1;\r
+    for (i = 0; i < m; ++i) {\r
+        carry += a[i] ^ PyLong_MASK;\r
+        z[i] = carry & PyLong_MASK;\r
+        carry >>= PyLong_SHIFT;\r
+    }\r
+    assert(carry == 0);\r
+}\r
+\r
+/* Bitwise and/xor/or operations */\r
+\r
+static PyObject *\r
+long_bitwise(PyLongObject *a,\r
+             int op,  /* '&', '|', '^' */\r
+             PyLongObject *b)\r
+{\r
+    int nega, negb, negz;\r
+    Py_ssize_t size_a, size_b, size_z, i;\r
+    PyLongObject *z;\r
+\r
+    /* Bitwise operations for negative numbers operate as though\r
+       on a two's complement representation.  So convert arguments\r
+       from sign-magnitude to two's complement, and convert the\r
+       result back to sign-magnitude at the end. */\r
+\r
+    /* If a is negative, replace it by its two's complement. */\r
+    size_a = ABS(Py_SIZE(a));\r
+    nega = Py_SIZE(a) < 0;\r
+    if (nega) {\r
+        z = _PyLong_New(size_a);\r
+        if (z == NULL)\r
+            return NULL;\r
+        v_complement(z->ob_digit, a->ob_digit, size_a);\r
+        a = z;\r
+    }\r
+    else\r
+        /* Keep reference count consistent. */\r
+        Py_INCREF(a);\r
+\r
+    /* Same for b. */\r
+    size_b = ABS(Py_SIZE(b));\r
+    negb = Py_SIZE(b) < 0;\r
+    if (negb) {\r
+        z = _PyLong_New(size_b);\r
+        if (z == NULL) {\r
+            Py_DECREF(a);\r
+            return NULL;\r
+        }\r
+        v_complement(z->ob_digit, b->ob_digit, size_b);\r
+        b = z;\r
+    }\r
+    else\r
+        Py_INCREF(b);\r
+\r
+    /* Swap a and b if necessary to ensure size_a >= size_b. */\r
+    if (size_a < size_b) {\r
+        z = a; a = b; b = z;\r
+        size_z = size_a; size_a = size_b; size_b = size_z;\r
+        negz = nega; nega = negb; negb = negz;\r
+    }\r
+\r
+    /* JRH: The original logic here was to allocate the result value (z)\r
+       as the longer of the two operands.  However, there are some cases\r
+       where the result is guaranteed to be shorter than that: AND of two\r
+       positives, OR of two negatives: use the shorter number.  AND with\r
+       mixed signs: use the positive number.  OR with mixed signs: use the\r
+       negative number.\r
+    */\r
+    switch (op) {\r
+    case '^':\r
+        negz = nega ^ negb;\r
+        size_z = size_a;\r
+        break;\r
+    case '&':\r
+        negz = nega & negb;\r
+        size_z = negb ? size_a : size_b;\r
+        break;\r
+    case '|':\r
+        negz = nega | negb;\r
+        size_z = negb ? size_b : size_a;\r
+        break;\r
+    default:\r
+        PyErr_BadArgument();\r
+        return NULL;\r
+    }\r
+\r
+    /* We allow an extra digit if z is negative, to make sure that\r
+       the final two's complement of z doesn't overflow. */\r
+    z = _PyLong_New(size_z + negz);\r
+    if (z == NULL) {\r
+        Py_DECREF(a);\r
+        Py_DECREF(b);\r
+        return NULL;\r
+    }\r
+\r
+    /* Compute digits for overlap of a and b. */\r
+    switch(op) {\r
+    case '&':\r
+        for (i = 0; i < size_b; ++i)\r
+            z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];\r
+        break;\r
+    case '|':\r
+        for (i = 0; i < size_b; ++i)\r
+            z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];\r
+        break;\r
+    case '^':\r
+        for (i = 0; i < size_b; ++i)\r
+            z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];\r
+        break;\r
+    default:\r
+        PyErr_BadArgument();\r
+        return NULL;\r
+    }\r
+\r
+    /* Copy any remaining digits of a, inverting if necessary. */\r
+    if (op == '^' && negb)\r
+        for (; i < size_z; ++i)\r
+            z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;\r
+    else if (i < size_z)\r
+        memcpy(&z->ob_digit[i], &a->ob_digit[i],\r
+               (size_z-i)*sizeof(digit));\r
+\r
+    /* Complement result if negative. */\r
+    if (negz) {\r
+        Py_SIZE(z) = -(Py_SIZE(z));\r
+        z->ob_digit[size_z] = PyLong_MASK;\r
+        v_complement(z->ob_digit, z->ob_digit, size_z+1);\r
+    }\r
+\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return (PyObject *)long_normalize(z);\r
+}\r
+\r
+static PyObject *\r
+long_and(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b;\r
+    PyObject *c;\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+    c = long_bitwise(a, '&', b);\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return c;\r
+}\r
+\r
+static PyObject *\r
+long_xor(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b;\r
+    PyObject *c;\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+    c = long_bitwise(a, '^', b);\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return c;\r
+}\r
+\r
+static PyObject *\r
+long_or(PyObject *v, PyObject *w)\r
+{\r
+    PyLongObject *a, *b;\r
+    PyObject *c;\r
+    CONVERT_BINOP(v, w, &a, &b);\r
+    c = long_bitwise(a, '|', b);\r
+    Py_DECREF(a);\r
+    Py_DECREF(b);\r
+    return c;\r
+}\r
+\r
+static int\r
+long_coerce(PyObject **pv, PyObject **pw)\r
+{\r
+    if (PyInt_Check(*pw)) {\r
+        *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));\r
+        if (*pw == NULL)\r
+            return -1;\r
+        Py_INCREF(*pv);\r
+        return 0;\r
+    }\r
+    else if (PyLong_Check(*pw)) {\r
+        Py_INCREF(*pv);\r
+        Py_INCREF(*pw);\r
+        return 0;\r
+    }\r
+    return 1; /* Can't do it */\r
+}\r
+\r
+static PyObject *\r
+long_long(PyObject *v)\r
+{\r
+    if (PyLong_CheckExact(v))\r
+        Py_INCREF(v);\r
+    else\r
+        v = _PyLong_Copy((PyLongObject *)v);\r
+    return v;\r
+}\r
+\r
+static PyObject *\r
+long_int(PyObject *v)\r
+{\r
+    long x;\r
+    x = PyLong_AsLong(v);\r
+    if (PyErr_Occurred()) {\r
+        if (PyErr_ExceptionMatches(PyExc_OverflowError)) {\r
+            PyErr_Clear();\r
+            if (PyLong_CheckExact(v)) {\r
+                Py_INCREF(v);\r
+                return v;\r
+            }\r
+            else\r
+                return _PyLong_Copy((PyLongObject *)v);\r
+        }\r
+        else\r
+            return NULL;\r
+    }\r
+    return PyInt_FromLong(x);\r
+}\r
+\r
+static PyObject *\r
+long_float(PyObject *v)\r
+{\r
+    double result;\r
+    result = PyLong_AsDouble(v);\r
+    if (result == -1.0 && PyErr_Occurred())\r
+        return NULL;\r
+    return PyFloat_FromDouble(result);\r
+}\r
+\r
+static PyObject *\r
+long_oct(PyObject *v)\r
+{\r
+    return _PyLong_Format(v, 8, 1, 0);\r
+}\r
+\r
+static PyObject *\r
+long_hex(PyObject *v)\r
+{\r
+    return _PyLong_Format(v, 16, 1, 0);\r
+}\r
+\r
+static PyObject *\r
+long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);\r
+\r
+static PyObject *\r
+long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
+{\r
+    PyObject *x = NULL;\r
+    int base = -909;                         /* unlikely! */\r
+    static char *kwlist[] = {"x", "base", 0};\r
+\r
+    if (type != &PyLong_Type)\r
+        return long_subtype_new(type, args, kwds); /* Wimp out */\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,\r
+                                     &x, &base))\r
+        return NULL;\r
+    if (x == NULL)\r
+        return PyLong_FromLong(0L);\r
+    if (base == -909)\r
+        return PyNumber_Long(x);\r
+    else if (PyString_Check(x)) {\r
+        /* Since PyLong_FromString doesn't have a length parameter,\r
+         * check here for possible NULs in the string. */\r
+        char *string = PyString_AS_STRING(x);\r
+        if (strlen(string) != (size_t)PyString_Size(x)) {\r
+            /* create a repr() of the input string,\r
+             * just like PyLong_FromString does. */\r
+            PyObject *srepr;\r
+            srepr = PyObject_Repr(x);\r
+            if (srepr == NULL)\r
+                return NULL;\r
+            PyErr_Format(PyExc_ValueError,\r
+                         "invalid literal for long() with base %d: %s",\r
+                         base, PyString_AS_STRING(srepr));\r
+            Py_DECREF(srepr);\r
+            return NULL;\r
+        }\r
+        return PyLong_FromString(PyString_AS_STRING(x), NULL, base);\r
+    }\r
+#ifdef Py_USING_UNICODE\r
+    else if (PyUnicode_Check(x))\r
+        return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),\r
+                                  PyUnicode_GET_SIZE(x),\r
+                                  base);\r
+#endif\r
+    else {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "long() can't convert non-string with explicit base");\r
+        return NULL;\r
+    }\r
+}\r
+\r
+/* Wimpy, slow approach to tp_new calls for subtypes of long:\r
+   first create a regular long from whatever arguments we got,\r
+   then allocate a subtype instance and initialize it from\r
+   the regular long.  The regular long is then thrown away.\r
+*/\r
+static PyObject *\r
+long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
+{\r
+    PyLongObject *tmp, *newobj;\r
+    Py_ssize_t i, n;\r
+\r
+    assert(PyType_IsSubtype(type, &PyLong_Type));\r
+    tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);\r
+    if (tmp == NULL)\r
+        return NULL;\r
+    assert(PyLong_CheckExact(tmp));\r
+    n = Py_SIZE(tmp);\r
+    if (n < 0)\r
+        n = -n;\r
+    newobj = (PyLongObject *)type->tp_alloc(type, n);\r
+    if (newobj == NULL) {\r
+        Py_DECREF(tmp);\r
+        return NULL;\r
+    }\r
+    assert(PyLong_Check(newobj));\r
+    Py_SIZE(newobj) = Py_SIZE(tmp);\r
+    for (i = 0; i < n; i++)\r
+        newobj->ob_digit[i] = tmp->ob_digit[i];\r
+    Py_DECREF(tmp);\r
+    return (PyObject *)newobj;\r
+}\r
+\r
+static PyObject *\r
+long_getnewargs(PyLongObject *v)\r
+{\r
+    return Py_BuildValue("(N)", _PyLong_Copy(v));\r
+}\r
+\r
+static PyObject *\r
+long_get0(PyLongObject *v, void *context) {\r
+    return PyLong_FromLong(0L);\r
+}\r
+\r
+static PyObject *\r
+long_get1(PyLongObject *v, void *context) {\r
+    return PyLong_FromLong(1L);\r
+}\r
+\r
+static PyObject *\r
+long__format__(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *format_spec;\r
+\r
+    if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))\r
+        return NULL;\r
+    if (PyBytes_Check(format_spec))\r
+        return _PyLong_FormatAdvanced(self,\r
+                                      PyBytes_AS_STRING(format_spec),\r
+                                      PyBytes_GET_SIZE(format_spec));\r
+    if (PyUnicode_Check(format_spec)) {\r
+        /* Convert format_spec to a str */\r
+        PyObject *result;\r
+        PyObject *str_spec = PyObject_Str(format_spec);\r
+\r
+        if (str_spec == NULL)\r
+            return NULL;\r
+\r
+        result = _PyLong_FormatAdvanced(self,\r
+                                        PyBytes_AS_STRING(str_spec),\r
+                                        PyBytes_GET_SIZE(str_spec));\r
+\r
+        Py_DECREF(str_spec);\r
+        return result;\r
+    }\r
+    PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");\r
+    return NULL;\r
+}\r
+\r
+static PyObject *\r
+long_sizeof(PyLongObject *v)\r
+{\r
+    Py_ssize_t res;\r
+\r
+    res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);\r
+    return PyInt_FromSsize_t(res);\r
+}\r
+\r
+static PyObject *\r
+long_bit_length(PyLongObject *v)\r
+{\r
+    PyLongObject *result, *x, *y;\r
+    Py_ssize_t ndigits, msd_bits = 0;\r
+    digit msd;\r
+\r
+    assert(v != NULL);\r
+    assert(PyLong_Check(v));\r
+\r
+    ndigits = ABS(Py_SIZE(v));\r
+    if (ndigits == 0)\r
+        return PyInt_FromLong(0);\r
+\r
+    msd = v->ob_digit[ndigits-1];\r
+    while (msd >= 32) {\r
+        msd_bits += 6;\r
+        msd >>= 6;\r
+    }\r
+    msd_bits += (long)(BitLengthTable[msd]);\r
+\r
+    if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)\r
+        return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);\r
+\r
+    /* expression above may overflow; use Python integers instead */\r
+    result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);\r
+    if (result == NULL)\r
+        return NULL;\r
+    x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);\r
+    if (x == NULL)\r
+        goto error;\r
+    y = (PyLongObject *)long_mul(result, x);\r
+    Py_DECREF(x);\r
+    if (y == NULL)\r
+        goto error;\r
+    Py_DECREF(result);\r
+    result = y;\r
+\r
+    x = (PyLongObject *)PyLong_FromLong((long)msd_bits);\r
+    if (x == NULL)\r
+        goto error;\r
+    y = (PyLongObject *)long_add(result, x);\r
+    Py_DECREF(x);\r
+    if (y == NULL)\r
+        goto error;\r
+    Py_DECREF(result);\r
+    result = y;\r
+\r
+    return (PyObject *)result;\r
+\r
+  error:\r
+    Py_DECREF(result);\r
+    return NULL;\r
+}\r
+\r
+PyDoc_STRVAR(long_bit_length_doc,\r
+"long.bit_length() -> int or long\n\\r
+\n\\r
+Number of bits necessary to represent self in binary.\n\\r
+>>> bin(37L)\n\\r
+'0b100101'\n\\r
+>>> (37L).bit_length()\n\\r
+6");\r
+\r
+#if 0\r
+static PyObject *\r
+long_is_finite(PyObject *v)\r
+{\r
+    Py_RETURN_TRUE;\r
+}\r
+#endif\r
+\r
+static PyMethodDef long_methods[] = {\r
+    {"conjugate",       (PyCFunction)long_long, METH_NOARGS,\r
+     "Returns self, the complex conjugate of any long."},\r
+    {"bit_length",      (PyCFunction)long_bit_length, METH_NOARGS,\r
+     long_bit_length_doc},\r
+#if 0\r
+    {"is_finite",       (PyCFunction)long_is_finite,    METH_NOARGS,\r
+     "Returns always True."},\r
+#endif\r
+    {"__trunc__",       (PyCFunction)long_long, METH_NOARGS,\r
+     "Truncating an Integral returns itself."},\r
+    {"__getnewargs__",          (PyCFunction)long_getnewargs,   METH_NOARGS},\r
+    {"__format__", (PyCFunction)long__format__, METH_VARARGS},\r
+    {"__sizeof__",      (PyCFunction)long_sizeof, METH_NOARGS,\r
+     "Returns size in memory, in bytes"},\r
+    {NULL,              NULL}           /* sentinel */\r
+};\r
+\r
+static PyGetSetDef long_getset[] = {\r
+    {"real",\r
+     (getter)long_long, (setter)NULL,\r
+     "the real part of a complex number",\r
+     NULL},\r
+    {"imag",\r
+     (getter)long_get0, (setter)NULL,\r
+     "the imaginary part of a complex number",\r
+     NULL},\r
+    {"numerator",\r
+     (getter)long_long, (setter)NULL,\r
+     "the numerator of a rational number in lowest terms",\r
+     NULL},\r
+    {"denominator",\r
+     (getter)long_get1, (setter)NULL,\r
+     "the denominator of a rational number in lowest terms",\r
+     NULL},\r
+    {NULL}  /* Sentinel */\r
+};\r
+\r
+PyDoc_STRVAR(long_doc,\r
+"long(x[, base]) -> integer\n\\r
+\n\\r
+Convert a string or number to a long integer, if possible.  A floating\n\\r
+point argument will be truncated towards zero (this does not include a\n\\r
+string representation of a floating point number!)  When converting a\n\\r
+string, use the optional base.  It is an error to supply a base when\n\\r
+converting a non-string.");\r
+\r
+static PyNumberMethods long_as_number = {\r
+    (binaryfunc)long_add,       /*nb_add*/\r
+    (binaryfunc)long_sub,       /*nb_subtract*/\r
+    (binaryfunc)long_mul,       /*nb_multiply*/\r
+    long_classic_div,           /*nb_divide*/\r
+    long_mod,                   /*nb_remainder*/\r
+    long_divmod,                /*nb_divmod*/\r
+    long_pow,                   /*nb_power*/\r
+    (unaryfunc)long_neg,        /*nb_negative*/\r
+    (unaryfunc)long_long,       /*tp_positive*/\r
+    (unaryfunc)long_abs,        /*tp_absolute*/\r
+    (inquiry)long_nonzero,      /*tp_nonzero*/\r
+    (unaryfunc)long_invert,     /*nb_invert*/\r
+    long_lshift,                /*nb_lshift*/\r
+    (binaryfunc)long_rshift,    /*nb_rshift*/\r
+    long_and,                   /*nb_and*/\r
+    long_xor,                   /*nb_xor*/\r
+    long_or,                    /*nb_or*/\r
+    long_coerce,                /*nb_coerce*/\r
+    long_int,                   /*nb_int*/\r
+    long_long,                  /*nb_long*/\r
+    long_float,                 /*nb_float*/\r
+    long_oct,                   /*nb_oct*/\r
+    long_hex,                   /*nb_hex*/\r
+    0,                          /* nb_inplace_add */\r
+    0,                          /* nb_inplace_subtract */\r
+    0,                          /* nb_inplace_multiply */\r
+    0,                          /* nb_inplace_divide */\r
+    0,                          /* nb_inplace_remainder */\r
+    0,                          /* nb_inplace_power */\r
+    0,                          /* nb_inplace_lshift */\r
+    0,                          /* nb_inplace_rshift */\r
+    0,                          /* nb_inplace_and */\r
+    0,                          /* nb_inplace_xor */\r
+    0,                          /* nb_inplace_or */\r
+    long_div,                   /* nb_floor_divide */\r
+    long_true_divide,           /* nb_true_divide */\r
+    0,                          /* nb_inplace_floor_divide */\r
+    0,                          /* nb_inplace_true_divide */\r
+    long_long,                  /* nb_index */\r
+};\r
+\r
+PyTypeObject PyLong_Type = {\r
+    PyObject_HEAD_INIT(&PyType_Type)\r
+    0,                                          /* ob_size */\r
+    "long",                                     /* tp_name */\r
+    offsetof(PyLongObject, ob_digit),           /* tp_basicsize */\r
+    sizeof(digit),                              /* tp_itemsize */\r
+    long_dealloc,                               /* tp_dealloc */\r
+    0,                                          /* tp_print */\r
+    0,                                          /* tp_getattr */\r
+    0,                                          /* tp_setattr */\r
+    (cmpfunc)long_compare,                      /* tp_compare */\r
+    long_repr,                                  /* tp_repr */\r
+    &long_as_number,                            /* tp_as_number */\r
+    0,                                          /* tp_as_sequence */\r
+    0,                                          /* tp_as_mapping */\r
+    (hashfunc)long_hash,                        /* tp_hash */\r
+    0,                                          /* tp_call */\r
+    long_str,                                   /* tp_str */\r
+    PyObject_GenericGetAttr,                    /* tp_getattro */\r
+    0,                                          /* tp_setattro */\r
+    0,                                          /* tp_as_buffer */\r
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
+        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */\r
+    long_doc,                                   /* tp_doc */\r
+    0,                                          /* tp_traverse */\r
+    0,                                          /* tp_clear */\r
+    0,                                          /* tp_richcompare */\r
+    0,                                          /* tp_weaklistoffset */\r
+    0,                                          /* tp_iter */\r
+    0,                                          /* tp_iternext */\r
+    long_methods,                               /* tp_methods */\r
+    0,                                          /* tp_members */\r
+    long_getset,                                /* tp_getset */\r
+    0,                                          /* tp_base */\r
+    0,                                          /* tp_dict */\r
+    0,                                          /* tp_descr_get */\r
+    0,                                          /* tp_descr_set */\r
+    0,                                          /* tp_dictoffset */\r
+    0,                                          /* tp_init */\r
+    0,                                          /* tp_alloc */\r
+    long_new,                                   /* tp_new */\r
+    PyObject_Del,                               /* tp_free */\r
+};\r
+\r
+static PyTypeObject Long_InfoType;\r
+\r
+PyDoc_STRVAR(long_info__doc__,\r
+"sys.long_info\n\\r
+\n\\r
+A struct sequence that holds information about Python's\n\\r
+internal representation of integers.  The attributes are read only.");\r
+\r
+static PyStructSequence_Field long_info_fields[] = {\r
+    {"bits_per_digit", "size of a digit in bits"},\r
+    {"sizeof_digit", "size in bytes of the C type used to represent a digit"},\r
+    {NULL, NULL}\r
+};\r
+\r
+static PyStructSequence_Desc long_info_desc = {\r
+    "sys.long_info",   /* name */\r
+    long_info__doc__,  /* doc */\r
+    long_info_fields,  /* fields */\r
+    2                  /* number of fields */\r
+};\r
+\r
+PyObject *\r
+PyLong_GetInfo(void)\r
+{\r
+    PyObject* long_info;\r
+    int field = 0;\r
+    long_info = PyStructSequence_New(&Long_InfoType);\r
+    if (long_info == NULL)\r
+        return NULL;\r
+    PyStructSequence_SET_ITEM(long_info, field++,\r
+                              PyInt_FromLong(PyLong_SHIFT));\r
+    PyStructSequence_SET_ITEM(long_info, field++,\r
+                              PyInt_FromLong(sizeof(digit)));\r
+    if (PyErr_Occurred()) {\r
+        Py_CLEAR(long_info);\r
+        return NULL;\r
+    }\r
+    return long_info;\r
+}\r
+\r
+int\r
+_PyLong_Init(void)\r
+{\r
+    /* initialize long_info */\r
+    if (Long_InfoType.tp_name == 0)\r
+        PyStructSequence_InitType(&Long_InfoType, &long_info_desc);\r
+    return 1;\r
+}\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h b/AppPkg/Applications/Python/PyMod-2.7.2/Objects/stringlib/localeutil.h
new file mode 100644 (file)
index 0000000..25b7f6f
--- /dev/null
@@ -0,0 +1,216 @@
+/* stringlib: locale related helpers implementation */\r
+\r
+#ifndef STRINGLIB_LOCALEUTIL_H\r
+#define STRINGLIB_LOCALEUTIL_H\r
+\r
+#include <locale.h>\r
+\r
+// Prevent conflicts with EFI\r
+#undef  MAX\r
+#undef  MIN\r
+\r
+#define MAX(x, y) ((x) < (y) ? (y) : (x))\r
+#define MIN(x, y) ((x) < (y) ? (x) : (y))\r
+\r
+typedef struct {\r
+    const char *grouping;\r
+    char previous;\r
+    Py_ssize_t i; /* Where we're currently pointing in grouping. */\r
+} GroupGenerator;\r
+\r
+static void\r
+_GroupGenerator_init(GroupGenerator *self, const char *grouping)\r
+{\r
+    self->grouping = grouping;\r
+    self->i = 0;\r
+    self->previous = 0;\r
+}\r
+\r
+/* Returns the next grouping, or 0 to signify end. */\r
+static Py_ssize_t\r
+_GroupGenerator_next(GroupGenerator *self)\r
+{\r
+    /* Note that we don't really do much error checking here. If a\r
+       grouping string contains just CHAR_MAX, for example, then just\r
+       terminate the generator. That shouldn't happen, but at least we\r
+       fail gracefully. */\r
+    switch (self->grouping[self->i]) {\r
+    case 0:\r
+        return self->previous;\r
+    case CHAR_MAX:\r
+        /* Stop the generator. */\r
+        return 0;\r
+    default: {\r
+        char ch = self->grouping[self->i];\r
+        self->previous = ch;\r
+        self->i++;\r
+        return (Py_ssize_t)ch;\r
+    }\r
+    }\r
+}\r
+\r
+/* Fill in some digits, leading zeros, and thousands separator. All\r
+   are optional, depending on when we're called. */\r
+static void\r
+fill(STRINGLIB_CHAR **digits_end, STRINGLIB_CHAR **buffer_end,\r
+     Py_ssize_t n_chars, Py_ssize_t n_zeros, const char* thousands_sep,\r
+     Py_ssize_t thousands_sep_len)\r
+{\r
+#if STRINGLIB_IS_UNICODE\r
+    Py_ssize_t i;\r
+#endif\r
+\r
+    if (thousands_sep) {\r
+        *buffer_end -= thousands_sep_len;\r
+\r
+        /* Copy the thousands_sep chars into the buffer. */\r
+#if STRINGLIB_IS_UNICODE\r
+        /* Convert from the char's of the thousands_sep from\r
+           the locale into unicode. */\r
+        for (i = 0; i < thousands_sep_len; ++i)\r
+            (*buffer_end)[i] = thousands_sep[i];\r
+#else\r
+        /* No conversion, just memcpy the thousands_sep. */\r
+        memcpy(*buffer_end, thousands_sep, thousands_sep_len);\r
+#endif\r
+    }\r
+\r
+    *buffer_end -= n_chars;\r
+    *digits_end -= n_chars;\r
+    memcpy(*buffer_end, *digits_end, n_chars * sizeof(STRINGLIB_CHAR));\r
+\r
+    *buffer_end -= n_zeros;\r
+    STRINGLIB_FILL(*buffer_end, '0', n_zeros);\r
+}\r
+\r
+/**\r
+ * _Py_InsertThousandsGrouping:\r
+ * @buffer: A pointer to the start of a string.\r
+ * @n_buffer: Number of characters in @buffer.\r
+ * @digits: A pointer to the digits we're reading from. If count\r
+ *          is non-NULL, this is unused.\r
+ * @n_digits: The number of digits in the string, in which we want\r
+ *            to put the grouping chars.\r
+ * @min_width: The minimum width of the digits in the output string.\r
+ *             Output will be zero-padded on the left to fill.\r
+ * @grouping: see definition in localeconv().\r
+ * @thousands_sep: see definition in localeconv().\r
+ *\r
+ * There are 2 modes: counting and filling. If @buffer is NULL,\r
+ *  we are in counting mode, else filling mode.\r
+ * If counting, the required buffer size is returned.\r
+ * If filling, we know the buffer will be large enough, so we don't\r
+ *  need to pass in the buffer size.\r
+ * Inserts thousand grouping characters (as defined by grouping and\r
+ *  thousands_sep) into the string between buffer and buffer+n_digits.\r
+ *\r
+ * Return value: 0 on error, else 1.  Note that no error can occur if\r
+ *  count is non-NULL.\r
+ *\r
+ * This name won't be used, the includer of this file should define\r
+ *  it to be the actual function name, based on unicode or string.\r
+ *\r
+ * As closely as possible, this code mimics the logic in decimal.py's\r
+    _insert_thousands_sep().\r
+ **/\r
+Py_ssize_t\r
+_Py_InsertThousandsGrouping(STRINGLIB_CHAR *buffer,\r
+                            Py_ssize_t n_buffer,\r
+                            STRINGLIB_CHAR *digits,\r
+                            Py_ssize_t n_digits,\r
+                            Py_ssize_t min_width,\r
+                            const char *grouping,\r
+                            const char *thousands_sep)\r
+{\r
+    Py_ssize_t count = 0;\r
+    Py_ssize_t n_zeros;\r
+    int loop_broken = 0;\r
+    int use_separator = 0; /* First time through, don't append the\r
+                              separator. They only go between\r
+                              groups. */\r
+    STRINGLIB_CHAR *buffer_end = NULL;\r
+    STRINGLIB_CHAR *digits_end = NULL;\r
+    Py_ssize_t l;\r
+    Py_ssize_t n_chars;\r
+    Py_ssize_t thousands_sep_len = strlen(thousands_sep);\r
+    Py_ssize_t remaining = n_digits; /* Number of chars remaining to\r
+                                        be looked at */\r
+    /* A generator that returns all of the grouping widths, until it\r
+       returns 0. */\r
+    GroupGenerator groupgen;\r
+    _GroupGenerator_init(&groupgen, grouping);\r
+\r
+    if (buffer) {\r
+        buffer_end = buffer + n_buffer;\r
+        digits_end = digits + n_digits;\r
+    }\r
+\r
+    while ((l = _GroupGenerator_next(&groupgen)) > 0) {\r
+        l = MIN(l, MAX(MAX(remaining, min_width), 1));\r
+        n_zeros = MAX(0, l - remaining);\r
+        n_chars = MAX(0, MIN(remaining, l));\r
+\r
+        /* Use n_zero zero's and n_chars chars */\r
+\r
+        /* Count only, don't do anything. */\r
+        count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;\r
+\r
+        if (buffer) {\r
+            /* Copy into the output buffer. */\r
+            fill(&digits_end, &buffer_end, n_chars, n_zeros,\r
+                 use_separator ? thousands_sep : NULL, thousands_sep_len);\r
+        }\r
+\r
+        /* Use a separator next time. */\r
+        use_separator = 1;\r
+\r
+        remaining -= n_chars;\r
+        min_width -= l;\r
+\r
+        if (remaining <= 0 && min_width <= 0) {\r
+            loop_broken = 1;\r
+            break;\r
+        }\r
+        min_width -= thousands_sep_len;\r
+    }\r
+    if (!loop_broken) {\r
+        /* We left the loop without using a break statement. */\r
+\r
+        l = MAX(MAX(remaining, min_width), 1);\r
+        n_zeros = MAX(0, l - remaining);\r
+        n_chars = MAX(0, MIN(remaining, l));\r
+\r
+        /* Use n_zero zero's and n_chars chars */\r
+        count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;\r
+        if (buffer) {\r
+            /* Copy into the output buffer. */\r
+            fill(&digits_end, &buffer_end, n_chars, n_zeros,\r
+                 use_separator ? thousands_sep : NULL, thousands_sep_len);\r
+        }\r
+    }\r
+    return count;\r
+}\r
+\r
+/**\r
+ * _Py_InsertThousandsGroupingLocale:\r
+ * @buffer: A pointer to the start of a string.\r
+ * @n_digits: The number of digits in the string, in which we want\r
+ *            to put the grouping chars.\r
+ *\r
+ * Reads thee current locale and calls _Py_InsertThousandsGrouping().\r
+ **/\r
+Py_ssize_t\r
+_Py_InsertThousandsGroupingLocale(STRINGLIB_CHAR *buffer,\r
+                                  Py_ssize_t n_buffer,\r
+                                  STRINGLIB_CHAR *digits,\r
+                                  Py_ssize_t n_digits,\r
+                                  Py_ssize_t min_width)\r
+{\r
+        struct lconv *locale_data = localeconv();\r
+        const char *grouping = locale_data->grouping;\r
+        const char *thousands_sep = locale_data->thousands_sep;\r
+\r
+        return _Py_InsertThousandsGrouping(buffer, n_buffer, digits, n_digits,\r
+                                           min_width, grouping, thousands_sep);\r
+}\r
+#endif /* STRINGLIB_LOCALEUTIL_H */\r
diff --git a/AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c b/AppPkg/Applications/Python/PyMod-2.7.2/Python/marshal.c
new file mode 100644 (file)
index 0000000..785f438
--- /dev/null
@@ -0,0 +1,1412 @@
+\r
+/* Write Python objects to files and read them back.\r
+   This is intended for writing and reading compiled Python code only;\r
+   a true persistent storage facility would be much harder, since\r
+   it would have to take circular links and sharing into account. */\r
+\r
+#define PY_SSIZE_T_CLEAN\r
+\r
+#include "Python.h"\r
+#include "longintrepr.h"\r
+#include "code.h"\r
+#include "marshal.h"\r
+\r
+#ifndef ABS\r
+  #define ABS(x) ((x) < 0 ? -(x) : (x))\r
+#endif\r
+\r
+/* High water mark to determine when the marshalled object is dangerously deep\r
+ * and risks coring the interpreter.  When the object stack gets this deep,\r
+ * raise an exception instead of continuing.\r
+ */\r
+#define MAX_MARSHAL_STACK_DEPTH 2000\r
+\r
+#define TYPE_NULL               '0'\r
+#define TYPE_NONE               'N'\r
+#define TYPE_FALSE              'F'\r
+#define TYPE_TRUE               'T'\r
+#define TYPE_STOPITER           'S'\r
+#define TYPE_ELLIPSIS           '.'\r
+#define TYPE_INT                'i'\r
+#define TYPE_INT64              'I'\r
+#define TYPE_FLOAT              'f'\r
+#define TYPE_BINARY_FLOAT       'g'\r
+#define TYPE_COMPLEX            'x'\r
+#define TYPE_BINARY_COMPLEX     'y'\r
+#define TYPE_LONG               'l'\r
+#define TYPE_STRING             's'\r
+#define TYPE_INTERNED           't'\r
+#define TYPE_STRINGREF          'R'\r
+#define TYPE_TUPLE              '('\r
+#define TYPE_LIST               '['\r
+#define TYPE_DICT               '{'\r
+#define TYPE_CODE               'c'\r
+#define TYPE_UNICODE            'u'\r
+#define TYPE_UNKNOWN            '?'\r
+#define TYPE_SET                '<'\r
+#define TYPE_FROZENSET          '>'\r
+\r
+#define WFERR_OK 0\r
+#define WFERR_UNMARSHALLABLE 1\r
+#define WFERR_NESTEDTOODEEP 2\r
+#define WFERR_NOMEMORY 3\r
+\r
+typedef struct {\r
+    FILE *fp;\r
+    int error;  /* see WFERR_* values */\r
+    int depth;\r
+    /* If fp == NULL, the following are valid: */\r
+    PyObject *str;\r
+    char *ptr;\r
+    char *end;\r
+    PyObject *strings; /* dict on marshal, list on unmarshal */\r
+    int version;\r
+} WFILE;\r
+\r
+#define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \\r
+                      else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \\r
+                           else w_more(c, p)\r
+\r
+static void\r
+w_more(int c, WFILE *p)\r
+{\r
+    Py_ssize_t size, newsize;\r
+    if (p->str == NULL)\r
+        return; /* An error already occurred */\r
+    size = PyString_Size(p->str);\r
+    newsize = size + size + 1024;\r
+    if (newsize > 32*1024*1024) {\r
+        newsize = size + (size >> 3);           /* 12.5% overallocation */\r
+    }\r
+    if (_PyString_Resize(&p->str, newsize) != 0) {\r
+        p->ptr = p->end = NULL;\r
+    }\r
+    else {\r
+        p->ptr = PyString_AS_STRING((PyStringObject *)p->str) + size;\r
+        p->end =\r
+            PyString_AS_STRING((PyStringObject *)p->str) + newsize;\r
+        *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char);\r
+    }\r
+}\r
+\r
+static void\r
+w_string(char *s, int n, WFILE *p)\r
+{\r
+    if (p->fp != NULL) {\r
+        fwrite(s, 1, n, p->fp);\r
+    }\r
+    else {\r
+        while (--n >= 0) {\r
+            w_byte(*s, p);\r
+            s++;\r
+        }\r
+    }\r
+}\r
+\r
+static void\r
+w_short(int x, WFILE *p)\r
+{\r
+    w_byte((char)( x      & 0xff), p);\r
+    w_byte((char)((x>> 8) & 0xff), p);\r
+}\r
+\r
+static void\r
+w_long(long x, WFILE *p)\r
+{\r
+    w_byte((char)( x      & 0xff), p);\r
+    w_byte((char)((x>> 8) & 0xff), p);\r
+    w_byte((char)((x>>16) & 0xff), p);\r
+    w_byte((char)((x>>24) & 0xff), p);\r
+}\r
+\r
+#if SIZEOF_LONG > 4\r
+static void\r
+w_long64(long x, WFILE *p)\r
+{\r
+    w_long(x, p);\r
+    w_long(x>>32, p);\r
+}\r
+#endif\r
+\r
+/* We assume that Python longs are stored internally in base some power of\r
+   2**15; for the sake of portability we'll always read and write them in base\r
+   exactly 2**15. */\r
+\r
+#define PyLong_MARSHAL_SHIFT 15\r
+#define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT)\r
+#define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1)\r
+#if PyLong_SHIFT % PyLong_MARSHAL_SHIFT != 0\r
+#error "PyLong_SHIFT must be a multiple of PyLong_MARSHAL_SHIFT"\r
+#endif\r
+#define PyLong_MARSHAL_RATIO (PyLong_SHIFT / PyLong_MARSHAL_SHIFT)\r
+\r
+static void\r
+w_PyLong(const PyLongObject *ob, WFILE *p)\r
+{\r
+    Py_ssize_t i, j, n, l;\r
+    digit d;\r
+\r
+    w_byte(TYPE_LONG, p);\r
+    if (Py_SIZE(ob) == 0) {\r
+        w_long((long)0, p);\r
+        return;\r
+    }\r
+\r
+    /* set l to number of base PyLong_MARSHAL_BASE digits */\r
+    n = ABS(Py_SIZE(ob));\r
+    l = (n-1) * PyLong_MARSHAL_RATIO;\r
+    d = ob->ob_digit[n-1];\r
+    assert(d != 0); /* a PyLong is always normalized */\r
+    do {\r
+        d >>= PyLong_MARSHAL_SHIFT;\r
+        l++;\r
+    } while (d != 0);\r
+    w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p);\r
+\r
+    for (i=0; i < n-1; i++) {\r
+        d = ob->ob_digit[i];\r
+        for (j=0; j < PyLong_MARSHAL_RATIO; j++) {\r
+            w_short(d & PyLong_MARSHAL_MASK, p);\r
+            d >>= PyLong_MARSHAL_SHIFT;\r
+        }\r
+        assert (d == 0);\r
+    }\r
+    d = ob->ob_digit[n-1];\r
+    do {\r
+        w_short(d & PyLong_MARSHAL_MASK, p);\r
+        d >>= PyLong_MARSHAL_SHIFT;\r
+    } while (d != 0);\r
+}\r
+\r
+static void\r
+w_object(PyObject *v, WFILE *p)\r
+{\r
+    Py_ssize_t i, n;\r
+\r
+    p->depth++;\r
+\r
+    if (p->depth > MAX_MARSHAL_STACK_DEPTH) {\r
+        p->error = WFERR_NESTEDTOODEEP;\r
+    }\r
+    else if (v == NULL) {\r
+        w_byte(TYPE_NULL, p);\r
+    }\r
+    else if (v == Py_None) {\r
+        w_byte(TYPE_NONE, p);\r
+    }\r
+    else if (v == PyExc_StopIteration) {\r
+        w_byte(TYPE_STOPITER, p);\r
+    }\r
+    else if (v == Py_Ellipsis) {\r
+        w_byte(TYPE_ELLIPSIS, p);\r
+    }\r
+    else if (v == Py_False) {\r
+        w_byte(TYPE_FALSE, p);\r
+    }\r
+    else if (v == Py_True) {\r
+        w_byte(TYPE_TRUE, p);\r
+    }\r
+    else if (PyInt_CheckExact(v)) {\r
+        long x = PyInt_AS_LONG((PyIntObject *)v);\r
+#if SIZEOF_LONG > 4\r
+        long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);\r
+        if (y && y != -1) {\r
+            w_byte(TYPE_INT64, p);\r
+            w_long64(x, p);\r
+        }\r
+        else\r
+#endif\r
+            {\r
+            w_byte(TYPE_INT, p);\r
+            w_long(x, p);\r
+        }\r
+    }\r
+    else if (PyLong_CheckExact(v)) {\r
+        PyLongObject *ob = (PyLongObject *)v;\r
+        w_PyLong(ob, p);\r
+    }\r
+    else if (PyFloat_CheckExact(v)) {\r
+        if (p->version > 1) {\r
+            unsigned char buf[8];\r
+            if (_PyFloat_Pack8(PyFloat_AsDouble(v),\r
+                               buf, 1) < 0) {\r
+                p->error = WFERR_UNMARSHALLABLE;\r
+                return;\r
+            }\r
+            w_byte(TYPE_BINARY_FLOAT, p);\r
+            w_string((char*)buf, 8, p);\r
+        }\r
+        else {\r
+            char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),\r
+                                              'g', 17, 0, NULL);\r
+            if (!buf) {\r
+                p->error = WFERR_NOMEMORY;\r
+                return;\r
+            }\r
+            n = strlen(buf);\r
+            w_byte(TYPE_FLOAT, p);\r
+            w_byte((int)n, p);\r
+            w_string(buf, (int)n, p);\r
+            PyMem_Free(buf);\r
+        }\r
+    }\r
+#ifndef WITHOUT_COMPLEX\r
+    else if (PyComplex_CheckExact(v)) {\r
+        if (p->version > 1) {\r
+            unsigned char buf[8];\r
+            if (_PyFloat_Pack8(PyComplex_RealAsDouble(v),\r
+                               buf, 1) < 0) {\r
+                p->error = WFERR_UNMARSHALLABLE;\r
+                return;\r
+            }\r
+            w_byte(TYPE_BINARY_COMPLEX, p);\r
+            w_string((char*)buf, 8, p);\r
+            if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v),\r
+                               buf, 1) < 0) {\r
+                p->error = WFERR_UNMARSHALLABLE;\r
+                return;\r
+            }\r
+            w_string((char*)buf, 8, p);\r
+        }\r
+        else {\r
+            char *buf;\r
+            w_byte(TYPE_COMPLEX, p);\r
+            buf = PyOS_double_to_string(PyComplex_RealAsDouble(v),\r
+                                        'g', 17, 0, NULL);\r
+            if (!buf) {\r
+                p->error = WFERR_NOMEMORY;\r
+                return;\r
+            }\r
+            n = strlen(buf);\r
+            w_byte((int)n, p);\r
+            w_string(buf, (int)n, p);\r
+            PyMem_Free(buf);\r
+            buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v),\r
+                                        'g', 17, 0, NULL);\r
+            if (!buf) {\r
+                p->error = WFERR_NOMEMORY;\r
+                return;\r
+            }\r
+            n = strlen(buf);\r
+            w_byte((int)n, p);\r
+            w_string(buf, (int)n, p);\r
+            PyMem_Free(buf);\r
+        }\r
+    }\r
+#endif\r
+    else if (PyString_CheckExact(v)) {\r
+        if (p->strings && PyString_CHECK_INTERNED(v)) {\r
+            PyObject *o = PyDict_GetItem(p->strings, v);\r
+            if (o) {\r
+                long w = PyInt_AsLong(o);\r
+                w_byte(TYPE_STRINGREF, p);\r
+                w_long(w, p);\r
+                goto exit;\r
+            }\r
+            else {\r
+                int ok;\r
+                o = PyInt_FromSsize_t(PyDict_Size(p->strings));\r
+                ok = o &&\r
+                     PyDict_SetItem(p->strings, v, o) >= 0;\r
+                Py_XDECREF(o);\r
+                if (!ok) {\r
+                    p->depth--;\r
+                    p->error = WFERR_UNMARSHALLABLE;\r
+                    return;\r
+                }\r
+                w_byte(TYPE_INTERNED, p);\r
+            }\r
+        }\r
+        else {\r
+            w_byte(TYPE_STRING, p);\r
+        }\r
+        n = PyString_GET_SIZE(v);\r
+        if (n > INT_MAX) {\r
+            /* huge strings are not supported */\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+        w_long((long)n, p);\r
+        w_string(PyString_AS_STRING(v), (int)n, p);\r
+    }\r
+#ifdef Py_USING_UNICODE\r
+    else if (PyUnicode_CheckExact(v)) {\r
+        PyObject *utf8;\r
+        utf8 = PyUnicode_AsUTF8String(v);\r
+        if (utf8 == NULL) {\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+        w_byte(TYPE_UNICODE, p);\r
+        n = PyString_GET_SIZE(utf8);\r
+        if (n > INT_MAX) {\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+        w_long((long)n, p);\r
+        w_string(PyString_AS_STRING(utf8), (int)n, p);\r
+        Py_DECREF(utf8);\r
+    }\r
+#endif\r
+    else if (PyTuple_CheckExact(v)) {\r
+        w_byte(TYPE_TUPLE, p);\r
+        n = PyTuple_Size(v);\r
+        w_long((long)n, p);\r
+        for (i = 0; i < n; i++) {\r
+            w_object(PyTuple_GET_ITEM(v, i), p);\r
+        }\r
+    }\r
+    else if (PyList_CheckExact(v)) {\r
+        w_byte(TYPE_LIST, p);\r
+        n = PyList_GET_SIZE(v);\r
+        w_long((long)n, p);\r
+        for (i = 0; i < n; i++) {\r
+            w_object(PyList_GET_ITEM(v, i), p);\r
+        }\r
+    }\r
+    else if (PyDict_CheckExact(v)) {\r
+        Py_ssize_t pos;\r
+        PyObject *key, *value;\r
+        w_byte(TYPE_DICT, p);\r
+        /* This one is NULL object terminated! */\r
+        pos = 0;\r
+        while (PyDict_Next(v, &pos, &key, &value)) {\r
+            w_object(key, p);\r
+            w_object(value, p);\r
+        }\r
+        w_object((PyObject *)NULL, p);\r
+    }\r
+    else if (PyAnySet_CheckExact(v)) {\r
+        PyObject *value, *it;\r
+\r
+        if (PyObject_TypeCheck(v, &PySet_Type))\r
+            w_byte(TYPE_SET, p);\r
+        else\r
+            w_byte(TYPE_FROZENSET, p);\r
+        n = PyObject_Size(v);\r
+        if (n == -1) {\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+        w_long((long)n, p);\r
+        it = PyObject_GetIter(v);\r
+        if (it == NULL) {\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+        while ((value = PyIter_Next(it)) != NULL) {\r
+            w_object(value, p);\r
+            Py_DECREF(value);\r
+        }\r
+        Py_DECREF(it);\r
+        if (PyErr_Occurred()) {\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+    }\r
+    else if (PyCode_Check(v)) {\r
+        PyCodeObject *co = (PyCodeObject *)v;\r
+        w_byte(TYPE_CODE, p);\r
+        w_long(co->co_argcount, p);\r
+        w_long(co->co_nlocals, p);\r
+        w_long(co->co_stacksize, p);\r
+        w_long(co->co_flags, p);\r
+        w_object(co->co_code, p);\r
+        w_object(co->co_consts, p);\r
+        w_object(co->co_names, p);\r
+        w_object(co->co_varnames, p);\r
+        w_object(co->co_freevars, p);\r
+        w_object(co->co_cellvars, p);\r
+        w_object(co->co_filename, p);\r
+        w_object(co->co_name, p);\r
+        w_long(co->co_firstlineno, p);\r
+        w_object(co->co_lnotab, p);\r
+    }\r
+    else if (PyObject_CheckReadBuffer(v)) {\r
+        /* Write unknown buffer-style objects as a string */\r
+        char *s;\r
+        PyBufferProcs *pb = v->ob_type->tp_as_buffer;\r
+        w_byte(TYPE_STRING, p);\r
+        n = (*pb->bf_getreadbuffer)(v, 0, (void **)&s);\r
+        if (n > INT_MAX) {\r
+            p->depth--;\r
+            p->error = WFERR_UNMARSHALLABLE;\r
+            return;\r
+        }\r
+        w_long((long)n, p);\r
+        w_string(s, (int)n, p);\r
+    }\r
+    else {\r
+        w_byte(TYPE_UNKNOWN, p);\r
+        p->error = WFERR_UNMARSHALLABLE;\r
+    }\r
+   exit:\r
+    p->depth--;\r
+}\r
+\r
+/* version currently has no effect for writing longs. */\r
+void\r
+PyMarshal_WriteLongToFile(long x, FILE *fp, int version)\r
+{\r
+    WFILE wf;\r
+    wf.fp = fp;\r
+    wf.error = WFERR_OK;\r
+    wf.depth = 0;\r
+    wf.strings = NULL;\r
+    wf.version = version;\r
+    w_long(x, &wf);\r
+}\r
+\r
+void\r
+PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)\r
+{\r
+    WFILE wf;\r
+    wf.fp = fp;\r
+    wf.error = WFERR_OK;\r
+    wf.depth = 0;\r
+    wf.strings = (version > 0) ? PyDict_New() : NULL;\r
+    wf.version = version;\r
+    w_object(x, &wf);\r
+    Py_XDECREF(wf.strings);\r
+}\r
+\r
+typedef WFILE RFILE; /* Same struct with different invariants */\r
+\r
+#define rs_byte(p) (((p)->ptr < (p)->end) ? (unsigned char)*(p)->ptr++ : EOF)\r
+\r
+#define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p))\r
+\r
+static int\r
+r_string(char *s, int n, RFILE *p)\r
+{\r
+    if (p->fp != NULL)\r
+        /* The result fits into int because it must be <=n. */\r
+        return (int)fread(s, 1, n, p->fp);\r
+    if (p->end - p->ptr < n)\r
+        n = (int)(p->end - p->ptr);\r
+    memcpy(s, p->ptr, n);\r
+    p->ptr += n;\r
+    return n;\r
+}\r
+\r
+static int\r
+r_short(RFILE *p)\r
+{\r
+    register short x;\r
+    x = r_byte(p);\r
+    x |= r_byte(p) << 8;\r
+    /* Sign-extension, in case short greater than 16 bits */\r
+    x |= -(x & 0x8000);\r
+    return x;\r
+}\r
+\r
+static long\r
+r_long(RFILE *p)\r
+{\r
+    register long x;\r
+    register FILE *fp = p->fp;\r
+    if (fp) {\r
+        x = getc(fp);\r
+        x |= (long)getc(fp) << 8;\r
+        x |= (long)getc(fp) << 16;\r
+        x |= (long)getc(fp) << 24;\r
+    }\r
+    else {\r
+        x = rs_byte(p);\r
+        x |= (long)rs_byte(p) << 8;\r
+        x |= (long)rs_byte(p) << 16;\r
+        x |= (long)rs_byte(p) << 24;\r
+    }\r
+#if SIZEOF_LONG > 4\r
+    /* Sign extension for 64-bit machines */\r
+    x |= -(x & 0x80000000L);\r
+#endif\r
+    return x;\r
+}\r
+\r
+/* r_long64 deals with the TYPE_INT64 code.  On a machine with\r
+   sizeof(long) > 4, it returns a Python int object, else a Python long\r
+   object.  Note that w_long64 writes out TYPE_INT if 32 bits is enough,\r
+   so there's no inefficiency here in returning a PyLong on 32-bit boxes\r
+   for everything written via TYPE_INT64 (i.e., if an int is written via\r
+   TYPE_INT64, it *needs* more than 32 bits).\r
+*/\r
+static PyObject *\r
+r_long64(RFILE *p)\r
+{\r
+    long lo4 = r_long(p);\r
+    long hi4 = r_long(p);\r
+#if SIZEOF_LONG > 4\r
+    long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL);\r
+    return PyInt_FromLong(x);\r
+#else\r
+    unsigned char buf[8];\r
+    int one = 1;\r
+    int is_little_endian = (int)*(char*)&one;\r
+    if (is_little_endian) {\r
+        memcpy(buf, &lo4, 4);\r
+        memcpy(buf+4, &hi4, 4);\r
+    }\r
+    else {\r
+        memcpy(buf, &hi4, 4);\r
+        memcpy(buf+4, &lo4, 4);\r
+    }\r
+    return _PyLong_FromByteArray(buf, 8, is_little_endian, 1);\r
+#endif\r
+}\r
+\r
+static PyObject *\r
+r_PyLong(RFILE *p)\r
+{\r
+    PyLongObject *ob;\r
+    int size, i, j, md, shorts_in_top_digit;\r
+    long n;\r
+    digit d;\r
+\r
+    n = r_long(p);\r
+    if (n == 0)\r
+        return (PyObject *)_PyLong_New(0);\r
+    if (n < -INT_MAX || n > INT_MAX) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                       "bad marshal data (long size out of range)");\r
+        return NULL;\r
+    }\r
+\r
+    size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO;\r
+    shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO;\r
+    ob = _PyLong_New(size);\r
+    if (ob == NULL)\r
+        return NULL;\r
+    Py_SIZE(ob) = n > 0 ? size : -size;\r
+\r
+    for (i = 0; i < size-1; i++) {\r
+        d = 0;\r
+        for (j=0; j < PyLong_MARSHAL_RATIO; j++) {\r
+            md = r_short(p);\r
+            if (md < 0 || md > PyLong_MARSHAL_BASE)\r
+                goto bad_digit;\r
+            d += (digit)md << j*PyLong_MARSHAL_SHIFT;\r
+        }\r
+        ob->ob_digit[i] = d;\r
+    }\r
+    d = 0;\r
+    for (j=0; j < shorts_in_top_digit; j++) {\r
+        md = r_short(p);\r
+        if (md < 0 || md > PyLong_MARSHAL_BASE)\r
+            goto bad_digit;\r
+        /* topmost marshal digit should be nonzero */\r
+        if (md == 0 && j == shorts_in_top_digit - 1) {\r
+            Py_DECREF(ob);\r
+            PyErr_SetString(PyExc_ValueError,\r
+                "bad marshal data (unnormalized long data)");\r
+            return NULL;\r
+        }\r
+        d += (digit)md << j*PyLong_MARSHAL_SHIFT;\r
+    }\r
+    /* top digit should be nonzero, else the resulting PyLong won't be\r
+       normalized */\r
+    ob->ob_digit[size-1] = d;\r
+    return (PyObject *)ob;\r
+  bad_digit:\r
+    Py_DECREF(ob);\r
+    PyErr_SetString(PyExc_ValueError,\r
+                    "bad marshal data (digit out of range in long)");\r
+    return NULL;\r
+}\r
+\r
+\r
+static PyObject *\r
+r_object(RFILE *p)\r
+{\r
+    /* NULL is a valid return value, it does not necessarily means that\r
+       an exception is set. */\r
+    PyObject *v, *v2;\r
+    long i, n;\r
+    int type = r_byte(p);\r
+    PyObject *retval;\r
+\r
+    p->depth++;\r
+\r
+    if (p->depth > MAX_MARSHAL_STACK_DEPTH) {\r
+        p->depth--;\r
+        PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");\r
+        return NULL;\r
+    }\r
+\r
+    switch (type) {\r
+\r
+    case EOF:\r
+        PyErr_SetString(PyExc_EOFError,\r
+                        "EOF read where object expected");\r
+        retval = NULL;\r
+        break;\r
+\r
+    case TYPE_NULL:\r
+        retval = NULL;\r
+        break;\r
+\r
+    case TYPE_NONE:\r
+        Py_INCREF(Py_None);\r
+        retval = Py_None;\r
+        break;\r
+\r
+    case TYPE_STOPITER:\r
+        Py_INCREF(PyExc_StopIteration);\r
+        retval = PyExc_StopIteration;\r
+        break;\r
+\r
+    case TYPE_ELLIPSIS:\r
+        Py_INCREF(Py_Ellipsis);\r
+        retval = Py_Ellipsis;\r
+        break;\r
+\r
+    case TYPE_FALSE:\r
+        Py_INCREF(Py_False);\r
+        retval = Py_False;\r
+        break;\r
+\r
+    case TYPE_TRUE:\r
+        Py_INCREF(Py_True);\r
+        retval = Py_True;\r
+        break;\r
+\r
+    case TYPE_INT:\r
+        retval = PyInt_FromLong(r_long(p));\r
+        break;\r
+\r
+    case TYPE_INT64:\r
+        retval = r_long64(p);\r
+        break;\r
+\r
+    case TYPE_LONG:\r
+        retval = r_PyLong(p);\r
+        break;\r
+\r
+    case TYPE_FLOAT:\r
+        {\r
+            char buf[256];\r
+            double dx;\r
+            n = r_byte(p);\r
+            if (n == EOF || r_string(buf, (int)n, p) != n) {\r
+                PyErr_SetString(PyExc_EOFError,\r
+                    "EOF read where object expected");\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            buf[n] = '\0';\r
+            dx = PyOS_string_to_double(buf, NULL, NULL);\r
+            if (dx == -1.0 && PyErr_Occurred()) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            retval = PyFloat_FromDouble(dx);\r
+            break;\r
+        }\r
+\r
+    case TYPE_BINARY_FLOAT:\r
+        {\r
+            unsigned char buf[8];\r
+            double x;\r
+            if (r_string((char*)buf, 8, p) != 8) {\r
+                PyErr_SetString(PyExc_EOFError,\r
+                    "EOF read where object expected");\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            x = _PyFloat_Unpack8(buf, 1);\r
+            if (x == -1.0 && PyErr_Occurred()) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            retval = PyFloat_FromDouble(x);\r
+            break;\r
+        }\r
+\r
+#ifndef WITHOUT_COMPLEX\r
+    case TYPE_COMPLEX:\r
+        {\r
+            char buf[256];\r
+            Py_complex c;\r
+            n = r_byte(p);\r
+            if (n == EOF || r_string(buf, (int)n, p) != n) {\r
+                PyErr_SetString(PyExc_EOFError,\r
+                    "EOF read where object expected");\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            buf[n] = '\0';\r
+            c.real = PyOS_string_to_double(buf, NULL, NULL);\r
+            if (c.real == -1.0 && PyErr_Occurred()) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            n = r_byte(p);\r
+            if (n == EOF || r_string(buf, (int)n, p) != n) {\r
+                PyErr_SetString(PyExc_EOFError,\r
+                    "EOF read where object expected");\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            buf[n] = '\0';\r
+            c.imag = PyOS_string_to_double(buf, NULL, NULL);\r
+            if (c.imag == -1.0 && PyErr_Occurred()) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            retval = PyComplex_FromCComplex(c);\r
+            break;\r
+        }\r
+\r
+    case TYPE_BINARY_COMPLEX:\r
+        {\r
+            unsigned char buf[8];\r
+            Py_complex c;\r
+            if (r_string((char*)buf, 8, p) != 8) {\r
+                PyErr_SetString(PyExc_EOFError,\r
+                    "EOF read where object expected");\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            c.real = _PyFloat_Unpack8(buf, 1);\r
+            if (c.real == -1.0 && PyErr_Occurred()) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            if (r_string((char*)buf, 8, p) != 8) {\r
+                PyErr_SetString(PyExc_EOFError,\r
+                    "EOF read where object expected");\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            c.imag = _PyFloat_Unpack8(buf, 1);\r
+            if (c.imag == -1.0 && PyErr_Occurred()) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+            retval = PyComplex_FromCComplex(c);\r
+            break;\r
+        }\r
+#endif\r
+\r
+    case TYPE_INTERNED:\r
+    case TYPE_STRING:\r
+        n = r_long(p);\r
+        if (n < 0 || n > INT_MAX) {\r
+            PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        v = PyString_FromStringAndSize((char *)NULL, n);\r
+        if (v == NULL) {\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        if (r_string(PyString_AS_STRING(v), (int)n, p) != n) {\r
+            Py_DECREF(v);\r
+            PyErr_SetString(PyExc_EOFError,\r
+                            "EOF read where object expected");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        if (type == TYPE_INTERNED) {\r
+            PyString_InternInPlace(&v);\r
+            if (PyList_Append(p->strings, v) < 0) {\r
+                retval = NULL;\r
+                break;\r
+            }\r
+        }\r
+        retval = v;\r
+        break;\r
+\r
+    case TYPE_STRINGREF:\r
+        n = r_long(p);\r
+        if (n < 0 || n >= PyList_GET_SIZE(p->strings)) {\r
+            PyErr_SetString(PyExc_ValueError, "bad marshal data (string ref out of range)");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        v = PyList_GET_ITEM(p->strings, n);\r
+        Py_INCREF(v);\r
+        retval = v;\r
+        break;\r
+\r
+#ifdef Py_USING_UNICODE\r
+    case TYPE_UNICODE:\r
+        {\r
+        char *buffer;\r
+\r
+        n = r_long(p);\r
+        if (n < 0 || n > INT_MAX) {\r
+            PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        buffer = PyMem_NEW(char, n);\r
+        if (buffer == NULL) {\r
+            retval = PyErr_NoMemory();\r
+            break;\r
+        }\r
+        if (r_string(buffer, (int)n, p) != n) {\r
+            PyMem_DEL(buffer);\r
+            PyErr_SetString(PyExc_EOFError,\r
+                "EOF read where object expected");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        v = PyUnicode_DecodeUTF8(buffer, n, NULL);\r
+        PyMem_DEL(buffer);\r
+        retval = v;\r
+        break;\r
+        }\r
+#endif\r
+\r
+    case TYPE_TUPLE:\r
+        n = r_long(p);\r
+        if (n < 0 || n > INT_MAX) {\r
+            PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        v = PyTuple_New((int)n);\r
+        if (v == NULL) {\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        for (i = 0; i < n; i++) {\r
+            v2 = r_object(p);\r
+            if ( v2 == NULL ) {\r
+                if (!PyErr_Occurred())\r
+                    PyErr_SetString(PyExc_TypeError,\r
+                        "NULL object in marshal data for tuple");\r
+                Py_DECREF(v);\r
+                v = NULL;\r
+                break;\r
+            }\r
+            PyTuple_SET_ITEM(v, (int)i, v2);\r
+        }\r
+        retval = v;\r
+        break;\r
+\r
+    case TYPE_LIST:\r
+        n = r_long(p);\r
+        if (n < 0 || n > INT_MAX) {\r
+            PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        v = PyList_New((int)n);\r
+        if (v == NULL) {\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        for (i = 0; i < n; i++) {\r
+            v2 = r_object(p);\r
+            if ( v2 == NULL ) {\r
+                if (!PyErr_Occurred())\r
+                    PyErr_SetString(PyExc_TypeError,\r
+                        "NULL object in marshal data for list");\r
+                Py_DECREF(v);\r
+                v = NULL;\r
+                break;\r
+            }\r
+            PyList_SET_ITEM(v, (int)i, v2);\r
+        }\r
+        retval = v;\r
+        break;\r
+\r
+    case TYPE_DICT:\r
+        v = PyDict_New();\r
+        if (v == NULL) {\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        for (;;) {\r
+            PyObject *key, *val;\r
+            key = r_object(p);\r
+            if (key == NULL)\r
+                break;\r
+            val = r_object(p);\r
+            if (val != NULL)\r
+                PyDict_SetItem(v, key, val);\r
+            Py_DECREF(key);\r
+            Py_XDECREF(val);\r
+        }\r
+        if (PyErr_Occurred()) {\r
+            Py_DECREF(v);\r
+            v = NULL;\r
+        }\r
+        retval = v;\r
+        break;\r
+\r
+    case TYPE_SET:\r
+    case TYPE_FROZENSET:\r
+        n = r_long(p);\r
+        if (n < 0 || n > INT_MAX) {\r
+            PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);\r
+        if (v == NULL) {\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        for (i = 0; i < n; i++) {\r
+            v2 = r_object(p);\r
+            if ( v2 == NULL ) {\r
+                if (!PyErr_Occurred())\r
+                    PyErr_SetString(PyExc_TypeError,\r
+                        "NULL object in marshal data for set");\r
+                Py_DECREF(v);\r
+                v = NULL;\r
+                break;\r
+            }\r
+            if (PySet_Add(v, v2) == -1) {\r
+                Py_DECREF(v);\r
+                Py_DECREF(v2);\r
+                v = NULL;\r
+                break;\r
+            }\r
+            Py_DECREF(v2);\r
+        }\r
+        retval = v;\r
+        break;\r
+\r
+    case TYPE_CODE:\r
+        if (PyEval_GetRestricted()) {\r
+            PyErr_SetString(PyExc_RuntimeError,\r
+                "cannot unmarshal code objects in "\r
+                "restricted execution mode");\r
+            retval = NULL;\r
+            break;\r
+        }\r
+        else {\r
+            int argcount;\r
+            int nlocals;\r
+            int stacksize;\r
+            int flags;\r
+            PyObject *code = NULL;\r
+            PyObject *consts = NULL;\r
+            PyObject *names = NULL;\r
+            PyObject *varnames = NULL;\r
+            PyObject *freevars = NULL;\r
+            PyObject *cellvars = NULL;\r
+            PyObject *filename = NULL;\r
+            PyObject *name = NULL;\r
+            int firstlineno;\r
+            PyObject *lnotab = NULL;\r
+\r
+            v = NULL;\r
+\r
+            /* XXX ignore long->int overflows for now */\r
+            argcount = (int)r_long(p);\r
+            nlocals = (int)r_long(p);\r
+            stacksize = (int)r_long(p);\r
+            flags = (int)r_long(p);\r
+            code = r_object(p);\r
+            if (code == NULL)\r
+                goto code_error;\r
+            consts = r_object(p);\r
+            if (consts == NULL)\r
+                goto code_error;\r
+            names = r_object(p);\r
+            if (names == NULL)\r
+                goto code_error;\r
+            varnames = r_object(p);\r
+            if (varnames == NULL)\r
+                goto code_error;\r
+            freevars = r_object(p);\r
+            if (freevars == NULL)\r
+                goto code_error;\r
+            cellvars = r_object(p);\r
+            if (cellvars == NULL)\r
+                goto code_error;\r
+            filename = r_object(p);\r
+            if (filename == NULL)\r
+                goto code_error;\r
+            name = r_object(p);\r
+            if (name == NULL)\r
+                goto code_error;\r
+            firstlineno = (int)r_long(p);\r
+            lnotab = r_object(p);\r
+            if (lnotab == NULL)\r
+                goto code_error;\r
+\r
+            v = (PyObject *) PyCode_New(\r
+                            argcount, nlocals, stacksize, flags,\r
+                            code, consts, names, varnames,\r
+                            freevars, cellvars, filename, name,\r
+                            firstlineno, lnotab);\r
+\r
+          code_error:\r
+            Py_XDECREF(code);\r
+            Py_XDECREF(consts);\r
+            Py_XDECREF(names);\r
+            Py_XDECREF(varnames);\r
+            Py_XDECREF(freevars);\r
+            Py_XDECREF(cellvars);\r
+            Py_XDECREF(filename);\r
+            Py_XDECREF(name);\r
+            Py_XDECREF(lnotab);\r
+\r
+        }\r
+        retval = v;\r
+        break;\r
+\r
+    default:\r
+        /* Bogus data got written, which isn't ideal.\r
+           This will let you keep working and recover. */\r
+        PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)");\r
+        retval = NULL;\r
+        break;\r
+\r
+    }\r
+    p->depth--;\r
+    return retval;\r
+}\r
+\r
+static PyObject *\r
+read_object(RFILE *p)\r
+{\r
+    PyObject *v;\r
+    if (PyErr_Occurred()) {\r
+        fprintf(stderr, "XXX readobject called with exception set\n");\r
+        return NULL;\r
+    }\r
+    v = r_object(p);\r
+    if (v == NULL && !PyErr_Occurred())\r
+        PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");\r
+    return v;\r
+}\r
+\r
+int\r
+PyMarshal_ReadShortFromFile(FILE *fp)\r
+{\r
+    RFILE rf;\r
+    assert(fp);\r
+    rf.fp = fp;\r
+    rf.strings = NULL;\r
+    rf.end = rf.ptr = NULL;\r
+    return r_short(&rf);\r
+}\r
+\r
+long\r
+PyMarshal_ReadLongFromFile(FILE *fp)\r
+{\r
+    RFILE rf;\r
+    rf.fp = fp;\r
+    rf.strings = NULL;\r
+    rf.ptr = rf.end = NULL;\r
+    return r_long(&rf);\r
+}\r
+\r
+#ifdef HAVE_FSTAT\r
+/* Return size of file in bytes; < 0 if unknown. */\r
+static off_t\r
+getfilesize(FILE *fp)\r
+{\r
+    struct stat st;\r
+    if (fstat(fileno(fp), &st) != 0)\r
+        return -1;\r
+    else\r
+        return st.st_size;\r
+}\r
+#endif\r
+\r
+/* If we can get the size of the file up-front, and it's reasonably small,\r
+ * read it in one gulp and delegate to ...FromString() instead.  Much quicker\r
+ * than reading a byte at a time from file; speeds .pyc imports.\r
+ * CAUTION:  since this may read the entire remainder of the file, don't\r
+ * call it unless you know you're done with the file.\r
+ */\r
+PyObject *\r
+PyMarshal_ReadLastObjectFromFile(FILE *fp)\r
+{\r
+/* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */\r
+#define REASONABLE_FILE_LIMIT (1L << 18)\r
+#ifdef HAVE_FSTAT\r
+    off_t filesize;\r
+    filesize = getfilesize(fp);\r
+    if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) {\r
+        char* pBuf = (char *)PyMem_MALLOC(filesize);\r
+        if (pBuf != NULL) {\r
+            PyObject* v;\r
+            size_t n;\r
+            /* filesize must fit into an int, because it\r
+               is smaller than REASONABLE_FILE_LIMIT */\r
+            n = fread(pBuf, 1, (int)filesize, fp);\r
+            v = PyMarshal_ReadObjectFromString(pBuf, n);\r
+            PyMem_FREE(pBuf);\r
+            return v;\r
+        }\r
+\r
+    }\r
+#endif\r
+    /* We don't have fstat, or we do but the file is larger than\r
+     * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time.\r
+     */\r
+    return PyMarshal_ReadObjectFromFile(fp);\r
+\r
+#undef REASONABLE_FILE_LIMIT\r
+}\r
+\r
+PyObject *\r
+PyMarshal_ReadObjectFromFile(FILE *fp)\r
+{\r
+    RFILE rf;\r
+    PyObject *result;\r
+    rf.fp = fp;\r
+    rf.strings = PyList_New(0);\r
+    rf.depth = 0;\r
+    rf.ptr = rf.end = NULL;\r
+    result = r_object(&rf);\r
+    Py_DECREF(rf.strings);\r
+    return result;\r
+}\r
+\r
+PyObject *\r
+PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len)\r
+{\r
+    RFILE rf;\r
+    PyObject *result;\r
+    rf.fp = NULL;\r
+    rf.ptr = str;\r
+    rf.end = str + len;\r
+    rf.strings = PyList_New(0);\r
+    rf.depth = 0;\r
+    result = r_object(&rf);\r
+    Py_DECREF(rf.strings);\r
+    return result;\r
+}\r
+\r
+static void\r
+set_error(int error)\r
+{\r
+    switch (error) {\r
+    case WFERR_NOMEMORY:\r
+        PyErr_NoMemory();\r
+        break;\r
+    case WFERR_UNMARSHALLABLE:\r
+        PyErr_SetString(PyExc_ValueError, "unmarshallable object");\r
+        break;\r
+    case WFERR_NESTEDTOODEEP:\r
+    default:\r
+        PyErr_SetString(PyExc_ValueError,\r
+            "object too deeply nested to marshal");\r
+        break;\r
+    }\r
+}\r
+\r
+PyObject *\r
+PyMarshal_WriteObjectToString(PyObject *x, int version)\r
+{\r
+    WFILE wf;\r
+    wf.fp = NULL;\r
+    wf.str = PyString_FromStringAndSize((char *)NULL, 50);\r
+    if (wf.str == NULL)\r
+        return NULL;\r
+    wf.ptr = PyString_AS_STRING((PyStringObject *)wf.str);\r
+    wf.end = wf.ptr + PyString_Size(wf.str);\r
+    wf.error = WFERR_OK;\r
+    wf.depth = 0;\r
+    wf.version = version;\r
+    wf.strings = (version > 0) ? PyDict_New() : NULL;\r
+    w_object(x, &wf);\r
+    Py_XDECREF(wf.strings);\r
+    if (wf.str != NULL) {\r
+        char *base = PyString_AS_STRING((PyStringObject *)wf.str);\r
+        if (wf.ptr - base > PY_SSIZE_T_MAX) {\r
+            Py_DECREF(wf.str);\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "too much marshall data for a string");\r
+            return NULL;\r
+        }\r
+        if (_PyString_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)))\r
+            return NULL;\r
+    }\r
+    if (wf.error != WFERR_OK) {\r
+        Py_XDECREF(wf.str);\r
+        set_error(wf.error);\r
+        return NULL;\r
+    }\r
+    return wf.str;\r
+}\r
+\r
+/* And an interface for Python programs... */\r
+\r
+static PyObject *\r
+marshal_dump(PyObject *self, PyObject *args)\r
+{\r
+    WFILE wf;\r
+    PyObject *x;\r
+    PyObject *f;\r
+    int version = Py_MARSHAL_VERSION;\r
+    if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version))\r
+        return NULL;\r
+    if (!PyFile_Check(f)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "marshal.dump() 2nd arg must be file");\r
+        return NULL;\r
+    }\r
+    wf.fp = PyFile_AsFile(f);\r
+    wf.str = NULL;\r
+    wf.ptr = wf.end = NULL;\r
+    wf.error = WFERR_OK;\r
+    wf.depth = 0;\r
+    wf.strings = (version > 0) ? PyDict_New() : 0;\r
+    wf.version = version;\r
+    w_object(x, &wf);\r
+    Py_XDECREF(wf.strings);\r
+    if (wf.error != WFERR_OK) {\r
+        set_error(wf.error);\r
+        return NULL;\r
+    }\r
+    Py_INCREF(Py_None);\r
+    return Py_None;\r
+}\r
+\r
+PyDoc_STRVAR(dump_doc,\r
+"dump(value, file[, version])\n\\r
+\n\\r
+Write the value on the open file. The value must be a supported type.\n\\r
+The file must be an open file object such as sys.stdout or returned by\n\\r
+open() or os.popen(). It must be opened in binary mode ('wb' or 'w+b').\n\\r
+\n\\r
+If the value has (or contains an object that has) an unsupported type, a\n\\r
+ValueError exception is raised — but garbage data will also be written\n\\r
+to the file. The object will not be properly read back by load()\n\\r
+\n\\r
+New in version 2.4: The version argument indicates the data format that\n\\r
+dump should use.");\r
+\r
+static PyObject *\r
+marshal_load(PyObject *self, PyObject *f)\r
+{\r
+    RFILE rf;\r
+    PyObject *result;\r
+    if (!PyFile_Check(f)) {\r
+        PyErr_SetString(PyExc_TypeError,\r
+                        "marshal.load() arg must be file");\r
+        return NULL;\r
+    }\r
+    rf.fp = PyFile_AsFile(f);\r
+    rf.strings = PyList_New(0);\r
+    rf.depth = 0;\r
+    result = read_object(&rf);\r
+    Py_DECREF(rf.strings);\r
+    return result;\r
+}\r
+\r
+PyDoc_STRVAR(load_doc,\r
+"load(file)\n\\r
+\n\\r
+Read one value from the open file and return it. If no valid value is\n\\r
+read (e.g. because the data has a different Python version’s\n\\r
+incompatible marshal format), raise EOFError, ValueError or TypeError.\n\\r
+The file must be an open file object opened in binary mode ('rb' or\n\\r
+'r+b').\n\\r
+\n\\r
+Note: If an object containing an unsupported type was marshalled with\n\\r
+dump(), load() will substitute None for the unmarshallable type.");\r
+\r
+\r
+static PyObject *\r
+marshal_dumps(PyObject *self, PyObject *args)\r
+{\r
+    PyObject *x;\r
+    int version = Py_MARSHAL_VERSION;\r
+    if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version))\r
+        return NULL;\r
+    return PyMarshal_WriteObjectToString(x, version);\r
+}\r
+\r
+PyDoc_STRVAR(dumps_doc,\r
+"dumps(value[, version])\n\\r
+\n\\r
+Return the string that would be written to a file by dump(value, file).\n\\r
+The value must be a supported type. Raise a ValueError exception if\n\\r
+value has (or contains an object that has) an unsupported type.\n\\r
+\n\\r
+New in version 2.4: The version argument indicates the data format that\n\\r
+dumps should use.");\r
+\r
+\r
+static PyObject *\r
+marshal_loads(PyObject *self, PyObject *args)\r
+{\r
+    RFILE rf;\r
+    char *s;\r
+    Py_ssize_t n;\r
+    PyObject* result;\r
+    if (!PyArg_ParseTuple(args, "s#:loads", &s, &n))\r
+        return NULL;\r
+    rf.fp = NULL;\r
+    rf.ptr = s;\r
+    rf.end = s + n;\r
+    rf.strings = PyList_New(0);\r
+    rf.depth = 0;\r
+    result = read_object(&rf);\r
+    Py_DECREF(rf.strings);\r
+    return result;\r
+}\r
+\r
+PyDoc_STRVAR(loads_doc,\r
+"loads(string)\n\\r
+\n\\r
+Convert the string to a value. If no valid value is found, raise\n\\r
+EOFError, ValueError or TypeError. Extra characters in the string are\n\\r
+ignored.");\r
+\r
+static PyMethodDef marshal_methods[] = {\r
+    {"dump",            marshal_dump,   METH_VARARGS,   dump_doc},\r
+    {"load",            marshal_load,   METH_O,         load_doc},\r
+    {"dumps",           marshal_dumps,  METH_VARARGS,   dumps_doc},\r
+    {"loads",           marshal_loads,  METH_VARARGS,   loads_doc},\r
+    {NULL,              NULL}           /* sentinel */\r
+};\r
+\r
+PyDoc_STRVAR(marshal_doc,\r
+"This module contains functions that can read and write Python values in\n\\r
+a binary format. The format is specific to Python, but independent of\n\\r
+machine architecture issues.\n\\r
+\n\\r
+Not all Python object types are supported; in general, only objects\n\\r
+whose value is independent from a particular invocation of Python can be\n\\r
+written and read by this module. The following types are supported:\n\\r
+None, integers, long integers, floating point numbers, strings, Unicode\n\\r
+objects, tuples, lists, sets, dictionaries, and code objects, where it\n\\r
+should be understood that tuples, lists and dictionaries are only\n\\r
+supported as long as the values contained therein are themselves\n\\r
+supported; and recursive lists and dictionaries should not be written\n\\r
+(they will cause infinite loops).\n\\r
+\n\\r
+Variables:\n\\r
+\n\\r
+version -- indicates the format that the module uses. Version 0 is the\n\\r
+    historical format, version 1 (added in Python 2.4) shares interned\n\\r
+    strings and version 2 (added in Python 2.5) uses a binary format for\n\\r
+    floating point numbers. (New in version 2.4)\n\\r
+\n\\r
+Functions:\n\\r
+\n\\r
+dump() -- write value to a file\n\\r
+load() -- read value from a file\n\\r
+dumps() -- write value to a string\n\\r
+loads() -- read value from a string");\r
+\r
+\r
+PyMODINIT_FUNC\r
+PyMarshal_Init(void)\r
+{\r
+    PyObject *mod = Py_InitModule3("marshal", marshal_methods,\r
+        marshal_doc);\r
+    if (mod == NULL)\r
+        return;\r
+    PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION);\r
+}\r