📄 intobject.c
字号:
/* Portions Copyright (c) 2005 Nokia Corporation */
/* Integer object implementation */
#include "Python.h"
#include <ctype.h>
long
PyInt_GetMax(void)
{
return LONG_MAX; /* To initialize sys.maxint */
}
/* Standard Booleans */
#ifndef SYMBIAN
const PyIntObject _Py_ZeroStruct = {
PyObject_HEAD_INIT(&c_PyInt_Type)
0
};
const PyIntObject _Py_TrueStruct = {
PyObject_HEAD_INIT(&c_PyInt_Type)
1
};
#else
extern void _Py_Zero_Init()
{
SPy_Python_globals* pyglobals = PYTHON_GLOBALS; // avoid TLS reads
#ifdef Py_TRACE_REFS
(pyglobals->_Py_ZeroStruct)._ob_next = 0;
(pyglobals->_Py_ZeroStruct)._ob_prev = 0;
#endif
(pyglobals->_Py_ZeroStruct).ob_refcnt = 1;
(pyglobals->_Py_ZeroStruct).ob_type = &PyInt_Type;
(pyglobals->_Py_ZeroStruct).ob_ival = 0;
return;
}
extern void _Py_True_Init()
{
SPy_Python_globals* pyglobals = PYTHON_GLOBALS; // avoid TLS reads
#ifdef Py_TRACE_REFS
(pyglobals->_Py_TrueStruct)._ob_next = 0;
(pyglobals->_Py_TrueStruct)._ob_prev = 0;
#endif
(pyglobals->_Py_TrueStruct).ob_refcnt = 1;
(pyglobals->_Py_TrueStruct).ob_type = &PyInt_Type;
(pyglobals->_Py_TrueStruct).ob_ival = 1;
return;
}
#endif /* SYMBIAN */
/* Return 1 if exception raised, 0 if caller should retry using longs */
static int
err_ovf(char *msg)
{
if (PyErr_Warn(PyExc_OverflowWarning, msg) < 0) {
if (PyErr_ExceptionMatches(PyExc_OverflowWarning))
PyErr_SetString(PyExc_OverflowError, msg);
return 1;
}
else
return 0;
}
/* Integers are quite normal objects, to make object handling uniform.
(Using odd pointers to represent integers would save much space
but require extra checks for this special case throughout the code.)
Since, a typical Python program spends much of its time allocating
and deallocating integers, these operations should be very fast.
Therefore we use a dedicated allocation scheme with a much lower
overhead (in space and time) than straight malloc(): a simple
dedicated free list, filled when necessary with memory from malloc().
*/
#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
#define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
struct _intblock {
struct _intblock *next;
PyIntObject objects[N_INTOBJECTS];
};
typedef struct _intblock PyIntBlock;
#ifndef SYMBIAN
static PyIntBlock *block_list = NULL;
static PyIntObject *free_list = NULL;
#else
#define block_list ((PyIntBlock*)(pyglobals->INTOBJ_block_list))
#define free_list ((PyIntObject*)(pyglobals->INTOBJ_free_list))
#endif
static PyIntObject *
fill_free_list(void)
{
PyIntObject *p, *q;
#ifdef SYMBIAN
SPy_Python_globals* pyglobals = PYTHON_GLOBALS; // avoid TLS reads
#endif
/* XXX Int blocks escape the object heap. Use PyObject_MALLOC ??? */
p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
if (p == NULL)
return (PyIntObject *) PyErr_NoMemory();
((PyIntBlock *)p)->next = block_list;
block_list = (PyIntBlock *)p;
p = &((PyIntBlock *)p)->objects[0];
q = p + N_INTOBJECTS;
while (--q > p)
q->ob_type = (struct _typeobject *)(q-1);
q->ob_type = NULL;
return p + N_INTOBJECTS - 1;
}
#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS 100
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS 1
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
can be shared.
The integers that are saved are those in the range
-NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/
#ifndef SYMBIAN
static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
#else
#define small_ints (pyglobals->small_ints)
#endif
#endif
#ifdef COUNT_ALLOCS
int quick_int_allocs, quick_neg_int_allocs;
#endif
DL_EXPORT(PyObject *)
PyInt_FromLong(long ival)
{
register PyIntObject *v;
#ifdef SYMBIAN
SPy_Python_globals* pyglobals = PYTHON_GLOBALS; // avoid TLS reads
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS &&
(v = small_ints[ival + NSMALLNEGINTS]) != NULL) {
Py_INCREF(v);
#ifdef COUNT_ALLOCS
if (ival >= 0)
quick_int_allocs++;
else
quick_neg_int_allocs++;
#endif
return (PyObject *) v;
}
#endif
if (free_list == NULL) {
if ((free_list = fill_free_list()) == NULL)
return NULL;
}
/* PyObject_New is inlined */
v = free_list;
free_list = (PyIntObject *)v->ob_type;
PyObject_INIT(v, &PyInt_Type);
v->ob_ival = ival;
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
/* save this one for a following allocation */
Py_INCREF(v);
small_ints[ival + NSMALLNEGINTS] = v;
}
#endif
return (PyObject *) v;
}
static void
int_dealloc(PyIntObject *v)
{
#ifdef SYMBIAN
SPy_Python_globals* pyglobals = PYTHON_GLOBALS; // avoid TLS reads
#endif
if (PyInt_CheckExact(v)) {
v->ob_type = (struct _typeobject *)free_list;
free_list = v;
}
else
v->ob_type->tp_free((PyObject *)v);
}
static void
int_free(PyIntObject *v)
{
#ifdef SYMBIAN
SPy_Python_globals* pyglobals = PYTHON_GLOBALS; // avoid TLS reads
#endif
v->ob_type = (struct _typeobject *)free_list;
free_list = v;
}
DL_EXPORT(long)
PyInt_AsLong(register PyObject *op)
{
PyNumberMethods *nb;
PyIntObject *io;
long val;
if (op && PyInt_Check(op))
return PyInt_AS_LONG((PyIntObject*) op);
// XXX:CW32
if (op == NULL || (nb = (PyNumberMethods *)op->ob_type->tp_as_number) == NULL ||
nb->nb_int == NULL) {
PyErr_SetString(PyExc_TypeError, "an integer is required");
return -1;
}
io = (PyIntObject*) (*nb->nb_int) (op);
if (io == NULL)
return -1;
if (!PyInt_Check(io)) {
PyErr_SetString(PyExc_TypeError,
"nb_int should return int object");
return -1;
}
val = PyInt_AS_LONG(io);
Py_DECREF(io);
return val;
}
DL_EXPORT(PyObject *)
PyInt_FromString(char *s, char **pend, int base)
{
char *end;
long x;
char buffer[256]; /* For errors */
if ((base != 0 && base < 2) || base > 36) {
PyErr_SetString(PyExc_ValueError, "int() base must be >= 2 and <= 36");
return NULL;
}
while (*s && isspace(Py_CHARMASK(*s)))
s++;
errno = 0;
if (base == 0 && s[0] == '0')
x = (long) PyOS_strtoul(s, &end, base);
else
x = PyOS_strtol(s, &end, base);
if (end == s || !isalnum(Py_CHARMASK(end[-1])))
goto bad;
while (*end && isspace(Py_CHARMASK(*end)))
end++;
if (*end != '\0') {
bad:
PyOS_snprintf(buffer, sizeof(buffer),
"invalid literal for int(): %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
return NULL;
}
else if (errno != 0) {
PyOS_snprintf(buffer, sizeof(buffer),
"int() literal too large: %.200s", s);
PyErr_SetString(PyExc_ValueError, buffer);
return NULL;
}
if (pend)
*pend = end;
return PyInt_FromLong(x);
}
#ifdef Py_USING_UNICODE
DL_EXPORT(PyObject *)
PyInt_FromUnicode(Py_UNICODE *s, int length, int base)
{
char buffer[256];
if (length >= sizeof(buffer)) {
PyErr_SetString(PyExc_ValueError,
"int() literal too large to convert");
return NULL;
}
if (PyUnicode_EncodeDecimal(s, length, buffer, NULL))
return NULL;
return PyInt_FromString(buffer, NULL, base);
}
#endif
/* Methods */
/* Integers are seen as the "smallest" of all numeric types and thus
don't have any knowledge about conversion of other types to
integers. */
#define CONVERT_TO_LONG(obj, lng) \
if (PyInt_Check(obj)) { \
lng = PyInt_AS_LONG(obj); \
} \
else { \
Py_INCREF(Py_NotImplemented); \
return Py_NotImplemented; \
}
/* ARGSUSED */
static int
int_print(PyIntObject *v, FILE *fp, int flags)
/* flags -- not used but required by interface */
{
fprintf(fp, "%ld", v->ob_ival);
return 0;
}
static PyObject *
int_repr(PyIntObject *v)
{
char buf[64];
PyOS_snprintf(buf, sizeof(buf), "%ld", v->ob_ival);
return PyString_FromString(buf);
}
static int
int_compare(PyIntObject *v, PyIntObject *w)
{
register long i = v->ob_ival;
register long j = w->ob_ival;
return (i < j) ? -1 : (i > j) ? 1 : 0;
}
static long
int_hash(PyIntObject *v)
{
/* XXX If this is changed, you also need to change the way
Python's long, float and complex types are hashed. */
long x = v -> ob_ival;
if (x == -1)
x = -2;
return x;
}
static PyObject *
int_add(PyIntObject *v, PyIntObject *w)
{
register long a, b, x;
CONVERT_TO_LONG(v, a);
CONVERT_TO_LONG(w, b);
x = a + b;
if ((x^a) >= 0 || (x^b) >= 0)
return PyInt_FromLong(x);
if (err_ovf("integer addition"))
return NULL;
return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
}
static PyObject *
int_sub(PyIntObject *v, PyIntObject *w)
{
register long a, b, x;
CONVERT_TO_LONG(v, a);
CONVERT_TO_LONG(w, b);
x = a - b;
if ((x^a) >= 0 || (x^~b) >= 0)
return PyInt_FromLong(x);
if (err_ovf("integer subtraction"))
return NULL;
return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
(PyObject *)w);
}
/*
Integer overflow checking for * is painful: Python tried a couple ways, but
they didn't work on all platforms, or failed in endcases (a product of
-sys.maxint-1 has been a particular pain).
Here's another way:
The native long product x*y is either exactly right or *way* off, being
just the last n bits of the true product, where n is the number of bits
in a long (the delivered product is the true product plus i*2**n for
some integer i).
The native double product (double)x * (double)y is subject to three
rounding errors: on a sizeof(long)==8 box, each cast to double can lose
info, and even on a sizeof(long)==4 box, the multiplication can lose info.
But, unlike the native long product, it's not in *range* trouble: even
if sizeof(long)==32 (256-bit longs), the product easily fits in the
dynamic range of a double. So the leading 50 (or so) bits of the double
product are correct.
We check these two ways against each other, and declare victory if they're
approximately the same. Else, because the native long product is the only
one that can lose catastrophic amounts of information, it's the native long
product that must have overflowed.
*/
/* Return true if the sq_repeat method should be used */
#define USE_SQ_REPEAT(o) (!PyInt_Check(o) && \
o->ob_type->tp_as_sequence && \
o->ob_type->tp_as_sequence->sq_repeat && \
!(o->ob_type->tp_as_number && \
o->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES && \
o->ob_type->tp_as_number->nb_multiply))
static PyObject *
int_mul(PyObject *v, PyObject *w)
{
long a, b;
long longprod; /* a*b in native long arithmetic */
double doubled_longprod; /* (double)longprod */
double doubleprod; /* (double)a * (double)b */
if (USE_SQ_REPEAT(v)) {
repeat:
/* sequence * int */
a = PyInt_AsLong(w);
#if LONG_MAX != INT_MAX
if (a > INT_MAX) {
PyErr_SetString(PyExc_ValueError,
"sequence repeat count too large");
return NULL;
}
else if (a < INT_MIN)
a = INT_MIN;
/* XXX Why don't I either
- set a to -1 whenever it's negative (after all,
sequence repeat usually treats negative numbers
as zero(); or
- raise an exception when it's less than INT_MIN?
I'm thinking about a hypothetical use case where some
sequence type might use a negative value as a flag of
some kind. In those cases I don't want to break the
code by mapping all negative values to -1. But I also
don't want to break e.g. []*(-sys.maxint), which is
perfectly safe, returning []. As a compromise, I do
map out-of-range negative values.
*/
#endif
return (*v->ob_type->tp_as_sequence->sq_repeat)(v, a);
}
if (USE_SQ_REPEAT(w)) {
PyObject *tmp = v;
v = w;
w = tmp;
goto repeat;
}
CONVERT_TO_LONG(v, a);
CONVERT_TO_LONG(w, b);
longprod = a * b;
doubleprod = (double)a * (double)b;
doubled_longprod = (double)longprod;
/* Fast path for normal case: small multiplicands, and no info
is lost in either method. */
if (doubled_longprod == doubleprod)
return PyInt_FromLong(longprod);
/* Somebody somewhere lost info. Close enough, or way off? Note
that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
The difference either is or isn't significant compared to the
true value (of which doubleprod is a good approximation).
*/
{
const double diff = doubled_longprod - doubleprod;
const double absdiff = diff >= 0.0 ? diff : -diff;
const double absprod = doubleprod >= 0.0 ? doubleprod :
-doubleprod;
/* absdiff/absprod <= 1/32 iff
32 * absdiff <= absprod -- 5 good bits is "close enough" */
if (32.0 * absdiff <= absprod)
return PyInt_FromLong(longprod);
else if (err_ovf("integer multiplication"))
return NULL;
else
return PyLong_Type.tp_as_number->nb_multiply(v, w);
}
}
/* Return type of i_divmod */
enum divmod_result {
DIVMOD_OK, /* Correct result */
DIVMOD_OVERFLOW, /* Overflow, try again using longs */
DIVMOD_ERROR /* Exception raised */
};
static enum divmod_result
i_divmod(register long x, register long y,
long *p_xdivy, long *p_xmody)
{
long xdivy, xmody;
if (y == 0) {
PyErr_SetString(PyExc_ZeroDivisionError,
"integer division or modulo by zero");
return DIVMOD_ERROR;
}
/* (-sys.maxint-1)/-1 is the only overflow case. */
if (y == -1 && x < 0 && x == -x) {
if (err_ovf("integer division"))
return DIVMOD_ERROR;
return DIVMOD_OVERFLOW;
}
xdivy = x / y;
xmody = x - xdivy * y;
/* If the signs of x and y differ, and the remainder is non-0,
* C89 doesn't define whether xdivy is now the floor or the
* ceiling of the infinitely precise quotient. We want the floor,
* and we have it iff the remainder's sign matches y's.
*/
if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
xmody += y;
--xdivy;
assert(xmody && ((y ^ xmody) >= 0));
}
*p_xdivy = xdivy;
*p_xmody = xmody;
return DIVMOD_OK;
}
static PyObject *
int_div(PyIntObject *x, PyIntObject *y)
{
long xi, yi;
long d, m;
CONVERT_TO_LONG(x, xi);
CONVERT_TO_LONG(y, yi);
switch (i_divmod(xi, yi, &d, &m)) {
case DIVMOD_OK:
return PyInt_FromLong(d);
case DIVMOD_OVERFLOW:
return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
(PyObject *)y);
default:
return NULL;
}
}
static PyObject *
int_classic_div(PyIntObject *x, PyIntObject *y)
{
long xi, yi;
long d, m;
CONVERT_TO_LONG(x, xi);
CONVERT_TO_LONG(y, yi);
if (Py_DivisionWarningFlag &&
PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
return NULL;
switch (i_divmod(xi, yi, &d, &m)) {
case DIVMOD_OK:
return PyInt_FromLong(d);
case DIVMOD_OVERFLOW:
return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -