bool BINARY_OPERATION_ADD_TUPLE_TUPLE_INPLACE(PyObject **operand1, PyObject *operand2) {
    assert(operand1);
    CHECK_OBJECT(*operand1);
    CHECK_OBJECT(operand2);
    assert(PyTuple_CheckExact(*operand1));
    assert(PyTuple_CheckExact(operand2));

    PyObject *result;

    // TODO: No tuple specific code, create one and use it, although it
    // is probably not too common to in-place to them.
    result = PySequence_InPlaceConcat(*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;
}
Esempio n. 2
0
static void py_variable_to_json_internal( PyObject *obj,
                                          json_writer_t *writer )
{
  if ( PyString_CheckExact( obj ) ) {
    json_writer_write_str( writer, PyString_AS_STRING( obj ) );
  }
  else if ( PyInt_CheckExact( obj ) ) {
    json_writer_write_integer( writer, PyInt_AS_LONG( obj ) );
  }
  else if ( PyFloat_CheckExact( obj ) ) {
    json_writer_write_number( writer, PyFloat_AS_DOUBLE( obj ) );
  }
  else if ( PyBool_Check( obj ) ) {
    json_writer_write_boolean( writer, ( obj == Py_True ) );
  }
  else if ( PyUnicode_CheckExact( obj ) ) {
    /* Create a new string object that is UTF-8 encoded. */
    Py_UNICODE *unicode = PyUnicode_AS_UNICODE( obj );
    Py_ssize_t size = PyUnicode_GET_SIZE( obj );
    PyObject *str_obj = PyUnicode_EncodeUTF8( unicode, size, NULL );
    py_variable_to_json_internal( str_obj, writer );
    PyObject_Free( str_obj );
  }
  else if ( PyDict_CheckExact( obj ) ) {
    py_dict_to_json( obj, writer );
  }
  else if ( PyList_CheckExact( obj ) ) {
    py_list_to_json( obj, writer );
  }
  else if ( PyTuple_CheckExact( obj ) ) {
    py_tuple_to_json( obj, writer ); 
  }
}
Esempio n. 3
0
/*
 * Get possible out argument from kwds, and returns the number of outputs
 * contained within it: if a tuple, the number of elements in it, 1 otherwise.
 * The out argument itself is returned in out_kwd_obj, and the outputs
 * in the out_obj array (all as borrowed references).
 *
 * Returns -1 if kwds is not a dict, 0 if no outputs found.
 */
static int
get_out_objects(PyObject *kwds, PyObject **out_kwd_obj, PyObject ***out_objs)
{
    if (kwds == NULL) {
        return 0;
    }
    if (!PyDict_CheckExact(kwds)) {
        PyErr_SetString(PyExc_TypeError,
                        "Internal Numpy error: call to PyUFunc_WithOverride "
                        "with non-dict kwds");
        return -1;
    }
    /* borrowed reference */
    *out_kwd_obj = PyDict_GetItemString(kwds, "out");
    if (*out_kwd_obj == NULL) {
        return 0;
    }
    if (PyTuple_CheckExact(*out_kwd_obj)) {
        *out_objs = PySequence_Fast_ITEMS(*out_kwd_obj);
        return PySequence_Fast_GET_SIZE(*out_kwd_obj);
    }
    else {
        *out_objs = out_kwd_obj;
        return 1;
    }
}
Esempio n. 4
0
Box* tupleMul(BoxedTuple* self, Box* rhs) {
    Py_ssize_t n;
    if (PyIndex_Check(rhs)) {
        n = PyNumber_AsSsize_t(rhs, PyExc_OverflowError);
        if (n == -1 && PyErr_Occurred())
            throwCAPIException();
    } else {
        raiseExcHelper(TypeError, "can't multiply sequence by non-int of type '%s'", getTypeName(rhs));
    }

    int s = self->size();

    if (n < 0)
        n = 0;

    if ((s == 0 || n == 1) && PyTuple_CheckExact(self)) {
        return self;
    } else {
        BoxedTuple* rtn = BoxedTuple::create(n * s);
        int rtn_i = 0;
        for (int i = 0; i < n; ++i) {
            memmove(&rtn->elts[rtn_i], &self->elts[0], sizeof(Box*) * s);
            rtn_i += s;
        }
        return rtn;
    }
}
Esempio n. 5
0
static PyObject* tupleslice(PyTupleObject* a, Py_ssize_t ilow, Py_ssize_t ihigh) {
    PyTupleObject* np;
    PyObject** src, **dest;
    Py_ssize_t i;
    Py_ssize_t len;
    if (ilow < 0)
        ilow = 0;
    if (ihigh > Py_SIZE(a))
        ihigh = Py_SIZE(a);
    if (ihigh < ilow)
        ihigh = ilow;
    if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact((PyObject*)a)) {
        Py_INCREF(a);
        return (PyObject*)a;
    }
    len = ihigh - ilow;
    np = (PyTupleObject*)PyTuple_New(len);
    if (np == NULL)
        return NULL;
    src = a->ob_item + ilow;
    dest = np->ob_item;
    for (i = 0; i < len; i++) {
        PyObject* v = src[i];
        Py_INCREF(v);
        dest[i] = v;
    }
    return (PyObject*)np;
}
Esempio n. 6
0
static PyObject* tuplerepeat(PyTupleObject* a, Py_ssize_t n) noexcept {
    Py_ssize_t i, j;
    Py_ssize_t size;
    PyTupleObject* np;
    PyObject** p, **items;
    if (n < 0)
        n = 0;
    if (Py_SIZE(a) == 0 || n == 1) {
        if (PyTuple_CheckExact((BoxedTuple*)a)) {
            /* Since tuples are immutable, we can return a shared
             *                copy in this case */
            Py_INCREF(a);
            return (PyObject*)a;
        }
        if (Py_SIZE(a) == 0)
            return PyTuple_New(0);
    }
    size = Py_SIZE(a) * n;
    if (size / Py_SIZE(a) != n)
        return PyErr_NoMemory();
    np = (PyTupleObject*)PyTuple_New(size);
    if (np == NULL)
        return NULL;
    p = np->ob_item;
    items = a->ob_item;
    for (i = 0; i < n; i++) {
        for (j = 0; j < Py_SIZE(a); j++) {
            *p = items[j];
            Py_INCREF(*p);
            p++;
        }
    }
    return (PyObject*)np;
}
Esempio n. 7
0
File: key.c Progetto: dw/acid
/**
 * Construct a Key from a sequence.
 */
