Exemplo n.º 1
0
 void callback(uint64_t prime){
     if (*i < pi){
         PyList_SET_ITEM(list, (*i)++, PyInt_FromSize_t(prime));
     } else {
         PyObject* pyprime = PyInt_FromSize_t(prime);
         PyList_Append(list, pyprime);
         Py_DECREF(pyprime);
     }
 }
Exemplo n.º 2
0
static void pybackend_ip_choose(u_int32_t *addr)
{
    PyObject *ret = NULL;
    PyObject *arg0 = NULL;

    dbglog("pybackend plugin: ip_choose_hook(addr = %d)", *addr);

    arg0 = PyInt_FromSize_t(*addr);
    ret = pybackend_call_function("ip_choose_hook", 1, arg0);
    if (ret == NULL || ret == Py_None)
    {
        goto Exit;
    }

    if (!PyInt_Check(ret))
    {
        warn("pybackend plugin: return value of ip_choose_hook() is not an int");
        goto Exit;
    }

    //
    // No failure.
    //

    *addr = PyInt_AsUnsignedLongMask(ret);

Exit:

    Py_CLEAR(arg0);
    Py_CLEAR(ret);

    dbglog("pybackend plugin: ip_choose_hook: %d", *addr);
    return;
}
Exemplo n.º 3
0
static int pybackend_allowed_address(u_int32_t addr)
{
    int result = 0;
    PyObject *ret = NULL;
    PyObject *arg0 = NULL;

    dbglog("pybackend plugin: allowed_address_hook(addr = %d)", addr);

    arg0 = PyInt_FromSize_t(addr);
    ret = pybackend_call_function("allowed_address_hook", 1, arg0);
    if (ret == NULL || ret == Py_None)
    {
        goto Exit;
    }

    if (!PyBool_Check(ret))
    {
        warn("pybackend plugin: allowed_address_hook() did not return a boolean value");
        goto Exit;
    }

    if (ret == Py_True)
    {
        result = 1;
    }

Exit:

    Py_CLEAR(arg0);
    Py_CLEAR(ret);

    dbglog("pybackend plugin: allowed_address_hook: %d", result);
    return result;
}
Exemplo n.º 4
0
Arquivo: key.c Projeto: dw/acid
/**
 * Calculate key size.
 */
static PyObject *
key_sizeof(Key *self)
{
    size_t sz = sizeof(Key);
    if(self->flags == KEY_SHARED) {
        sz += sizeof(SharedKeyInfo);
    } else {
        sz += Key_SIZE(self);
    }
    return PyInt_FromSize_t(sz);
}
Exemplo n.º 5
0
static PyObject *
_getattr4 (PyObject *self, char *name)
{
  PyAuthData *py_ad = (PyAuthData *)self;
  struct mu_auth_data *ad = py_ad->auth_data;

  if (!ad)
    return NULL;

  if (strcmp (name, "name") == 0)
    return PyString_FromString (ad->name);
  else if (strcmp (name, "passwd") == 0)
    return PyString_FromString (ad->passwd);

  /* FIXME: The use of PyInt_FromSize_t to convert uid_t and gid_t is
     a bit dubious, but so far there's no other feasible way in Python,
     save for converting uid (gid) to string and using PyInt_FromString. */
  else if (strcmp (name, "uid") == 0)
    return PyInt_FromSize_t (ad->uid);
  else if (strcmp (name, "gid") == 0)
    return PyInt_FromSize_t (ad->gid);
  else if (strcmp (name, "gecos") == 0)
    return PyString_FromString (ad->gecos);
  else if (strcmp (name, "dir") == 0)
    return PyString_FromString (ad->dir);
  else if (strcmp (name, "shell") == 0)
    return PyString_FromString (ad->shell);
  else if (strcmp (name, "mailbox") == 0)
    return PyString_FromString (ad->mailbox);
  else if (strcmp (name, "source") == 0)
    return PyString_FromString (ad->source);
  else if (strcmp (name, "quota") == 0)
    /* FIXME: quota is mu_off_t rather than size_t.  See comment for uid
       above */
    return PyInt_FromSize_t (ad->quota);
  else if (strcmp (name, "flags") == 0)
    return PyInt_FromLong (ad->flags);
  else if (strcmp (name, "change_uid") == 0)
    return PyInt_FromLong (ad->change_uid);
  return NULL;
}
Exemplo n.º 6
0
static PyObject *
api_mime_get_num_parts (PyObject *self, PyObject *args)
{
  int status;
  size_t nparts;
  PyMime *py_mime;

  if (!PyArg_ParseTuple (args, "O!", &PyMimeType, &py_mime))
    return NULL;

  status = mu_mime_get_num_parts (py_mime->mime, &nparts);
  return status_object (status, PyInt_FromSize_t (nparts));
}
Exemplo n.º 7
0
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
#if PY_VERSION_HEX < 0x02050000
   if (ival <= LONG_MAX)
       return PyInt_FromLong((long)ival);
   else {
       unsigned char *bytes = (unsigned char *) &ival;
       int one = 1; int little = (int)*(unsigned char*)&one;
       return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
   }
