Exemplo n.º 1
0
/* Insert item in external memory list.
 *
 * XXX: Support slice objects and negative indices?
 */
static int em_list_setitem(em_list_t *self, PyObject *key, PyObject *value)
{
    Py_ssize_t index;

    int ret = -1;

    /* Python 3 supports only long integers. */
#if PY_MAJOR_VERSION < 3
    if(PyInt_CheckExact(key))
    {
        index = PyInt_AsSsize_t(key);
        ret = em_list_setitem_safe(self, index, value);
    }
    else if(PyLong_CheckExact(key))
#else
    if(PyLong_CheckExact(key))
#endif
    {
        index = PyLong_AsSsize_t(key);
        ret = em_list_setitem_safe(self, index, value);
    }
    else
        PyErr_SetString(PyExc_TypeError, "Invalid index type");

    return ret;
}
Exemplo n.º 2
0
/* Retrieve item from external memory list.
 *
 * XXX: Support slice objects and negative indices?
 */
static PyObject *em_list_getitem(em_list_t *self, PyObject *key)
{
    Py_ssize_t index;

    PyObject *r = NULL;

    /* Python 3 supports only long integers. */
#if PY_MAJOR_VERSION < 3
    if(PyInt_CheckExact(key))
    {
        index = PyInt_AsSsize_t(key);
        r = em_list_getitem_internal(self, index);
    }
    else if(PyLong_CheckExact(key))
#else
    if(PyLong_CheckExact(key))
#endif
    {
        index = PyLong_AsSsize_t(key);
        r = em_list_getitem_internal(self, index);
    }
    else
        PyErr_SetString(PyExc_TypeError, "Invalid key object type");

    return r;
}
bool BINARY_OPERATION_ADD_LONG_LONG_INPLACE(PyObject **operand1, PyObject *operand2) {
    assert(operand1);
    CHECK_OBJECT(*operand1);
    CHECK_OBJECT(operand2);
    assert(PyLong_CheckExact(*operand1));
    assert(PyLong_CheckExact(operand2));

    // TODO: Consider adding this shortcut, we might often be able to use
    // existing values at least in case of smaller right hand side, but it
    // may equally often not work out and not be worth it. CPython doesn't
    // try it.
#if 0
    // Adding floats to a new float could get special code too.
    if (Py_REFCNT(*operand1) == 1) {
        return LONG_ADD_INCREMENTAL(operand1, operand2);
    }
#endif

    PyObject *result = PyNumber_InPlaceAdd(*operand1, operand2);

    if (unlikely(result == NULL)) {
        return false;
    }

    // We got an object handed, that we have to release.
    Py_DECREF(*operand1);

    // That's our return value then. As we use a dedicated variable, it's
    // OK that way.
    *operand1 = result;

    return true;
}
Exemplo n.º 4
0
static int
_set_int(const char *name, int *target, PyObject *src, int dflt)
{
    if (src == NULL)
        *target = dflt;
    else {
        long value;
        if (!PyLong_CheckExact(src)) {
            PyErr_Format(PyExc_TypeError,
                         "\"%s\" must be an integer", name);
            return -1;
        }
        value = PyLong_AsLong(src);
        if (value == -1 && PyErr_Occurred())
            return -1;
#if SIZEOF_LONG > SIZEOF_INT
        if (value > INT_MAX || value < INT_MIN) {
            PyErr_Format(PyExc_ValueError,
                         "integer out of range for \"%s\"", name);
            return -1;
        }
#endif
        *target = (int)value;
    }
    return 0;
}
static INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
    if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
        long val = PyInt_AS_LONG(x);
        if (unlikely(val < 0)) {
            PyErr_SetString(PyExc_OverflowError,
                            "can't convert negative value to unsigned PY_LONG_LONG");
            return (unsigned PY_LONG_LONG)-1;
        }
        return (unsigned PY_LONG_LONG)val;
    } else