static PyObject *
key_new(PyTypeObject *cls, PyObject *args, PyObject *kwds)
{
    if(PyTuple_GET_SIZE(args) == 1) {
        PyObject *arg = PyTuple_GET_ITEM(args, 0);
        if(Py_TYPE(arg) == &KeyType) {
            Py_INCREF(arg);
            return arg;
        }
        if(PyTuple_CheckExact(arg)) {
            args = arg;
        }
    }

    struct writer wtr;
    if(acid_writer_init(&wtr, 32)) {
        return NULL;
    }

    Py_ssize_t len = PyTuple_GET_SIZE(args);
    for(Py_ssize_t i = 0; i < len; i++) {
        PyObject *arg = PyTuple_GET_ITEM(args, i);
        if(acid_write_element(&wtr, arg)) {
            acid_writer_abort(&wtr);
            return NULL;
        }
    }

    Key *self = acid_make_private_key(acid_writer_ptr(&wtr) - wtr.pos, wtr.pos);
    acid_writer_abort(&wtr);
    return (PyObject *) self;
}
Esempio n. 8
0
 std::string GetObjectName( Object * pyobjreff )
 {
     Py_XINCREF( pyobjreff );
     if( PyString_CheckExact( pyobjreff ) )
     {
         const char * objname = PyString_AsString( pyobjreff );
         std::string ret(objname);
         objname = NULL;
         Py_XDECREF( pyobjreff );
         return ret;
     }
     if( PyTuple_CheckExact( pyobjreff ) )
     {
         if( !PyTuple_Size( pyobjreff ) )
         {
             Py_XDECREF( pyobjreff );
             ThrowError(-1);
         }
         Object * curpydec = PyTuple_GetItem( pyobjreff,0 );
         if( !PyString_CheckExact( curpydec ) )
         {
             Py_XDECREF( pyobjreff );
             ThrowError(-2);
         }
         const char * dec = PyString_AsString( curpydec );
         std::string ret(dec);
         dec = NULL;
         Py_XDECREF( pyobjreff );
         return ret;
     }
     Py_XDECREF( pyobjreff );
     ThrowError(-3);
     return std::string();
 }
Esempio n. 9
0
 POGEL::OBJECT * GetObject( const std::string& simname, Object* pyobjreff )
 {
     if( PyString_CheckExact( pyobjreff ) )
     {
         const char* objname = PyString_AsString( pyobjreff );
         POGEL::OBJECT* ret = (POGEL::OBJECT*)Renderer::Physics::getObject( simname,  std::string( objname ) );
         objname = NULL;
         return ret;
     }
     if( PyTuple_CheckExact( pyobjreff ) )
     {
         int tlen = PyTuple_Size( pyobjreff );
         ClassList< std::string > declist( tlen );
         for( int i = 0; i < tlen; ++i )
         {
             Object * curpydec = PyTuple_GetItem( pyobjreff, i );
             if( !curpydec || !PyString_CheckExact( curpydec ) )
             {
                 declist.clear();
                 return NULL;
             }
             const char * dec = PyString_AsString( curpydec );
             //char * dec = (char*)memcpy( (void*)new char[strlen(tdec)], (const void *)tdec, strlen(tdec) );
             //tdec = NULL;
             declist += std::string(dec);
             dec = NULL;
             //delete [] dec;
         }
         POGEL::OBJECT * ret = Renderer::Physics::getObject( simname, declist );
         declist.clear();
         return ret;
     }
     return NULL;
 }