#else
   return PyInt_FromSize_t(ival);
#endif
}
Exemplo n.º 8
0
static PyObject *py_lz4f_getFrameInfo(PyObject *self, PyObject *args) {
    const char *source;
    int src_size;
    LZ4F_decompressionContext_t dCtx;
    LZ4F_frameInfo_t frameInfo;
    PyObject *blkSize;
    PyObject *blkMode;
    PyObject *contChkFlag;
    PyObject *py_dCtx;
    PyObject *result = PyDict_New();
    size_t ssrc_size;
    size_t err;

    (void)self;
    if (!PyArg_ParseTuple(args, "s#O", &source, &src_size, &py_dCtx)) {
        return NULL;
    }

    dCtx = (LZ4F_decompressionContext_t)PyCapsule_GetPointer(py_dCtx, NULL);
    ssrc_size = (size_t)src_size;

    err = LZ4F_getFrameInfo(dCtx, &frameInfo, (unsigned char*)source, &ssrc_size);
    CHECK(LZ4F_isError(err), "Failed getting frameInfo. (error %i)", (int)err);

    blkSize = PyInt_FromSize_t(frameInfo.blockSizeID);
    blkMode = PyInt_FromSize_t(frameInfo.blockMode);
    contChkFlag = PyInt_FromSize_t(frameInfo.contentChecksumFlag);
    PyDict_SetItemString(result, "blkSize", blkSize);
    PyDict_SetItemString(result, "blkMode", blkMode);
    PyDict_SetItemString(result, "chkFlag", contChkFlag);


    return result;
_output_error:
    return Py_None;
}
Exemplo n.º 9
0
static PyObject* factorize(PyObject* self, PyObject* args){
    Py_ssize_t n = 0;
    if (!PyArg_ParseTuple(args, "n:factorize", &n)) return NULL;
    PyObject* prime_factorization = PyList_New(0);
    if (n < 2) return prime_factorization;
    size_t i = 0;
    while (!(n & 1)){
        n /= 2;
        i++;
    }
    if (i > 0){
        PyObject* tuple = PyTuple_Pack(2, PyInt_FromLong(2), PyInt_FromSize_t(i));
        PyList_Append(prime_factorization, tuple);
        Py_DECREF(tuple);
    }
    Py_ssize_t p = 3;
    while (p*p <= n){
        i = 0;
        while (n % p == 0){
            n /= p;
            i++;
        }
        if (i > 0){
            PyObject* tuple = PyTuple_Pack(2, PyInt_FromSsize_t(p), PyInt_FromSize_t(i));
            PyList_Append(prime_factorization, tuple);
            Py_DECREF(tuple);
        }
        p += 2;
    }
    if (n > 1){
        PyObject* tuple = PyTuple_Pack(2, PyInt_FromSsize_t(n), PyInt_FromLong(1));
        PyList_Append(prime_factorization, tuple);
        Py_DECREF(tuple);
    }
    return prime_factorization;
}
static PyObject * hash(PyObject * self, PyObject * args)
{
    PyArrayObject * desc;
    PyObject * out_list;     
    int cnt = 0;   
 
    // get reference to the numpy.ndarray that OpenCV stores the descriptor matrix in
    if(!PyArg_ParseTuple(args, "O!", &PyArray_Type, &desc)) 
    {
        PyErr_SetString(lsh_error, "Invalid arguments.");
        return NULL;
    }
    
    // get a pointer to the input matrix (must be contiguous!!!!!)
    unsigned char * arr = (unsigned char *)PyArray_DATA(desc);

    // get the dimensions of the input matrix
    npy_intp * dims = PyArray_DIMS(desc);
    
    // allocate output
    out_list = PyList_New(dims[0] * NUMBER_OF_TABLES);
    if(!out_list)
    {
        PyErr_SetString(lsh_error, "Failed to allocate list.");
        return NULL;
    }

    // for each feature...
    for(int i = 0; i < dims[0]; i++)
    {
        // for each table...
        for(int tb = 0; tb < NUMBER_OF_TABLES; tb++)
        {
            // hash the feature
            size_t key_raw = get_key(tb, arr);
            
            // store in the output
            PyObject * key = PyInt_FromSize_t(key_raw);
            PyList_SET_ITEM(out_list, cnt, key);
            cnt++;
        }    
        // move to the next feature
        arr += FEATURE_SIZE;
    }
    return out_list;
}
Exemplo n.º 11
0
static PyObject *py_lz4f_decompress(PyObject *self, PyObject *args, PyObject *keywds) {
    const char* source;
    char* dest;
    LZ4F_decompressionContext_t dCtx;
    int src_size;
    PyObject *decomp;
    PyObject *next;
    PyObject *py_dCtx;
    PyObject *result = PyDict_New();
    size_t ssrc_size;
    size_t dest_size;
    size_t err;
    static char *kwlist[] = {"source", "dCtx", "blkSizeID"};
    unsigned int blkID=7;

    (void)self;
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#O|i", kwlist, &source,
                                     &src_size, &py_dCtx, &blkID)) {
        return NULL;
    }

    dest_size = LZ4S_GetBlockSize_FromBlockId(blkID);
    dCtx = (LZ4F_decompressionContext_t)PyCapsule_GetPointer(py_dCtx, NULL);
    ssrc_size = (size_t)src_size;

    dest = (char*)malloc(dest_size);
    err = LZ4F_decompress(dCtx, dest, &dest_size, source, &ssrc_size, NULL);
    CHECK(LZ4F_isError(err), "Failed getting frameInfo. (error %i)", (int)err);
    //fprintf(stdout, "Dest_size: %zu  Error Code:%zu \n", dest_size, err);

    decomp = PyBytes_FromStringAndSize(dest, dest_size);
    next = PyInt_FromSize_t(err);
    PyDict_SetItemString(result, "decomp", decomp);
    PyDict_SetItemString(result, "next", next);

    Py_XDECREF(decomp);
    Py_XDECREF(next);
    free(dest);

    return result;