#endif
    if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
        if (unlikely(Py_SIZE(x) < 0)) {
            PyErr_SetString(PyExc_OverflowError,
                            "can't convert negative value to unsigned PY_LONG_LONG");
            return (unsigned PY_LONG_LONG)-1;
        }
        return PyLong_AsUnsignedLongLong(x);
    } else {
        unsigned PY_LONG_LONG val;
        PyObject *tmp = __Pyx_PyNumber_Int(x);
        if (!tmp) return (unsigned PY_LONG_LONG)-1;
        val = __Pyx_PyInt_AsUnsignedLongLong(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
Exemplo n.º 6
0
static PyObject *
range_index(rangeobject *r, PyObject *ob)
{
    int contains;

    if (!PyLong_CheckExact(ob) && !PyBool_Check(ob)) {
        Py_ssize_t index;
        index = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_INDEX);
        if (index == -1)
            return NULL;
        return PyLong_FromSsize_t(index);
    }

    contains = range_contains_long(r, ob);
    if (contains == -1)
        return NULL;

    if (contains) {
        PyObject *idx, *tmp = PyNumber_Subtract(ob, r->start);
        if (tmp == NULL)
            return NULL;
        /* idx = (ob - r.start) // r.step */
        idx = PyNumber_FloorDivide(tmp, r->step);
        Py_DECREF(tmp);
        return idx;
    }

    /* object is not in the range */
    PyErr_Format(PyExc_ValueError, "%R is not in range", ob);
    return NULL;
}
Exemplo n.º 7
0
/* Write a single value to the buffer (also write it's type_byte, for which
 * space has already been reserved.
 *
 * returns 0 on failure */
static int write_element_to_buffer(bson_buffer* buffer, int type_byte, PyObject* value, unsigned char check_keys) {
    /* TODO this isn't quite the same as the Python version:
     * here we check for type equivalence, not isinstance in some
     * places. */
    if (PyInt_CheckExact(value) || PyLong_CheckExact(value)) {
        const long long_value = PyInt_AsLong(value);
        const int int_value = (int)long_value;
        if (PyErr_Occurred() || long_value != int_value) { /* Overflow */
            long long long_long_value;
            PyErr_Clear();
            long_long_value = PyLong_AsLongLong(value);
            if (PyErr_Occurred()) { /* Overflow AGAIN */
                PyErr_SetString(PyExc_OverflowError,
                                "MongoDB can only handle up to 8-byte ints");
                return 0;
            }
            *(buffer->buffer + type_byte) = 0x12;
            return buffer_write_bytes(buffer, (const char*)&long_long_value, 8);
        }
        *(buffer->buffer + type_byte) = 0x10;
        return buffer_write_bytes(buffer, (const char*)&int_value, 4);
    } else if (PyBool_Check(value)) {
        const long bool = PyInt_AsLong(value);
        const char c = bool ? 0x01 : 0x00;
        *(buffer->buffer + type_byte) = 0x08;
        return buffer_write_bytes(buffer, &c, 1);
    } else if (PyFloat_CheckExact(value)) {
Exemplo n.º 8
0
static int
range_contains(rangeobject *r, PyObject *ob) {
    if (PyLong_CheckExact(ob) || PyBool_Check(ob))
        return range_contains_long(r, ob);

    return (int)_PySequence_IterSearch((PyObject*)r, ob,
                                       PY_ITERSEARCH_CONTAINS);
}
Exemplo n.º 9
0
static PyObject *
GMPy_MPZ_IAdd_Slot(PyObject *self, PyObject *other)
{
    MPZ_Object *result = NULL;

    if (CHECK_MPZANY(other)) {
        if ((result = GMPy_MPZ_New(NULL))) {
            mpz_add(result->z, MPZ(self), MPZ(other));
        }
        return (PyObject*)result;
    }

    if (PyLong_CheckExact(other)) {
        if ((result = GMPy_MPZ_New(NULL))) {
            switch (Py_SIZE((PyLongObject*)other)) {
            case -1:
                mpz_sub_ui(result->z, MPZ(self), ((PyLongObject*)other)->ob_digit[0]);
                return (PyObject*)result;
            case 0:
            case 1:
                mpz_add_ui(result->z, MPZ(self), ((PyLongObject*)other)->ob_digit[0]);
                return (PyObject*)result;
            default:
                break;
            }
        }
        else {
            return NULL;
        }
    }

    if (PyIntOrLong_Check(other)) {
        int error;
        long temp = GMPy_Integer_AsLongAndError(other, &error);

        if ((result = GMPy_MPZ_New(NULL))) {
            if (!error) {
                if (temp >= 0) {
                    mpz_add_ui(result->z, MPZ(self), temp);
                }
                else {
                    mpz_sub_ui(result->z, MPZ(self), -temp);
                }
            }
            else {
                mpz_t tempz;
                mpz_inoc(tempz);
                mpz_set_PyIntOrLong(tempz, other);
                mpz_add(result->z, MPZ(self), tempz);
                mpz_cloc(tempz);
            }
        }
        return (PyObject*)result;
    }

    Py_RETURN_NOTIMPLEMENTED;
}
Exemplo n.º 10
0
static PyObject *
pint_getquoted(pintObject *self, PyObject *args)
{
    PyObject *res = NULL;

    /* Convert subclass to int to handle IntEnum and other subclasses
     * whose str() is not the number. */
    if (PyLong_CheckExact(self->wrapped)
#if PY_MAJOR_VERSION < 2
        || PyInt_CheckExact(self->wrapped)
#endif
       ) {
        res = PyObject_Str(self->wrapped);
    } else {
        PyObject *tmp;
        if (!(tmp = PyObject_CallFunctionObjArgs(
                (PyObject *)&PyLong_Type, self->wrapped, NULL))) {
            goto exit;
        }
        res = PyObject_Str(tmp);
        Py_DECREF(tmp);
    }

    if (!res) {
        goto exit;
    }

#if PY_MAJOR_VERSION > 2
    /* unicode to bytes in Py3 */
    {
        PyObject *tmp = PyUnicode_AsUTF8String(res);
        Py_DECREF(res);
        if (!(res = tmp)) {
            goto exit;
        }
    }
#endif

    if ('-' == Bytes_AS_STRING(res)[0]) {
        /* Prepend a space in front of negative numbers (ticket #57) */
        PyObject *tmp;
        if (!(tmp = Bytes_FromString(" "))) {
            Py_DECREF(res);
            res = NULL;
            goto exit;
        }
        Bytes_ConcatAndDel(&tmp, res);
        if (!(res = tmp)) {
            goto exit;
        }
    }

exit:
    return res;
}
Exemplo n.º 11
0
    static void *convertible(::PyObject *obj_ptr)
    {
        if (!obj_ptr
            || (
#if PY_MAJOR_VERSION < 3
                   !PyInt_CheckExact(obj_ptr) &&
#endif
                   !PyLong_CheckExact(obj_ptr))) {
            return nullptr;
        }
        return obj_ptr;
    }
Exemplo n.º 12
0
static PyObject *
range_index(rangeobject *r, PyObject *ob)
{
    PyObject *idx, *tmp;
    int contains;
    PyObject *format_tuple, *err_string;
    static PyObject *err_format = NULL;

    if (!PyLong_CheckExact(ob) && !PyBool_Check(ob)) {
        Py_ssize_t index;
        index = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_INDEX);
        if (index == -1)
            return NULL;
        return PyLong_FromSsize_t(index);
    }

    contains = range_contains_long(r, ob);
    if (contains == -1)
        return NULL;

    if (!contains)
        goto value_error;

    tmp = PyNumber_Subtract(ob, r->start);
    if (tmp == NULL)
        return NULL;

    /* idx = (ob - r.start) // r.step */
    idx = PyNumber_FloorDivide(tmp, r->step);
    Py_DECREF(tmp);
    return idx;

value_error:

    /* object is not in the range */
    if (err_format == NULL) {
        err_format = PyUnicode_FromString("%r is not in range");
        if (err_format == NULL)
            return NULL;
    }
    format_tuple = PyTuple_Pack(1, ob);
    if (format_tuple == NULL)
        return NULL;
    err_string = PyUnicode_Format(err_format, format_tuple);
    Py_DECREF(format_tuple);
    if (err_string == NULL)
        return NULL;
    PyErr_SetObject(PyExc_ValueError, err_string);
    Py_DECREF(err_string);
    return NULL;
}
Exemplo n.º 13
0
static INLINE PY_LONG_LONG __pyx_PyInt_AsLongLong(PyObject* x) {
    if (PyInt_CheckExact(x)) {
        return PyInt_AS_LONG(x);
    }
    else if (PyLong_CheckExact(x)) {
        return PyLong_AsLongLong(x);
    }
    else {
        PY_LONG_LONG val;
        PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1;
        val = __pyx_PyInt_AsLongLong(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
Exemplo n.º 14
0
static PyObject *
range_count(rangeobject *r, PyObject *ob)
{
    if (PyLong_CheckExact(ob) || PyBool_Check(ob)) {
        int result = range_contains_long(r, ob);
        if (result == -1)
            return NULL;
        return PyLong_FromLong(result);
    } else {
        Py_ssize_t count;
        count = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_COUNT);
        if (count == -1)
            return NULL;
        return PyLong_FromSsize_t(count);
    }
}
static PyObject* JavaRandom_next(JavaRandomObject* self, PyObject* arg1)
{
    if (!PyLong_CheckExact(arg1))
    {
        PyErr_SetString(PyExc_TypeError, "The first attribute value must be an int");
        return NULL;
    }

    int bits = PyLong_AsLong(arg1);

    long long int next_rnd_bits = java_random_next(&self->rnd, bits);

    PyObject* result = PyLong_FromLongLong(next_rnd_bits);

    return result;
}
Exemplo n.º 16
0
/*
 * PyArray_GetAttrString_SuppressException:
 *
 * Stripped down version of PyObject_GetAttrString,
 * avoids lookups for None, tuple, and List objects,
 * and doesn't create a PyErr since this code ignores it.
 *
 * This can be much faster then PyObject_GetAttrString where
 * exceptions are not used by caller.
 *
 * 'obj' is the object to search for attribute.
 *
 * 'name' is the attribute to search for.
 *
 * Returns attribute value on success, 0 on failure.
 */
PyObject *
PyArray_GetAttrString_SuppressException(PyObject *obj, char *name)
{
    PyTypeObject *tp = Py_TYPE(obj);
    PyObject *res = (PyObject *)NULL;

    /* We do not need to check for special attributes on trivial types */
    if (obj == Py_None ||
            /* Basic number types */
#if !defined(NPY_PY3K)
            PyInt_CheckExact(obj) ||
#endif
            PyLong_CheckExact(obj) ||
            PyFloat_CheckExact(obj) ||
            /* Basic sequence types */
            PyList_CheckExact(obj) ||
            PyTuple_CheckExact(obj)) {
        return NULL;
    }

    /* Attribute referenced by (char *)name */
    if (tp->tp_getattr != NULL) {
        res = (*tp->tp_getattr)(obj, name);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    /* Attribute referenced by (PyObject *)name */
    else if (tp->tp_getattro != NULL) {
#if defined(NPY_PY3K)
        PyObject *w = PyUnicode_InternFromString(name);
#else
        PyObject *w = PyString_InternFromString(name);
#endif
        if (w == NULL) {
            return (PyObject *)NULL;
        }
        res = (*tp->tp_getattro)(obj, w);
        Py_DECREF(w);
        if (res == NULL) {
            PyErr_Clear();
        }
    }
    return res;
}
Exemplo n.º 17
0
static PyObject *
python_compress(PyObject *self, PyObject *args) {
    char *input, *output;
    Py_ssize_t inlen;
    PyObject *pyoutlen = Py_None;
    long outlen;
    PyObject *result;

    if (!PyArg_ParseTuple(args, "s#|O", &input, &inlen, &pyoutlen))
        return NULL;

    if (pyoutlen == Py_None)
        outlen = inlen - 1;
    else if (PyInt_CheckExact(pyoutlen))
        outlen = PyInt_AsLong(pyoutlen);
    else if (PyLong_CheckExact(pyoutlen))
        outlen = PyLong_AsLong(pyoutlen);
    else {
        PyErr_SetString(PyExc_TypeError, "max_len must be an integer");
        return NULL;
    }

    if (inlen == 1) outlen++; /* work around for what looks like a liblzf bug */
    if (outlen <= 0) {
        PyErr_SetString(PyExc_ValueError, "max_len must be > 0");
        return NULL;
    }

    output = (char *)malloc(outlen + 1);
    if (output == NULL) {
        PyErr_SetString(PyExc_MemoryError, "out of memory");
        return NULL;
    }
    outlen = lzf_compress(input, inlen, output, outlen + 1);

    if (outlen)
        result = PYBYTES_FSAS(output, outlen);
    else {
        Py_XINCREF(Py_None);
        result = Py_None;
    }
    free(output);

    return result;
}
static INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
    if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
        long val = PyInt_AS_LONG(x);
        return (signed PY_LONG_LONG)val;
    } else
#endif
    if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
        return PyLong_AsLongLong(x);
    } else {
        signed PY_LONG_LONG val;
        PyObject *tmp = __Pyx_PyNumber_Int(x);
        if (!tmp) return (signed PY_LONG_LONG)-1;
        val = __Pyx_PyInt_AsSignedLongLong(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
Exemplo n.º 19
0
Arquivo: myson.c Projeto: S-YOU/myson
void encode_object(PyObject *arg) {
	Py_ssize_t size, i;
	char *p;

	if (PyString_CheckExact(arg)) {
		uint8_t *s, *sEnd;
		*d++ = '"';
		ENCODE_STR(arg, s, sEnd)
		*d++ = '"';
	} else if (PyUnicode_CheckExact(arg)) {
		*d++ = '"';
		Py_UNICODE *u, *uEnd;
		ENCODE_UNICODE(arg, u, uEnd)
		*d++ = '"';
	} else if (PyInt_CheckExact(arg) || PyLong_CheckExact(arg)) {
		i = PyInt_AsSsize_t(arg);
		uint64_t val = i < 0 ? *d++ = '-', (uint64_t)(~i + 1) : i;
		ITOA(val)
	} else if (PyList_CheckExact(arg)) {
Exemplo n.º 20
0
Arquivo: _speedups.c Projeto: 10sr/hue
static PyObject*
escape(PyObject *self, PyObject *text)
{
	PyObject *s = NULL, *rv = NULL, *html;

	/* we don't have to escape integers, bools or floats */
	if (PyLong_CheckExact(text) ||
#if PY_MAJOR_VERSION < 3
	    PyInt_CheckExact(text) ||
#endif
	    PyFloat_CheckExact(text) || PyBool_Check(text) ||
	    text == Py_None)
		return PyObject_CallFunctionObjArgs(markup, text, NULL);

	/* if the object has an __html__ method that performs the escaping */
	html = PyObject_GetAttrString(text, "__html__");
	if (html) {
		rv = PyObject_CallObject(html, NULL);
		Py_DECREF(html);
		return rv;
	}

	/* otherwise make the object unicode if it isn't, then escape */
	PyErr_Clear();
	if (!PyUnicode_Check(text)) {
#if PY_MAJOR_VERSION < 3
		PyObject *unicode = PyObject_Unicode(text);
#else
		PyObject *unicode = PyObject_Str(text);
#endif
		if (!unicode)
			return NULL;
		s = escape_unicode((PyUnicodeObject*)unicode);
		Py_DECREF(unicode);
	}
	else
		s = escape_unicode((PyUnicodeObject*)text);

	/* convert the unicode string into a markup object. */
	rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);
	Py_DECREF(s);
	return rv;
}
Exemplo n.º 21
0
static INLINE unsigned PY_LONG_LONG __pyx_PyInt_AsUnsignedLongLong(PyObject* x) {
    if (PyInt_CheckExact(x)) {
        long val = PyInt_AS_LONG(x);
        if (unlikely(val < 0)) {
            PyErr_SetString(PyExc_TypeError, "Negative assignment to unsigned type.");
            return (unsigned PY_LONG_LONG)-1;
        }
        return val;
    }
    else if (PyLong_CheckExact(x)) {
        return PyLong_AsUnsignedLongLong(x);
    }
    else {
        PY_LONG_LONG val;
        PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1;
        val = __pyx_PyInt_AsUnsignedLongLong(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
Exemplo n.º 22
0
Arquivo: _csv.c Projeto: 1st1/cpython
static int
_set_int(const char *name, int *target, PyObject *src, int dflt)
{
    if (src == NULL)
        *target = dflt;
    else {
        int value;
        if (!PyLong_CheckExact(src)) {
            PyErr_Format(PyExc_TypeError,
                         "\"%s\" must be an integer", name);
            return -1;
        }
        value = _PyLong_AsInt(src);
        if (value == -1 && PyErr_Occurred()) {
            return -1;
        }
        *target = value;
    }
    return 0;
}
static int JavaRandom_set_seed(JavaRandomObject* self, PyObject* value, void* closure)
{
    if (value == NULL)
    {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the seed attribute");
        return -1;
    }

    if (!PyLong_CheckExact(value))
    {
        PyErr_SetString(PyExc_TypeError, "The first attribute value must be an int");
        return -1;
    }

    seed_t seed_value = PyLong_AsLongLong(value);

    java_random_set_seed(&self->rnd, seed_value);

    return 0;
}
Exemplo n.º 24
0
static PyObject* cstuff_DirectionMap_set_walls(cstuff_DirectionMap* self, PyObject *args) {
	PyObject *list1, *list2, *iterator1, *iterator2, *value;
	int whichwall;
	int row, col, stride;

	if (!PyArg_ParseTuple(args, "Oi", &list1, &whichwall)) {
		return NULL;
	}

	row = 0;
	if (!(iterator1 = PyObject_GetIter(list1))) {
		return NULL;
	}
	while ((list2 = PyIter_Next(iterator1)) && row < g_rows) {
		stride = row * g_cols;
		if (!(iterator2 = PyObject_GetIter(list2))) {
			Py_DECREF(list2);
			break;
		}
		col = 0;
		while ((value = PyIter_Next(iterator2)) && col < g_cols) {
			if (PyLong_CheckExact(value) && PyLong_AsLong(value) == whichwall) {
				self->walls->values[stride+col] = 1;
			}
			Py_DECREF(value);
			col += 1;
		}
		Py_DECREF(iterator2);
		Py_DECREF(list2);
		row += 1;
	}

	Py_DECREF(iterator1);

	if (PyErr_Occurred()) {
		return NULL;
	}

	Py_RETURN_NONE;
}
Exemplo n.º 25
0
static PyObject*
convert_nested(PyObject *ob, convert_func convert_string)
{
    /* dict. */
    if (PyDict_CheckExact(ob)) {
        return convert_dict(ob, convert_string);
    }

    /* sequence. */
    if (PyTuple_CheckExact(ob) || PyList_CheckExact(ob)) {
        return convert_seq(ob, convert_string);
    }

    /* numbers. */
    if (PyInt_CheckExact(ob) || PyLong_CheckExact(ob) || PyFloat_CheckExact(ob)) {
        Py_INCREF(ob);
        return ob;
    }

    /* bool. */
    if (PyBool_Check(ob)) {
        Py_INCREF(ob);
        return ob;
    }

    /* none. */
    if (ob == Py_None) {
        Py_INCREF(ob);
        return ob;
    }

    if (PyString_CheckExact(ob) || PyUnicode_CheckExact(ob)) {
        return convert_string(ob);
    }

    return PyErr_Format(
        PyExc_TypeError,
        "Got wrong type: %s",
        ob->ob_type->tp_name);
}
Exemplo n.º 26
0
static PyObject *
csv_field_size_limit(PyObject *module, PyObject *args)
{
    PyObject *new_limit = NULL;
    long old_limit = field_limit;

    if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
        return NULL;
    if (new_limit != NULL) {
        if (!PyLong_CheckExact(new_limit)) {
            PyErr_Format(PyExc_TypeError,
                         "limit must be an integer");
            return NULL;
        }
        field_limit = PyLong_AsLong(new_limit);
        if (field_limit == -1 && PyErr_Occurred()) {
            field_limit = old_limit;
            return NULL;
        }
    }
    return PyLong_FromLong(old_limit);
}
Exemplo n.º 27
0
static PyObject*
NAInteger_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  static PyLongObject *self = NULL;
  static char *kwlist[] = {0};
  PyObject *py_value;
  Py_ssize_t i, n;

  assert(PyType_IsSubtype(type, &PyLong_Type));

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist)) {
    return NULL;
  }
  
  if (self == NULL) {
    py_value = PyLong_FromLong((long)(NA_INTEGER));
    if (py_value == NULL) {
      return NULL;
    }

    assert(PyLong_CheckExact(py_value));
    n = Py_SIZE(py_value);
    if (n < 0)
      n = -n;
    self = (PyLongObject *)(PyLong_Type.tp_alloc(type, n));
    if (self == NULL) {
      Py_DECREF(py_value);
      return NULL;
    }
    assert(PyLong_Check(self));
    Py_SIZE(self) = Py_SIZE(py_value);
    for (i = 0; i < n; i++) {
      self->ob_digit[i] = ((PyLongObject *)py_value)->ob_digit[i];
    }
    Py_DECREF(py_value);
  }
  Py_XINCREF(self);
  return (PyObject *)self;
}
Exemplo n.º 28
0
static int
already_warned(PyObject *registry, PyObject *key, int should_set)
{
    PyObject *version_obj, *already_warned;
    _Py_IDENTIFIER(version);

    if (key == NULL)
        return -1;

    version_obj = _PyDict_GetItemId(registry, &PyId_version);
    if (version_obj == NULL
        || !PyLong_CheckExact(version_obj)
        || PyLong_AsLong(version_obj) != _filters_version) {
        PyDict_Clear(registry);
        version_obj = PyLong_FromLong(_filters_version);
        if (version_obj == NULL)
            return -1;
        if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
            Py_DECREF(version_obj);
            return -1;
        }
        Py_DECREF(version_obj);
    }
    else {
        already_warned = PyDict_GetItem(registry, key);
        if (already_warned != NULL) {
            int rc = PyObject_IsTrue(already_warned);
            if (rc != 0)
                return rc;
        }
    }

    /* This warning wasn't found in the registry, set it. */
    if (should_set)
        return PyDict_SetItem(registry, key, Py_True);
    return 0;
}
Exemplo n.º 29
0
static int
format_long_internal(PyObject *value, const InternalFormatSpec *format,
                     _PyUnicodeWriter *writer)
{
    int result = -1;
    Py_UCS4 maxchar = 127;
    PyObject *tmp = NULL;
    Py_ssize_t inumeric_chars;
    Py_UCS4 sign_char = '\0';
    Py_ssize_t n_digits;       /* count of digits need from the computed
                                  string */
    Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which
                                   produces non-digits */
    Py_ssize_t n_prefix = 0;   /* Count of prefix chars, (e.g., '0x') */
    Py_ssize_t n_total;
    Py_ssize_t prefix = 0;
    NumberFieldWidths spec;
    long x;

    /* Locale settings, either from the actual locale or
       from a hard-code pseudo-locale */
    LocaleInfo locale = STATIC_LOCALE_INFO_INIT;

    /* no precision allowed on integers */
    if (format->precision != -1) {
        PyErr_SetString(PyExc_ValueError,
                        "Precision not allowed in integer format specifier");
        goto done;
    }

    /* special case for character formatting */
    if (format->type == 'c') {
        /* error to specify a sign */
        if (format->sign != '\0') {
            PyErr_SetString(PyExc_ValueError,
                            "Sign not allowed with integer"
                            " format specifier 'c'");
            goto done;
        }

        /* taken from unicodeobject.c formatchar() */
        /* Integer input truncated to a character */
        x = PyLong_AsLong(value);
        if (x == -1 && PyErr_Occurred())
            goto done;
        if (x < 0 || x > 0x10ffff) {
            PyErr_SetString(PyExc_OverflowError,
                            "%c arg not in range(0x110000)");
            goto done;
        }
        tmp = PyUnicode_FromOrdinal(x);
        inumeric_chars = 0;
        n_digits = 1;
        maxchar = Py_MAX(maxchar, (Py_UCS4)x);

        /* As a sort-of hack, we tell calc_number_widths that we only
           have "remainder" characters. calc_number_widths thinks
           these are characters that don't get formatted, only copied
           into the output string. We do this for 'c' formatting,
           because the characters are likely to be non-digits. */
        n_remainder = 1;
    }
    else {
        int base;
        int leading_chars_to_skip = 0;  /* Number of characters added by
                                           PyNumber_ToBase that we want to
                                           skip over. */

        /* Compute the base and how many characters will be added by
           PyNumber_ToBase */
        switch (format->type) {
        case 'b':
            base = 2;
            leading_chars_to_skip = 2; /* 0b */
            break;
        case 'o':
            base = 8;
            leading_chars_to_skip = 2; /* 0o */
            break;
        case 'x':
        case 'X':
            base = 16;
            leading_chars_to_skip = 2; /* 0x */
            break;
        default:  /* shouldn't be needed, but stops a compiler warning */
        case 'd':
        case 'n':
            base = 10;
            break;
        }

        if (format->sign != '+' && format->sign != ' '
            && format->width == -1
            && format->type != 'X' && format->type != 'n'
            && !format->thousands_separators
            && PyLong_CheckExact(value))
        {
            /* Fast path */
            return _PyLong_FormatWriter(writer, value, base, format->alternate);
        }

        /* The number of prefix chars is the same as the leading
           chars to skip */
        if (format->alternate)
            n_prefix = leading_chars_to_skip;

        /* Do the hard part, converting to a string in a given base */
        tmp = _PyLong_Format(value, base);
        if (tmp == NULL || PyUnicode_READY(tmp) == -1)
            goto done;

        inumeric_chars = 0;
        n_digits = PyUnicode_GET_LENGTH(tmp);

        prefix = inumeric_chars;

        /* Is a sign character present in the output?  If so, remember it
           and skip it */
        if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') {
            sign_char = '-';
            ++prefix;
            ++leading_chars_to_skip;
        }

        /* Skip over the leading chars (0x, 0b, etc.) */
        n_digits -= leading_chars_to_skip;
        inumeric_chars += leading_chars_to_skip;
    }

    /* Determine the grouping, separator, and decimal point, if any. */
    if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
                        (format->thousands_separators ?
                         LT_DEFAULT_LOCALE :
                         LT_NO_LOCALE),
                        &locale) == -1)
        goto done;

    /* Calculate how much memory we'll need. */
    n_total = calc_number_widths(&spec, n_prefix, sign_char, tmp, inumeric_chars,
                                 inumeric_chars + n_digits, n_remainder, 0,
                                 &locale, format, &maxchar);

    /* Allocate the memory. */
    if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1)
        goto done;

    /* Populate the memory. */
    result = fill_number(writer, &spec,
                         tmp, inumeric_chars, inumeric_chars + n_digits,
                         tmp, prefix, format->fill_char,
                         &locale, format->type == 'X');

done:
    Py_XDECREF(tmp);
    free_locale_info(&locale);
    return result;
}
Exemplo n.º 30
0
int
_PyLong_FormatAdvancedWriter(_PyUnicodeWriter *writer,
                             PyObject *obj,
                             PyObject *format_spec,
                             Py_ssize_t start, Py_ssize_t end)
{
    PyObject *tmp = NULL, *str = NULL;
    InternalFormatSpec format;
    int result = -1;

    /* check for the special case of zero length format spec, make
       it equivalent to str(obj) */
    if (start == end) {
        if (PyLong_CheckExact(obj))
            return _PyLong_FormatWriter(writer, obj, 10, 0);
        else
            return format_obj(obj, writer);
    }

    /* parse the format_spec */
    if (!parse_internal_render_format_spec(format_spec, start, end,
                                           &format, 'd', '>'))
        goto done;

    /* type conversion? */
    switch (format.type) {
    case 'b':
    case 'c':
    case 'd':
    case 'o':
    case 'x':
    case 'X':
    case 'n':
        /* no type conversion needed, already an int.  do the formatting */
        result = format_long_internal(obj, &format, writer);
        break;

    case 'e':
    case 'E':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case '%':
        /* convert to float */
        tmp = PyNumber_Float(obj);
        if (tmp == NULL)
            goto done;
        result = format_float_internal(tmp, &format, writer);
        break;

    default:
        /* unknown */
        unknown_presentation_type(format.type, obj->ob_type->tp_name);
        goto done;
    }

done:
    Py_XDECREF(tmp);
    Py_XDECREF(str);
    return result;
}