Esempio n. 10
0
static PyObject*
run(PyObject* self, PyObject* args)
{
  ServerInfo info;

  PyObject* socket;

  if(!PyArg_ParseTuple(args, "OO:server_run", &socket, &info.wsgi_app)) {
    return NULL;
  }

  info.sockfd = PyObject_AsFileDescriptor(socket);
  if (info.sockfd < 0) {
    return NULL;
  }

  info.host = NULL;
  if (PyObject_HasAttrString(socket, "getsockname")) {
    PyObject* sockname = PyObject_CallMethod(socket, "getsockname", NULL);
    if (sockname == NULL) {
      return NULL;
    }
    if (PyTuple_CheckExact(sockname) && PyTuple_GET_SIZE(sockname) == 2) {
      /* Standard (ipaddress, port) case */
      info.host = PyTuple_GET_ITEM(sockname, 0);
      info.port = PyTuple_GET_ITEM(sockname, 1);
    }
  }

  _initialize_request_module();
  server_run(&info);

  Py_RETURN_NONE;
}
Esempio n. 11
0
void
_PyTuple_MaybeUntrack(PyObject *op)
{
    PyTupleObject *t;
    Py_ssize_t i, n;

    if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
        return;
    t = (PyTupleObject *) op;
    n = Py_SIZE(t);
    for (i = 0; i < n; i++) {
        PyObject *elt = PyTuple_GET_ITEM(t, i);
        /* Tuple with NULL elements aren't
           fully constructed, don't untrack
           them yet. */
        if (!elt ||
            _PyObject_GC_MAY_BE_TRACKED(elt))
            return;
    }
#ifdef SHOW_TRACK_COUNT
    count_tracked--;
    count_untracked++;
#endif
    _PyObject_GC_UNTRACK(op);
}
Esempio n. 12
0
void pb_num_feature::add_feature(
    const std::string& key,
    double value,
    std::vector<std::pair<std::string, double> >& ret_fv) const {
  scoped_gil lk;

  pb_object pkey(pb_unicode_from_string(key));
  PB_CHECK(pkey,
           "cannot convert input key to Python object: " << key);

  pb_object pval(PyFloat_FromDouble(value));
  PB_CHECK(pval,
           "cannot convert input value to Python object for key: " << key);

  pb_object ret(PyObject_CallMethodObjArgs(
      ins_.get(),
      method_.get(),
      pkey.get(),
      pval.get(),
      NULL));
  PB_CHECK(ret,
           name_ << " method cannot be called");
  PB_CHECK(PyList_CheckExact(ret.get()),
           name_ << " method returned non-list type: " << pb_str(ret.get()));

  size_t size = PyList_Size(ret.get());
  for (size_t i = 0; i < size; ++i) {
    PyObject* tpl = PyList_GetItem(ret.get(), i);

    PB_CHECK(tpl,
             "item " << i << " cannot be accessed: "
             << pb_str(ret.get()));
    PB_CHECK(PyTuple_CheckExact(tpl),
             "list must not contain non-tuple: " << pb_str(tpl));
    PB_CHECK(PyTuple_Size(tpl) == 2,
             "tuple length must be 2: " << pb_str(tpl));

    PyObject* f_key = PyTuple_GetItem(tpl, 0);
    PyObject* f_val = PyTuple_GetItem(tpl, 1);

    PB_CHECK(PyUnicode_CheckExact(f_key),
             "feature key must be a unicode string: " << pb_str(tpl));
    PB_CHECK(PyNumber_Check(f_val),
             "feature value must be a number: " << pb_str(tpl));

    pb_object f_key_enc(PyUnicode_AsUTF8String(f_key));
    PB_CHECK(f_key_enc,
             "feature key cannot be encoded as UTF-8: "
             << pb_str(tpl));
    pb_object f_val_float(PyNumber_Float(f_val));
    PB_CHECK(f_val_float,
             "value cannot be converted as float: " << pb_str(tpl));

    ret_fv.push_back(std::make_pair(
        std::string(PyBytes_AsString(f_key_enc.get())),
        PyFloat_AsDouble(f_val_float.get())));
  }
}
Esempio n. 13
0
/* Move the unreachable objects from young to unreachable.  After this,
 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE.  All tracked
 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
 * All objects in young after this are directly or indirectly reachable
 * from outside the original young; and all objects in unreachable are
 * not.
 */