_output_error:
    return Py_None;
}
Exemplo n.º 12
0
std::vector<std::string> PyInterpreter::Complete(const std::string& cmd, int max_options)
{
    std::vector<std::string> ret;
    PyErr_Clear();

    if(pycomplete) {
        for(int i=0; i < max_options; ++i) {
#if PY_MAJOR_VERSION >= 3
            PyUniqueObj args = PyTuple_Pack( 2, PyUnicode_FromString(cmd.c_str()), PyLong_FromSize_t(i) );
            PyUniqueObj result = PyObject_CallObject(pycomplete, args);
            if (result && PyUnicode_Check(result)) {
                std::string res_str(PyUnicode_AsUTF8(result));
#else
            PyUniqueObj args = PyTuple_Pack(2, PyString_FromString(cmd.c_str()), PyInt_FromSize_t(i));
            PyUniqueObj result = PyObject_CallObject(pycomplete, args);
            if (result && PyString_Check(result)) {
                std::string res_str(PyString_AsString(result));
#endif
                if( res_str.find("__")==std::string::npos ||
                    cmd.find("__")!=std::string::npos ||
                    (cmd.size() > 0 && cmd[cmd.size()-1] == '_')
                ) {
                    ret.push_back( res_str );
                }
            }else{
                break;
            }
        }
    }

    return ret;
}

void PyInterpreter::PushCommand(const std::string& cmd)
{
    PyUniqueObj obj = EvalExec(cmd);
    if(obj && obj != Py_None) {
        const std::string output = ToString(obj);
        line_queue.push(
            ConsoleLine(output, ConsoleLineTypeOutput)
        );
    }
}
Exemplo n.º 13
0
static PyObject*
_mktime_ymd(PyObject* self, PyObject* arg) {
	if (!PyUnicode_CheckExact(arg)) return NULL;

	Py_UNICODE *src = PyUnicode_AS_UNICODE(arg), *bPtr;
	size_t year = 0, month = 0, day = 0, timestamp = 0, multiplier, size = PyUnicode_GET_SIZE(arg);

	if (size >= 4) { ATOI(src, src + 4, year); }
	if (size >= 6) { ATOI(src + 4, src + 6, month); }
	if (size >= 8) { ATOI(src + 6, src + 8, day); }

	if (year < 1970 || year > 2038 || month > 13 || day > 32) {
		Py_RETURN_NONE;
	}

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

	return PyInt_FromSize_t(timestamp);
}
Exemplo n.º 14
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);
}
Exemplo n.º 15
0
static PyObject* sys_getsizeof(PyObject* self, PyObject* args, PyObject* kwds) noexcept {
    static const char* kwlist[] = { "object", "default", 0 };
    size_t size;
    PyObject* o, * dflt = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", const_cast<char**>(kwlist), &o, &dflt))
        return NULL;

    size = _PySys_GetSizeOf(o);

    if (size == (size_t)-1 && PyErr_Occurred()) {
        /* Has a default value been given */
        if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
            PyErr_Clear();
            Py_INCREF(dflt);
            return dflt;
        } else
            return NULL;
    }

    return PyInt_FromSize_t(size);
}
Exemplo n.º 16
0
static void pybackend_notifier(void *hook, int arg)
{
    const char *name = (const char *)hook;
    PyObject *ret = NULL;
    PyObject *arg0 = NULL;

    dbglog("pybackend plugin: %s(arg = %d)", name, arg);

    arg0 = PyInt_FromSize_t(arg);
    ret = pybackend_call_function(name, 1, arg0);
    if (ret == NULL || ret == Py_None)
    {
        goto Exit;
    }

Exit:

    Py_CLEAR(arg0);
    Py_CLEAR(ret);

    dbglog("pybackend plugin: %s: void", name);
    return;
}
Exemplo n.º 17
0
void Pywrap::AddArgument (unsigned int argument)
{
    PyTuple_SetItem(args, index, PyInt_FromSize_t(argument));
    index++;
}
Exemplo n.º 18
0
PyObject *
option(PyObject *self, PyObject *args)
{
    long option;
    int error;
    PyObject *py_option;

    py_option = PyTuple_GetItem(args, 0);
    if (!py_option)
        return NULL;

    if (!PyInt_Check(py_option))
        return Error_type_error(
            "option should be an integer, got %.200s", py_option);

    option = PyInt_AsLong(py_option);

    switch (option) {

        case GIT_OPT_GET_MWINDOW_SIZE:
        {
            size_t size;

            error = git_libgit2_opts(GIT_OPT_GET_MWINDOW_SIZE, &size);
            if (error < 0)
                return Error_set(error);

            return PyInt_FromSize_t(size);
        }

        case GIT_OPT_SET_MWINDOW_SIZE:
        {
            size_t size;
            PyObject *py_size;

            py_size = PyTuple_GetItem(args, 1);
            if (!py_size)
                return NULL;

            if (!PyInt_Check(py_size))
                return Error_type_error(
                    "size should be an integer, got %.200s", py_size);

            size = PyInt_AsSize_t(py_size);
            error = git_libgit2_opts(GIT_OPT_SET_MWINDOW_SIZE, size);
            if (error  < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_GET_MWINDOW_MAPPED_LIMIT:
        {
            size_t limit;

            error = git_libgit2_opts(GIT_OPT_GET_MWINDOW_MAPPED_LIMIT, &limit);
            if (error < 0)
                return Error_set(error);

            return PyInt_FromSize_t(limit);
        }

        case GIT_OPT_SET_MWINDOW_MAPPED_LIMIT:
        {
            size_t limit;
            PyObject *py_limit;

            py_limit = PyTuple_GetItem(args, 1);
            if (!py_limit)
                return NULL;

            if (PyInt_Check(py_limit)) {
                limit = PyInt_AsSize_t(py_limit);
            } else if (PyLong_Check(py_limit)) {
                limit = PyLong_AsSize_t(py_limit);
            } else {
                return Error_type_error(
                    "limit should be an integer, got %.200s", py_limit);
            }

            error = git_libgit2_opts(GIT_OPT_SET_MWINDOW_MAPPED_LIMIT, limit);
            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_GET_SEARCH_PATH:
        {
            PyObject *py_level;

            py_level = PyTuple_GetItem(args, 1);
            if (!py_level)
                return NULL;

            if (!PyInt_Check(py_level))
                return Error_type_error(
                    "level should be an integer, got %.200s", py_level);

            return get_search_path(PyInt_AsLong(py_level));
        }

        case GIT_OPT_SET_SEARCH_PATH:
        {
            PyObject *py_level, *py_path, *tpath;
            const char *path;
            int err;

            py_level = PyTuple_GetItem(args, 1);
            if (!py_level)
                return NULL;

            py_path = PyTuple_GetItem(args, 2);
            if (!py_path)
                return NULL;

            if (!PyInt_Check(py_level))
                return Error_type_error(
                    "level should be an integer, got %.200s", py_level);

            path = py_str_borrow_c_str(&tpath, py_path, NULL);
            if (!path)
                return NULL;

            err = git_libgit2_opts(
                GIT_OPT_SET_SEARCH_PATH, PyInt_AsLong(py_level), path);
            Py_DECREF(tpath);

            if (err < 0)
                return Error_set(err);

            Py_RETURN_NONE;
        }

        case GIT_OPT_SET_CACHE_OBJECT_LIMIT:
        {
            size_t limit;
            int object_type;
            PyObject *py_object_type, *py_limit;

            py_object_type = PyTuple_GetItem(args, 1);
            if (!py_object_type)
                return NULL;

            py_limit = PyTuple_GetItem(args, 2);
            if (!py_limit)
                return NULL;

            if (!PyInt_Check(py_limit))
                return Error_type_error(
                    "limit should be an integer, got %.200s", py_limit);

            object_type = PyInt_AsLong(py_object_type);
            limit = PyInt_AsSize_t(py_limit);
            error = git_libgit2_opts(
                GIT_OPT_SET_CACHE_OBJECT_LIMIT, object_type, limit);

            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_SET_CACHE_MAX_SIZE:
        {
            size_t max_size;
            PyObject *py_max_size;

            py_max_size = PyTuple_GetItem(args, 1);
            if (!py_max_size)
                return NULL;

            if (!PyInt_Check(py_max_size))
                return Error_type_error(
                    "max_size should be an integer, got %.200s", py_max_size);

            max_size = PyInt_AsSize_t(py_max_size);
            error = git_libgit2_opts(GIT_OPT_SET_CACHE_MAX_SIZE, max_size);
            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        case GIT_OPT_GET_CACHED_MEMORY:
        {
            size_t current;
            size_t allowed;
            PyObject* tup = PyTuple_New(2);

            error = git_libgit2_opts(GIT_OPT_GET_CACHED_MEMORY, &current, &allowed);
            if (error < 0)
                return Error_set(error);

            PyTuple_SetItem(tup, 0, PyInt_FromLong(current));
            PyTuple_SetItem(tup, 1, PyInt_FromLong(allowed));

            return tup;
        }

        case GIT_OPT_SET_SSL_CERT_LOCATIONS:
        {
            PyObject *py_file, *py_dir;
            const char *file_path, *dir_path;
            int err;

            py_file = PyTuple_GetItem(args, 1);
            py_dir = PyTuple_GetItem(args, 2);

            /* py_file and py_dir are only valid if they are strings */
            if (PyUnicode_Check(py_file) || PyBytes_Check(py_file)) {
                file_path = py_str_to_c_str(py_file, Py_FileSystemDefaultEncoding);
            } else {
                file_path = NULL;
            }

            if (PyUnicode_Check(py_dir) || PyBytes_Check(py_dir)) {
                dir_path = py_str_to_c_str(py_dir, Py_FileSystemDefaultEncoding);
            } else {
                dir_path = NULL;
            }

            err = git_libgit2_opts(GIT_OPT_SET_SSL_CERT_LOCATIONS, file_path, dir_path);

            if (err < 0)
                return Error_set(err);

            Py_RETURN_NONE;
        }

        // int enabled
        case GIT_OPT_ENABLE_CACHING:
        case GIT_OPT_ENABLE_STRICT_OBJECT_CREATION:
        case GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION:
        case GIT_OPT_ENABLE_OFS_DELTA:
        case GIT_OPT_ENABLE_FSYNC_GITDIR:
        case GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION:
        case GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY:
        {
            PyObject *py_enabled;
            int enabled;

            py_enabled = PyTuple_GetItem(args, 1);
            if (!py_enabled)
                return NULL;

            if (!PyInt_Check(py_enabled))
                return Error_type_error("expected integer, got %.200s", py_enabled);

            enabled = PyInt_AsSize_t(py_enabled);
            error = git_libgit2_opts(option, enabled);
            if (error < 0)
                return Error_set(error);

            Py_RETURN_NONE;
        }

        // Not implemented
        case GIT_OPT_GET_TEMPLATE_PATH:
        case GIT_OPT_SET_TEMPLATE_PATH:
        case GIT_OPT_SET_USER_AGENT:
        case GIT_OPT_SET_SSL_CIPHERS:
        case GIT_OPT_GET_USER_AGENT:
        case GIT_OPT_GET_WINDOWS_SHAREMODE:
        case GIT_OPT_SET_WINDOWS_SHAREMODE:
        case GIT_OPT_SET_ALLOCATOR:
        case GIT_OPT_GET_PACK_MAX_OBJECTS:
        case GIT_OPT_SET_PACK_MAX_OBJECTS:
        {
            Py_INCREF(Py_NotImplemented);
            return Py_NotImplemented;
        }

    }

    PyErr_SetString(PyExc_ValueError, "unknown/unsupported option value");
    return NULL;
}
Exemplo n.º 19
0
static void _seq_set_int(PyObject* seq, locale_t loc, ssize_t index, char data) {
	PyObject* item = PyInt_FromSize_t(data);

	if (item!=NULL)
		PyStructSequence_SET_ITEM(seq, index, item);
}
Exemplo n.º 20
0
 void callback(uint64_t p){
     if (++i == n){
         prime = PyInt_FromSize_t(p);
         throw StopPrimeGeneration();
     }
 }
Exemplo n.º 21
0
PyObject* XPolygon_size(PyObject *obj, PyObject *args)
{
	XPolygon *self = (XPolygon*)obj;

	return PyInt_FromSize_t(self->line_ring.point_list.size());
}
Exemplo n.º 22
0
static PyObject *
sizeof_py_ssize_t(PyObject *self, PyObject *args)
{
    return PyInt_FromSize_t(sizeof(Py_ssize_t));
}
Exemplo n.º 23
0
static void
_sieve_action_printer (void *data, mu_stream_t stream,
		       size_t msgno, mu_message_t msg,
		       const char *action, const char *fmt, va_list ap)
{
  PyObject *py_args;
  PyObject *py_dict = PyDict_New ();
  PyStream *py_stm;

  if (!py_dict)
    return;
  py_stm = PyStream_NEW ();
  if (py_stm)
    {
      PyMessage *py_msg = PyMessage_NEW ();
      char *buf = NULL;
      size_t buflen = 0;

      if (py_msg)
	{
	  PyStream *py_stm = PyStream_NEW ();
	  if (py_stm)
	    {
	      py_stm->stm = stream;
	      mu_stream_ref (stream);
	  
	      py_msg->msg = msg;
	      Py_INCREF (py_msg);

	      PyDict_SetItemString (py_dict, "msgno",
				    PyInt_FromSize_t (msgno));
	      PyDict_SetItemString (py_dict, "msg", (PyObject *)py_msg);
	      PyDict_SetItemString (py_dict, "action",
				    PyString_FromString (action ? action : ""));

	      if (mu_vasnprintf (&buf, &buflen, fmt, ap))
		{
		  mu_stream_unref (stream);
		  return;
		}
	      PyDict_SetItemString (py_dict, "text",
				    PyString_FromString (buf ? buf : ""));
	      free (buf);

	      py_args = PyTuple_New (1);
	      if (py_args)
		{
		  struct _mu_py_sieve_logger *s = data;
		  PyObject *py_fnc = s->py_action_printer;

		  Py_INCREF (py_dict);
		  PyTuple_SetItem (py_args, 0, py_dict);
		  
		  if (py_fnc && PyCallable_Check (py_fnc))
		    PyObject_CallObject (py_fnc, py_args);

		  Py_DECREF (py_dict);
		  Py_DECREF (py_args);
		}
	    }
	}
    }
}
Exemplo n.º 24
0
//  _tnetstring_load:  parse tnetstring-format value from a file.
//
//  This takes care to read no more data than is required to get the
//  full tnetstring-encoded value.  It might read arbitrarily-much
//  data if the file doesn't begin with a valid tnetstring.
//
static PyObject*
_tnetstring_load(PyObject* self, PyObject *args) 
{
  PyObject *val = NULL;
  PyObject *file = NULL;
  PyObject *encoding = Py_None;
  PyObject *methnm = NULL;
  PyObject *metharg = NULL;
  PyObject *res = NULL;
  tns_ops *ops = &_tnetstring_ops_bytes;
  char c, *data;
  size_t datalen = 0;

  if(!PyArg_UnpackTuple(args, "load", 1, 2, &file, &encoding)) {
      goto error;
  }
  Py_INCREF(file);

  if(encoding != Py_None) {
      if(!PyString_Check(encoding)) {
          PyErr_SetString(PyExc_TypeError, "encoding must be a string");
          goto error;
      }
      Py_INCREF(encoding);
      ops = _tnetstring_get_unicode_ops(encoding);
      if(ops == NULL) {
          goto error;
      }
  }

  //  We're going to read one char at a time
  if((methnm = PyString_FromString("read")) == NULL) {
      goto error;
  }
  if((metharg = PyInt_FromLong(1)) == NULL) {
      goto error;
  }

  //  Read the length prefix one char at a time
  res = PyObject_CallMethodObjArgs(file, methnm, metharg, NULL);
  if(res == NULL) {
      goto error;
  }
  Py_INCREF(res);
  if(!PyString_Check(res) || !PyString_GET_SIZE(res)) {
      PyErr_SetString(PyExc_ValueError,
                      "Not a tnetstring: invalid or missing length prefix");
      goto error;
  }
  c = PyString_AS_STRING(res)[0];
  Py_DECREF(res); res = NULL;
  //  Note that the netstring spec explicitly forbids padding zeroes.
  //  If the first char is zero, it must be the only char.
  if(c < '0' || c > '9') {
      PyErr_SetString(PyExc_ValueError,
                      "Not a tnetstring: invalid or missing length prefix");
      goto error;
  } else if (c == '0') {
      res = PyObject_CallMethodObjArgs(file, methnm, metharg, NULL);
      if(res == NULL) {
          goto error;
      }
      Py_INCREF(res);
      if(!PyString_Check(res) || !PyString_GET_SIZE(res)) {
          PyErr_SetString(PyExc_ValueError,
                      "Not a tnetstring: invalid or missing length prefix");
          goto error;
      }
      c = PyString_AS_STRING(res)[0];
      Py_DECREF(res); res = NULL;
  } else {
      do {
          datalen = (10 * datalen) + (c - '0');
          check(datalen <= TNS_MAX_LENGTH,
                "Not a tnetstring: absurdly large length prefix"); 
          res = PyObject_CallMethodObjArgs(file, methnm, metharg, NULL);
          if(res == NULL) {
              goto error;
          }
          Py_INCREF(res);
          if(!PyString_Check(res) || !PyString_GET_SIZE(res)) {
              PyErr_SetString(PyExc_ValueError,
                        "Not a tnetstring: invalid or missing length prefix");
              goto error;
          }
          c = PyString_AS_STRING(res)[0];
          Py_DECREF(res); res = NULL;
      } while(c >= '0' && c <= '9');
  }

  //  Validate end-of-length-prefix marker.
  if(c != ':') {
      PyErr_SetString(PyExc_ValueError,
                      "Not a tnetstring: missing length prefix");
      goto error;
  }
  
  //  Read the data plus terminating type tag.
  Py_DECREF(metharg);
  if((metharg = PyInt_FromSize_t(datalen + 1)) == NULL) {
      goto error;
  } 
  res = PyObject_CallMethodObjArgs(file, methnm, metharg, NULL);
  if(res == NULL) {
      goto error;
  }
  Py_INCREF(res);
  Py_DECREF(file); file = NULL;
  Py_DECREF(methnm); methnm = NULL;
  Py_DECREF(metharg); metharg = NULL;
  if(!PyString_Check(res) || PyString_GET_SIZE(res) != datalen + 1) {
      PyErr_SetString(PyExc_ValueError,
                      "Not a tnetstring: invalid length prefix");
      goto error;
  }

  //  Parse out the payload object
  data = PyString_AS_STRING(res);
  val = tns_parse_payload(ops, data[datalen], data, datalen);
  Py_DECREF(res); res = NULL;

  if(ops != &_tnetstring_ops_bytes) {
      free(ops);
      Py_DECREF(encoding);
  }

  return val;

error:
  if(file != NULL) {
      Py_DECREF(file);
  }
  if(ops != &_tnetstring_ops_bytes) {
      free(ops);
      Py_DECREF(encoding);
  }
  if(methnm != NULL) {
      Py_DECREF(methnm);
  }
  if(metharg != NULL) {
      Py_DECREF(metharg);
  }
  if(res != NULL) {
      Py_DECREF(res);
  }
  if(val != NULL) {
      Py_DECREF(val);
  }
  return NULL;
}
Exemplo n.º 25
0
static PyObject *get_noperands(instruction_t *self, PyObject *args)
{
    return PyInt_FromSize_t(xed_decoded_inst_noperands(self->decoded_inst));
}
Exemplo n.º 26
0
static PyObject *
get_thread_lock_count(PyObject *self)
{
    (void)self;
    return PyInt_FromSize_t(thread_lock_count);
}