static void
move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
{
    PyGC_Head *gc = young->gc.gc_next;

    /* Invariants:  all objects "to the left" of us in young have gc_refs
     * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
     * from outside the young list as it was at entry.  All other objects
     * from the original young "to the left" of us are in unreachable now,
     * and have gc_refs = GC_TENTATIVELY_UNREACHABLE.  All objects to the
     * left of us in 'young' now have been scanned, and no objects here
     * or to the right have been scanned yet.
     */

    while (gc != young) {
        PyGC_Head *next;

        if (gc->gc.gc_refs) {
            /* gc is definitely reachable from outside the
             * original 'young'.  Mark it as such, and traverse
             * its pointers to find any other objects that may
             * be directly reachable from it.  Note that the
             * call to tp_traverse may append objects to young,
             * so we have to wait until it returns to determine
             * the next object to visit.
             */
            PyObject *op = FROM_GC(gc);
            traverseproc traverse = Py_TYPE(op)->tp_traverse;
            assert(gc->gc.gc_refs > 0);
            gc->gc.gc_refs = GC_REACHABLE;
            (void) traverse(op,
                            (visitproc)visit_reachable,
                            (void *)young);
            next = gc->gc.gc_next;
            if (PyTuple_CheckExact(op)) {
                _PyTuple_MaybeUntrack(op);
            }
            else if (PyDict_CheckExact(op)) {
                _PyDict_MaybeUntrack(op);
            }
        }
        else {
            /* This *may* be unreachable.  To make progress,
             * assume it is.  gc isn't directly reachable from
             * any object we've already traversed, but may be
             * reachable from an object we haven't gotten to yet.
             * visit_reachable will eventually move gc back into
             * young if that's so, and we'll see it again.
             */
            next = gc->gc.gc_next;
            gc_list_move(gc, unreachable);
            gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
        }
        gc = next;
    }
}
Esempio n. 14
0
static PyObject*
tuplesubscript(PyTupleObject* self, PyObject* item)
{
    if (PyIndex_Check(item)) {
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            return NULL;
        if (i < 0)
            i += PyTuple_GET_SIZE(self);
        return tupleitem(self, i);
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelength, cur, i;
        PyObject* result;
        PyObject* it;
        PyObject **src, **dest;

        if (PySlice_GetIndicesEx(item,
                         PyTuple_GET_SIZE(self),
                         &start, &stop, &step, &slicelength) < 0) {
            return NULL;
        }

        if (slicelength <= 0) {
            return PyTuple_New(0);
        }
        else if (start == 0 && step == 1 &&
                 slicelength == PyTuple_GET_SIZE(self) &&
                 PyTuple_CheckExact(self)) {
            Py_INCREF(self);
            return (PyObject *)self;
        }
        else {
            result = PyTuple_New(slicelength);
            if (!result) return NULL;

            src = self->ob_item;
            dest = ((PyTupleObject *)result)->ob_item;
            for (cur = start, i = 0; i < slicelength;
                 cur += step, i++) {
                it = src[cur];
                Py_INCREF(it);
                dest[i] = it;
            }

            return result;
        }
    }
    else {
        PyErr_Format(PyExc_TypeError,
                     "tuple indices must be integers, not %.200s",
                     Py_TYPE(item)->tp_name);
        return NULL;
    }
}
Esempio n. 15
0
/* Intern selected string constants */
static int
intern_string_constants(PyObject *tuple)
{
    int modified = 0;
    Py_ssize_t i;

    for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
        PyObject *v = PyTuple_GET_ITEM(tuple, i);
        if (PyUnicode_CheckExact(v)) {
            if (PyUnicode_READY(v) == -1) {
                PyErr_Clear();
                continue;
            }
            if (all_name_chars(v)) {
                PyObject *w = v;
                PyUnicode_InternInPlace(&v);
                if (w != v) {
                    PyTuple_SET_ITEM(tuple, i, v);
                    modified = 1;
                }
            }
        }
        else if (PyTuple_CheckExact(v)) {
            intern_string_constants(v);
        }
        else if (PyFrozenSet_CheckExact(v)) {
            PyObject *w = v;
            PyObject *tmp = PySequence_Tuple(v);
            if (tmp == NULL) {
                PyErr_Clear();
                continue;
            }
            if (intern_string_constants(tmp)) {
                v = PyFrozenSet_New(tmp);
                if (v == NULL) {
                    PyErr_Clear();
                }
                else {
                    PyTuple_SET_ITEM(tuple, i, v);
                    Py_DECREF(w);
                    modified = 1;
                }
            }
            Py_DECREF(tmp);
        }
    }
    return modified;
}
Esempio n. 16
0
/* Text encoding/decoding API */
static
PyObject *codec_getitem_checked(const char *encoding,
                                const char *operation_name,
                                int index)
{
    _Py_IDENTIFIER(_is_text_encoding);
    PyObject *codec;
    PyObject *attr;
    PyObject *v;
    int is_text_codec;

    codec = _PyCodec_Lookup(encoding);
    if (codec == NULL)
        return NULL;

    /* Backwards compatibility: assume any raw tuple describes a text
     * encoding, and the same for anything lacking the private
     * attribute.
     */
    if (!PyTuple_CheckExact(codec)) {
        attr = _PyObject_GetAttrId(codec, &PyId__is_text_encoding);
        if (attr == NULL) {
            if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
                PyErr_Clear();
            } else {
                Py_DECREF(codec);
                return NULL;
            }
        } else {
            is_text_codec = PyObject_IsTrue(attr);
            Py_DECREF(attr);
            if (!is_text_codec) {
                Py_DECREF(codec);
                PyErr_Format(PyExc_LookupError,
                             "'%.400s' is not a text encoding; "
                             "use codecs.%s() to handle arbitrary codecs",
                             encoding, operation_name);
                return NULL;
            }
        }
    }

    v = PyTuple_GET_ITEM(codec, index);
    Py_DECREF(codec);
    Py_INCREF(v);
    return v;
}
Esempio n. 17
0
static PyObject *
partial_setstate(partialobject *pto, PyObject *state)
{
    PyObject *fn, *fnargs, *kw, *dict;

    if (!PyTuple_Check(state) ||
        !PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) ||
        !PyCallable_Check(fn) ||
        !PyTuple_Check(fnargs) ||
        (kw != Py_None && !PyDict_Check(kw)))
    {
        PyErr_SetString(PyExc_TypeError, "invalid partial state");
        return NULL;
    }

    if(!PyTuple_CheckExact(fnargs))
        fnargs = PySequence_Tuple(fnargs);
    else
        Py_INCREF(fnargs);
    if (fnargs == NULL)
        return NULL;

    if (kw == Py_None)
        kw = PyDict_New();
    else if(!PyDict_CheckExact(kw))
        kw = PyDict_Copy(kw);
    else
        Py_INCREF(kw);
    if (kw == NULL) {
        Py_DECREF(fnargs);
        return NULL;
    }

    if (dict == Py_None)
        dict = NULL;
    else
        Py_INCREF(dict);

    Py_INCREF(fn);
    pto->use_fastcall = _PyObject_HasFastCall(fn);
    Py_SETREF(pto->fn, fn);
    Py_SETREF(pto->args, fnargs);
    Py_SETREF(pto->kw, kw);
    Py_XSETREF(pto->dict, dict);
    Py_RETURN_NONE;
}
Esempio n. 18
0
PyObject *
PyTuple_DeepCopy(register PyObject *a)
{
	PyTupleObject *np;
	PyObject **src, **dest;
	register Py_ssize_t i;
	Py_ssize_t len = Py_SIZE(a);
	np = (PyTupleObject *)PyTuple_New(len);
	if (np == NULL)
		return NULL;
	src = ((PyTupleObject *) a)->ob_item;
	dest = np->ob_item;
	for (i = 0; i < len; i++) {
		register PyObject *v = src[i];
		Py_INCREF(v);
		if (PyTuple_CheckExact(v)) {
			PyObject *w = PyTuple_DeepCopy(v);
			Py_DECREF(v);
			if (!w)	{
				Py_DECREF(np);
				return NULL;
			}
			v = w;
		}
		else if (PyList_CheckExact(v)) {
			PyObject *w = PyList_DeepCopy(v);
			Py_DECREF(v);
			if (!w)	{
				Py_DECREF(np);
				return NULL;
			}
			v = w;
		}
		else if (PyDict_CheckExact(v)) {
			PyObject *w = PyDict_DeepCopy(v);
			Py_DECREF(v);
			if (!w)	{
				Py_DECREF(np);
				return NULL;
			}
			v = w;
		}
		dest[i] = v;
	}
	return (PyObject *)np;
}
Esempio n. 19
0
PyObject*
__call__(PyObject* self_, PyObject* args, PyObject**)
{
  PyObject* status_ = nullptr;
  PyObject* headers = nullptr;

  if (!PyArg_ParseTuple(args, "OO", &status_, &headers)) {
    return nullptr;
  }

  // - Extract out the status lines
  auto self = (WsgiStartResponseObject*)self_;
  std::string status(
      PyBytes_AS_STRING(PyUnicode_AsEncodedString(status_, "utf-8", "Error")));

  size_t code;
  std::string message;
  std::tie(code, message) = ParseMessageLine(status);

  // - Extract out the headers
  assert(PyList_CheckExact(headers));

  fcgi::HttpHeader header(code, message);
  for (Py_ssize_t i = 0; i < PyList_Size(headers); ++i) {
    PyObject* pair = PyList_GET_ITEM(headers, i);
    assert(PyTuple_CheckExact(pair));

    PyObject* nameObj  = PyTuple_GET_ITEM(pair, 0);
    PyObject* valueObj = PyTuple_GET_ITEM(pair, 1);

    std::string name(
      PyBytes_AS_STRING(PyUnicode_AsEncodedString(nameObj, "utf-8", "Error")));
    std::string value(
      PyBytes_AS_STRING(PyUnicode_AsEncodedString(valueObj, "utf-8", "Error")));

    Py_DECREF(pair);
    header.Add(name, value);
  }

  // - Send header response
  assert(nullptr != self);
  assert(nullptr != self->res);
  self->res->SetResponse(header);

  Py_RETURN_NONE;
}
Esempio n. 20
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;
}
Esempio n. 21
0
/* Text encoding/decoding API */
PyObject * _PyCodec_LookupTextEncoding(const char *encoding,
                                       const char *alternate_command)
{
    _Py_IDENTIFIER(_is_text_encoding);
    PyObject *codec;
    PyObject *attr;
    int is_text_codec;

    codec = _PyCodec_Lookup(encoding);
    if (codec == NULL)
        return NULL;

    /* Backwards compatibility: assume any raw tuple describes a text
     * encoding, and the same for anything lacking the private
     * attribute.
     */
    if (!PyTuple_CheckExact(codec)) {
        attr = _PyObject_GetAttrId(codec, &PyId__is_text_encoding);
        if (attr == NULL) {
            if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
                PyErr_Clear();
            } else {
                Py_DECREF(codec);
                return NULL;
            }
        } else {
            is_text_codec = PyObject_IsTrue(attr);
            Py_DECREF(attr);
            if (is_text_codec <= 0) {
                Py_DECREF(codec);
                if (!is_text_codec)
                    PyErr_Format(PyExc_LookupError,
                                 "'%.400s' is not a text encoding; "
                                 "use %s to handle arbitrary codecs",
                                 encoding, alternate_command);
                return NULL;
            }
        }
    }

    /* This appears to be a valid text encoding */
    return codec;
}
Esempio n. 22
0
 ClassList<std::string> * GetObjectNameList( Object* pyobjreff )
 {
     Py_XINCREF( pyobjreff );
     if( PyString_CheckExact( pyobjreff ) )
     {
         ClassList< std::string > * ret = new ClassList<std::string>( 1 );
         const char* objname = PyString_AsString( pyobjreff );
         ret->add( std::string(objname) );
         objname = NULL;
         Py_XDECREF( pyobjreff );
         return ret;
     }
     if( PyTuple_CheckExact( pyobjreff ) )
     {
         int tlen = PyTuple_Size( pyobjreff );
         if( tlen <= 0 )
         {
             Py_XDECREF( pyobjreff );
             return NULL;
         }
         ClassList<std::string> * ret = new ClassList<std::string>( tlen );
         for( int i = 0; i < tlen; ++i )
         {
             Object * curpydec = PyTuple_GetItem( pyobjreff, i );
             Py_XINCREF( curpydec );
             if( !curpydec || !PyString_CheckExact( curpydec ) )
             {
                 delete ret;
                 Py_XDECREF( curpydec );
                 return NULL;
             }
             const char * dec = PyString_AsString( curpydec );
             ret->add( std::string(dec) );
             dec = NULL;
             Py_XDECREF( curpydec );
         }
         Py_XDECREF( pyobjreff );
         return ret;
     }
     Py_XDECREF( pyobjreff );
     return NULL;
 }
Esempio n. 23
0
static int _compose_handle_stopiteration(PyComposeObject* self, PyObject* exc_value) {
    PyObject* args = exc_value
                     ? PyObject_GetAttrString(exc_value, "args") // new ref
                     : NULL;

    if(args && PyTuple_CheckExact(args) && PyObject_IsTrue(args)) {
        int i;

        for(i = PyTuple_Size(args) - 1; i >= 0; i--)
            if(!messages_insert(self, PyTuple_GET_ITEM(args, i))) {
                Py_CLEAR(args);
                return 0;
            }

        Py_CLEAR(args);

    } else if(!generators_empty(self))
        messages_insert(self, Py_None);

    return 1;
}
Esempio n. 24
0
json_t *py_variable_to_json( apr_pool_t *mp, PyObject *obj )
{
  json_writer_t *writer;
  json_t *json = NULL;
  apr_pool_t *tmp_mp;

  if ( PyDict_CheckExact( obj ) || PyList_CheckExact( obj ) ||
       PyTuple_CheckExact( obj ) ) {
    apr_pool_create( &tmp_mp, NULL );
    writer = json_writer_create( tmp_mp, mp );
    py_variable_to_json_internal( obj, writer );
    json = writer->json;
    apr_pool_destroy( tmp_mp );
  }
  else {
    fprintf( stderr, "Must be an object, list or tuple.\n" );
  }

  return json;

}
Esempio n. 25
0
static PyObject *
starmap_next(starmapobject *lz)
{
	PyObject *args;
	PyObject *result;
	PyObject *it = lz->it;

	assert(PyIter_Check(it));
	args = (*it->ob_type->tp_iternext)(it);
	if (args == NULL)
		return NULL;
	if (!PyTuple_CheckExact(args)) {
		Py_DECREF(args);
		PyErr_SetString(PyExc_TypeError,
				"iterator must return a tuple");
		return NULL;
	}
	result = PyObject_Call(lz->func, args, NULL);
	Py_DECREF(args);
	return result;
}
Esempio n. 26
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);
}
Esempio n. 27
0
static PyObject*
_mktime_tuple(PyObject* self, PyObject* arg) {
	if (!PyTuple_CheckExact(arg)) return NULL;
	PyTupleObject* tuple = (PyTupleObject*) arg;
	size_t year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, size = tuple->ob_size, timestamp = 0;

	if (size > 0) year = PyInt_AsSsize_t(tuple->ob_item[0]);
	if (size > 1) month = PyInt_AsSsize_t(tuple->ob_item[1]);
	if (size > 2) day = PyInt_AsSsize_t(tuple->ob_item[2]);
	if (size > 3) hour = PyInt_AsSsize_t(tuple->ob_item[3]);
	if (size > 4) minute = PyInt_AsSsize_t(tuple->ob_item[4]);
	if (size > 5) second = PyInt_AsSsize_t(tuple->ob_item[5]);

	if (year < 1970 || year > 2038 || month > 13 || day > 32 || hour > 24 || minute > 60 || second > 60) {
		Py_RETURN_NONE;
	}

	timestamp = YEARS[year - 1970] + (IS_LEAP(year) ? MONTHS2[month] : MONTHS1[month]) +
		DAYS[day] + HOURS[hour] + MINUTES[minute] + second;

	return PyInt_FromSize_t(timestamp);
}
Esempio n. 28
0
static PyObject* new_check(PyObject* args)
{
    // We don't support a normal constructor, so only allow this for unpickling.  There should be a single arg that was
    // returned by Row_reduce.  Make sure the sizes match.  The desc and map should have one entry per column, which
    // should equal the number of remaining items.

    if (PyTuple_GET_SIZE(args) < 3)
        return 0;

    PyObject* desc = PyTuple_GET_ITEM(args, 0);
    PyObject* map  = PyTuple_GET_ITEM(args, 1);

    if (!PyTuple_CheckExact(desc) || !PyDict_CheckExact(map))
        return 0;

    Py_ssize_t cols = PyTuple_GET_SIZE(desc);

    if (PyDict_Size(map) != cols || PyTuple_GET_SIZE(args) - 2 != cols)
        return 0;

    PyObject** apValues = (PyObject**)pyodbc_malloc(sizeof(PyObject*) * cols);
    if (!apValues)
        return 0;

    for (int i = 0; i < cols; i++)
    {
        apValues[i] = PyTuple_GET_ITEM(args, i+2);
        Py_INCREF(apValues[i]);
    }

    // Row_Internal will incref desc and map.

    PyObject* self = (PyObject*)Row_InternalNew(desc, map, cols, apValues);
    if (!self)
        pyodbc_free(apValues);

    return self;
}
Esempio n. 29
0
File: key.c Progetto: dw/acid
/**
 * Concatenate a Key with another or a tuple.
 */
static PyObject *
key_concat(Key *self, PyObject *other)
{
    Key *out = NULL;
    struct writer wtr;

    if(Py_TYPE(other) == &KeyType) {
        Key *otherk = (Key *)other;
        out = acid_make_private_key(NULL, Key_SIZE(self) + Key_SIZE(otherk));
        if(out) {
            memcpy(Key_DATA(out), Key_DATA(self), Key_SIZE(self));
            memcpy(Key_DATA(out), Key_DATA(otherk), Key_SIZE(otherk));
        }
    } else if(PyTuple_CheckExact(other)) {
        if(! acid_writer_init(&wtr, Key_SIZE(self) * 2)) {
            memcpy(acid_writer_ptr(&wtr), Key_DATA(self), Key_SIZE(self));
            wtr.pos += Key_SIZE(self);

            Py_ssize_t len = PyTuple_GET_SIZE(other);
            Py_ssize_t i;
            for(i = 0; i < len; i++) {
                if(acid_write_element(&wtr, PyTuple_GET_ITEM(other, i))) {
                    break;
                }
            }
            if(i == len) { // success
                uint8_t *ptr = acid_writer_ptr(&wtr) - wtr.pos;
                out = acid_make_private_key(ptr, wtr.pos);
            }
            acid_writer_abort(&wtr);
        }
    } else {
        PyErr_Format(PyExc_TypeError, "Key.add only accepts tuples or Keys.");
    }
    return (PyObject *) out;
}
Esempio n. 30
0
PyObject*
_PyCode_ConstantKey(PyObject *op)
{
    PyObject *key;

    /* Py_None and Py_Ellipsis are singleton */
    if (op == Py_None || op == Py_Ellipsis
       || PyLong_CheckExact(op)
       || PyBool_Check(op)
       || PyBytes_CheckExact(op)
       || PyUnicode_CheckExact(op)
          /* code_richcompare() uses _PyCode_ConstantKey() internally */
       || PyCode_Check(op)) {
        key = PyTuple_Pack(2, Py_TYPE(op), op);
    }
    else if (PyFloat_CheckExact(op)) {
        double d = PyFloat_AS_DOUBLE(op);
        /* all we need is to make the tuple different in either the 0.0
         * or -0.0 case from all others, just to avoid the "coercion".
         */
        if (d == 0.0 && copysign(1.0, d) < 0.0)
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
        else
            key = PyTuple_Pack(2, Py_TYPE(op), op);
    }
    else if (PyComplex_CheckExact(op)) {
        Py_complex z;
        int real_negzero, imag_negzero;
        /* For the complex case we must make complex(x, 0.)
           different from complex(x, -0.) and complex(0., y)
           different from complex(-0., y), for any x and y.
           All four complex zeros must be distinguished.*/
        z = PyComplex_AsCComplex(op);
        real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
        imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
        /* use True, False and None singleton as tags for the real and imag
         * sign, to make tuples different */
        if (real_negzero && imag_negzero) {
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
        }
        else if (imag_negzero) {
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
        }
        else if (real_negzero) {
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
        }
        else {
            key = PyTuple_Pack(2, Py_TYPE(op), op);
        }
    }
    else if (PyTuple_CheckExact(op)) {
        Py_ssize_t i, len;
        PyObject *tuple;

        len = PyTuple_GET_SIZE(op);
        tuple = PyTuple_New(len);
        if (tuple == NULL)
            return NULL;

        for (i=0; i < len; i++) {
            PyObject *item, *item_key;

            item = PyTuple_GET_ITEM(op, i);
            item_key = _PyCode_ConstantKey(item);
            if (item_key == NULL) {
                Py_DECREF(tuple);
                return NULL;
            }

            PyTuple_SET_ITEM(tuple, i, item_key);
        }

        key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
        Py_DECREF(tuple);
    }
    else if (PyFrozenSet_CheckExact(op)) {
        Py_ssize_t pos = 0;
        PyObject *item;
        Py_hash_t hash;
        Py_ssize_t i, len;
        PyObject *tuple, *set;

        len = PySet_GET_SIZE(op);
        tuple = PyTuple_New(len);
        if (tuple == NULL)
            return NULL;

        i = 0;
        while (_PySet_NextEntry(op, &pos, &item, &hash)) {
            PyObject *item_key;

            item_key = _PyCode_ConstantKey(item);
            if (item_key == NULL) {
                Py_DECREF(tuple);
                return NULL;
            }

            assert(i < len);
            PyTuple_SET_ITEM(tuple, i, item_key);
            i++;
        }
        set = PyFrozenSet_New(tuple);
        Py_DECREF(tuple);
        if (set == NULL)
            return NULL;

        key = PyTuple_Pack(3, Py_TYPE(op), op, set);
        Py_DECREF(set);
        return key;
    }
    else {
        /* for other types, use the object identifier as a unique identifier
         * to ensure that they are seen as unequal. */
        PyObject *obj_id = PyLong_FromVoidPtr(op);
        if (obj_id == NULL)
            return NULL;

        key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
        Py_DECREF(obj_id);
    }
    return key;
}