Esempio n. 1
0
static PyObject *
escape_encode(PyObject *self,
              PyObject *args)
{
    PyObject *str;
    Py_ssize_t size;
    Py_ssize_t newsize;
    const char *errors = NULL;
    PyObject *v;

    if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
                          &PyBytes_Type, &str, &errors))
        return NULL;

    size = PyBytes_GET_SIZE(str);
    if (size > PY_SSIZE_T_MAX / 4) {
        PyErr_SetString(PyExc_OverflowError,
            "string is too large to encode");
            return NULL;
    }
    newsize = 4*size;
    v = PyBytes_FromStringAndSize(NULL, newsize);

    if (v == NULL) {
        return NULL;
    }
    else {
        Py_ssize_t i;
        char c;
        char *p = PyBytes_AS_STRING(v);

        for (i = 0; i < size; i++) {
            /* There's at least enough room for a hex escape */
            assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4);
            c = PyBytes_AS_STRING(str)[i];
            if (c == '\'' || c == '\\')
                *p++ = '\\', *p++ = c;
            else if (c == '\t')
                *p++ = '\\', *p++ = 't';
            else if (c == '\n')
                *p++ = '\\', *p++ = 'n';
            else if (c == '\r')
                *p++ = '\\', *p++ = 'r';
            else if (c < ' ' || c >= 0x7f) {
                *p++ = '\\';
                *p++ = 'x';
                *p++ = Py_hexdigits[(c & 0xf0) >> 4];
                *p++ = Py_hexdigits[c & 0xf];
            }
            else
                *p++ = c;
        }
Esempio n. 2
0
void get_arg::get_arg_base::finished() {
    // are there more keywords than we used?
    if(UNLIKELY(kwds && kcount < PyDict_Size(kwds))) {
        PyObject *key;
        Py_ssize_t pos = 0;
        while(PyDict_Next(kwds,&pos,&key,NULL)){
            if(!PYSTR(Check)(key)) {
                PyErr_SetString(PyExc_TypeError,"keywords must be strings");
                throw py_error_set();
            }
#if PY_MAJOR_VERSION >= 3
  #if PY_MINOR_VERSION >= 3
            const char *kstr = PyUnicode_AsUTF8(key);
            if(!kstr) throw py_error_set();
  #else
            PyObject *kstr_obj = PyUnicode_AsUTF8String(key);
            if(!kstr_obj) throw py_error_set();
            
            struct deleter {
                PyObject *ptr;
                deleter(PyObject *ptr) : ptr(ptr) {}
                ~deleter() { Py_DECREF(ptr); }
            } _(kstr_obj);
            
            const char *kstr = PyBytes_AS_STRING(kstr_obj);
  #endif
#else
            const char *kstr = PyBytes_AS_STRING(key);
#endif
            if(names) {
                for(const char **name = names; *name; ++name) {
                    if(strcmp(kstr,*name) == 0) goto match;
                }
            }
                
            PyErr_Format(PyExc_TypeError,"'%s' is an invalid keyword argument for %s%s",
                kstr,
                fname ? fname : "this function",
                fname ? "()" : "");
            throw py_error_set();
            
        match:
            ;
        }
        
        // should never reach here
        assert(false);
    }
}
Esempio n. 3
0
/* Internal routine for detaching the shared buffer of BytesIO objects.
   The caller should ensure that the 'size' argument is non-negative and
   not lesser than self->string_size.  Returns 0 on success, -1 otherwise. */
static int
unshare_buffer(bytesio *self, size_t size)
{
    PyObject *new_buf;
    assert(SHARED_BUF(self));
    assert(self->exports == 0);
    assert(size >= (size_t)self->string_size);
    new_buf = PyBytes_FromStringAndSize(NULL, size);
    if (new_buf == NULL)
        return -1;
    memcpy(PyBytes_AS_STRING(new_buf), PyBytes_AS_STRING(self->buf),
           self->string_size);
    Py_SETREF(self->buf, new_buf);
    return 0;
}
Esempio n. 4
0
// from Python/bltinmodule.c
static const char *
source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy)
{
    const char *str;
    Py_ssize_t size;
    Py_buffer view;

    *cmd_copy = NULL;
    if (PyUnicode_Check(cmd)) {
        cf->cf_flags |= PyCF_IGNORE_COOKIE;
        str = PyUnicode_AsUTF8AndSize(cmd, &size);
        if (str == NULL)
            return NULL;
    }
    else if (PyBytes_Check(cmd)) {
        str = PyBytes_AS_STRING(cmd);
        size = PyBytes_GET_SIZE(cmd);
    }
    else if (PyByteArray_Check(cmd)) {
        str = PyByteArray_AS_STRING(cmd);
        size = PyByteArray_GET_SIZE(cmd);
    }
    else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) {
        /* Copy to NUL-terminated buffer. */
        *cmd_copy = PyBytes_FromStringAndSize(
            (const char *)view.buf, view.len);
        PyBuffer_Release(&view);
        if (*cmd_copy == NULL) {
            return NULL;
        }
        str = PyBytes_AS_STRING(*cmd_copy);
        size = PyBytes_GET_SIZE(*cmd_copy);
    }
    else {
        PyErr_Format(PyExc_TypeError,
          "%s() arg 1 must be a %s object",
          funcname, what);
        return NULL;
    }

    if (strlen(str) != (size_t)size) {
        PyErr_SetString(PyExc_ValueError,
                        "source code string cannot contain null bytes");
        Py_CLEAR(*cmd_copy);
        return NULL;
    }
    return str;
}
Esempio n. 5
0
static PyObject *
PyBlosc_decompress(PyObject *self, PyObject *args)
{
    PyObject *result_str;
    void *input, *output;
    size_t nbytes, cbytes;

    if (!PyArg_ParseTuple(args, "s#:decompress", &input, &cbytes))
      return NULL;

    /*  fetch the uncompressed size into nbytes */
    if (!get_nbytes(input, cbytes, &nbytes))
      return NULL;

    /* Book memory for the result */
    if (!(result_str = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)nbytes)))
      return NULL;
    output = PyBytes_AS_STRING(result_str);

    /*  do decompression */
    if (!decompress_helper(input, nbytes, output)){
      Py_XDECREF(result_str);
      return NULL;
    }

    return result_str;
}
Esempio n. 6
0
static PyObject *
Billiard_recv(PyObject *self, PyObject *args)
{
    HANDLE handle;
    int size, nread;
    PyObject *buf;

    if (!PyArg_ParseTuple(args, F_HANDLE "i:recv" , &handle, &size))
        return NULL;

    buf = PyBytes_FromStringAndSize(NULL, size);
    if (!buf)
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    nread = recv((SOCKET) handle, PyBytes_AS_STRING(buf), size, 0);
    Py_END_ALLOW_THREADS

    if (nread < 0) {
        Py_DECREF(buf);
        return PyErr_SetExcFromWindowsErr(PyExc_IOError, WSAGetLastError());
    }
    _PyBytes_Resize(&buf, nread);
    return buf;
}
Esempio n. 7
0
remove history item given by its position");

static PyObject *
py_replace_history(PyObject *self, PyObject *args)
{
    int entry_number;
    PyObject *line;
    PyObject *encoded;
    HIST_ENTRY *old_entry;

    if (!PyArg_ParseTuple(args, "iU:replace_history_item", &entry_number,
                          &line)) {
        return NULL;
    }
    if (entry_number < 0) {
        PyErr_SetString(PyExc_ValueError,
                        "History index cannot be negative");
        return NULL;
    }
    encoded = encode(line);
    if (encoded == NULL) {
        return NULL;
    }
    old_entry = replace_history_entry(entry_number, PyBytes_AS_STRING(encoded), (void *)NULL);
    Py_DECREF(encoded);
    if (!old_entry) {
        PyErr_Format(PyExc_ValueError,
                     "No history item at position %d",
                     entry_number);
        return NULL;
    }
    /* free memory allocated for the old history entry */
    _py_free_history_entry(old_entry);
    Py_RETURN_NONE;
}
Esempio n. 8
0
PyObject * MGLTextureArray_read(MGLTextureArray * self, PyObject * args) {
	int alignment;

	int args_ok = PyArg_ParseTuple(
		args,
		"I",
		&alignment
	);

	if (!args_ok) {
		return 0;
	}

	if (alignment != 1 && alignment != 2 && alignment != 4 && alignment != 8) {
		MGLError_Set("the alignment must be 1, 2, 4 or 8");
		return 0;
	}

	int expected_size = self->width * self->components * self->data_type->size;
	expected_size = (expected_size + alignment - 1) / alignment * alignment;
	expected_size = expected_size * self->height * self->layers;

	PyObject * result = PyBytes_FromStringAndSize(0, expected_size);
	char * data = PyBytes_AS_STRING(result);

	int pixel_type = self->data_type->gl_type;
	int base_format = self->data_type->base_format[self->components];

	const GLMethods & gl = self->context->gl;

	gl.ActiveTexture(GL_TEXTURE0 + self->context->default_texture_unit);
	gl.BindTexture(GL_TEXTURE_2D_ARRAY, self->texture_obj);

	gl.PixelStorei(GL_PACK_ALIGNMENT, alignment);
	gl.PixelStorei(GL_UNPACK_ALIGNMENT, alignment);

	// To determine the required size of pixels, use glGetTexLevelParameter to determine
	// the dimensions of the internal texture image, then scale the required number of pixels
	// by the storage required for each pixel, based on format and type. Be sure to take the
	// pixel storage parameters into account, especially GL_PACK_ALIGNMENT.

	// int pack = 0;
	// gl.GetIntegerv(GL_PACK_ALIGNMENT, &pack);
	// printf("GL_PACK_ALIGNMENT: %d\n", pack);

	// glGetTexLevelParameter with argument GL_TEXTURE_WIDTH
	// glGetTexLevelParameter with argument GL_TEXTURE_HEIGHT
	// glGetTexLevelParameter with argument GL_TEXTURE_INTERNAL_FORMAT

	// int level_width = 0;
	// int level_height = 0;
	// gl.GetTexLevelParameteriv(GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &level_width);
	// gl.GetTexLevelParameteriv(GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &level_height);
	// printf("level_width: %d\n", level_width);
	// printf("level_height: %d\n", level_height);

	gl.GetTexImage(GL_TEXTURE_2D_ARRAY, 0, base_format, pixel_type, data);

	return result;
}
Esempio n. 9
0
static long __Pyx__PyObject_Ord(PyObject* c) {
    Py_ssize_t size;
    if (PyBytes_Check(c)) {
        size = PyBytes_GET_SIZE(c);
        if (likely(size == 1)) {
            return (unsigned char) PyBytes_AS_STRING(c)[0];
        }
#if PY_MAJOR_VERSION < 3
    } else if (PyUnicode_Check(c)) {
        return (long)__Pyx_PyUnicode_AsPy_UCS4(c);
#endif
#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))
    } else if (PyByteArray_Check(c)) {
        size = PyByteArray_GET_SIZE(c);
        if (likely(size == 1)) {
            return (unsigned char) PyByteArray_AS_STRING(c)[0];
        }
#endif
    } else {
        // FIXME: support character buffers - but CPython doesn't support them either
        PyErr_Format(PyExc_TypeError,
            "ord() expected string of length 1, but %.200s found", c->ob_type->tp_name);
        return (long)(Py_UCS4)-1;
    }
    PyErr_Format(PyExc_TypeError,
        "ord() expected a character, but string of length %zd found", size);
    return (long)(Py_UCS4)-1;
}
Esempio n. 10
0
static char *
on_completion(const char *text, int state)
{
    char *result = NULL;
    if (readlinestate_global->completer != NULL) {
        PyObject *r = NULL, *t;
        PyGILState_STATE gilstate = PyGILState_Ensure();
        rl_attempted_completion_over = 1;
        t = decode(text);
        r = PyObject_CallFunction(readlinestate_global->completer, "Ni", t, state);
        if (r == NULL)
            goto error;
        if (r == Py_None) {
            result = NULL;
        }
        else {
            PyObject *encoded = encode(r);
            if (encoded == NULL)
                goto error;
            result = strdup(PyBytes_AS_STRING(encoded));
            Py_DECREF(encoded);
        }
        Py_DECREF(r);
        goto done;
      error:
        PyErr_Clear();
        Py_XDECREF(r);
      done:
        PyGILState_Release(gilstate);
        return result;
    }
    return result;
}
Esempio n. 11
0
static PyObject *
_lzma__encode_filter_properties_impl(PyModuleDef *module, lzma_filter filter)
/*[clinic end generated code: output=b5fe690acd6b61d1 input=d4c64f1b557c77d4]*/
{
    lzma_ret lzret;
    uint32_t encoded_size;
    PyObject *result = NULL;

    lzret = lzma_properties_size(&encoded_size, &filter);
    if (catch_lzma_error(lzret))
        goto error;

    result = PyBytes_FromStringAndSize(NULL, encoded_size);
    if (result == NULL)
        goto error;

    lzret = lzma_properties_encode(
            &filter, (uint8_t *)PyBytes_AS_STRING(result));
    if (catch_lzma_error(lzret))
        goto error;

    return result;

error:
    Py_XDECREF(result);
    return NULL;
}
NUITKA_MAY_BE_UNUSED static bool BYTES_ADD_INCREMENTAL(PyObject **operand1, PyObject *operand2) {
    assert(PyBytes_CheckExact(*operand1));
    assert(PyBytes_CheckExact(operand2));

    // Buffer
    Py_buffer wb;
    wb.len = -1;

    if (PyObject_GetBuffer(operand2, &wb, PyBUF_SIMPLE) != 0) {
        PyErr_Format(PyExc_TypeError, "can't concat %s to %s", Py_TYPE(operand2)->tp_name, Py_TYPE(*operand1)->tp_name);

        return false;
    }

    Py_ssize_t oldsize = PyBytes_GET_SIZE(*operand1);

    if (oldsize > PY_SSIZE_T_MAX - wb.len) {
        PyErr_NoMemory();
        PyBuffer_Release(&wb);
        return false;
    }
    if (_PyBytes_Resize(operand1, oldsize + wb.len) < 0) {
        PyBuffer_Release(&wb);
        return false;
    }

    memcpy(PyBytes_AS_STRING(*operand1) + oldsize, wb.buf, wb.len);
    PyBuffer_Release(&wb);
    return true;
}
Esempio n. 13
0
static PyObject *
compress_helper(void * input, size_t nbytes, size_t typesize,
                int clevel, int shuffle, char *cname){

    int cbytes;
    PyObject *output = NULL;

    /* Alloc memory for compression */
    if (!(output = PyBytes_FromStringAndSize(NULL, nbytes+BLOSC_MAX_OVERHEAD)))
      return NULL;

    /* Select compressor */
    if (blosc_set_compressor(cname) < 0) {
      /* The compressor is not available (should never happen here) */
      blosc_error(-1, "compressor not available");
      return NULL;
    }

    /* Compress */
    cbytes = blosc_compress(clevel, shuffle, typesize, nbytes,
                            input, PyBytes_AS_STRING(output),
                            nbytes+BLOSC_MAX_OVERHEAD);
    if (cbytes < 0) {
      blosc_error(cbytes, "while compressing data");
      Py_XDECREF(output);
      return NULL;
    }

    /* Attempt to resize, if it's much smaller, a copy is required. */
    if (_PyBytes_Resize(&output, cbytes) < 0){
        /* the memory exception will have been set, hopefully */
        return NULL;
    }
    return output;
}
static PyObject*
automaton_search_iter_new(
	Automaton* automaton,
	PyObject* object,
	int start,
	int end
) {
	AutomatonSearchIter* iter;

	iter = (AutomatonSearchIter*)PyObject_New(AutomatonSearchIter, &automaton_search_iter_type);
	if (iter == NULL)
		return NULL;

	iter->automaton = automaton;
	iter->version	= automaton->version;
	iter->object	= object;
#ifdef AHOCORASICK_UNICODE
	iter->data		= PyUnicode_AS_UNICODE(object);
#else
	iter->data		= (uint8_t*)PyBytes_AS_STRING(object);
#endif

	iter->state	= automaton->root;
	iter->output= NULL;
	iter->shift	= 0;
	iter->index	= start - 1;	// -1 because first instruction in next() increments index
	iter->end	= end;

	Py_INCREF(iter->automaton);
	Py_INCREF(iter->object);

	return (PyObject*)iter;
}
Esempio n. 15
0
FILE*
_Py_fopen(PyObject *path, const char *mode)
{
#ifdef MS_WINDOWS
    wchar_t *wpath;
    wchar_t wmode[10];
    int usize;

    if (!PyUnicode_Check(path)) {
        PyErr_Format(PyExc_TypeError,
                     "str file path expected under Windows, got %R",
                     Py_TYPE(path));
        return NULL;
    }
    wpath = PyUnicode_AsUnicode(path);
    if (wpath == NULL)
        return NULL;

    usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
    if (usize == 0)
        return NULL;

    return _wfopen(wpath, wmode);
#else
    FILE *f;
    PyObject *bytes;
    if (!PyUnicode_FSConverter(path, &bytes))
        return NULL;
    f = fopen(PyBytes_AS_STRING(bytes), mode);
    Py_DECREF(bytes);
    return f;
#endif
}
Esempio n. 16
0
static int
Per_p_set_or_delattro(cPersistentObject *self, PyObject *name, PyObject *v)
{
    int result = -1;    /* guilty until proved innocent */
    PyObject *converted;
    char *s;

    converted = convert_name(name);
    if (!converted)
        goto Done;
    s = PyBytes_AS_STRING(converted);

    if (strncmp(s, "_p_", 3))
    {
        if (unghostify(self) < 0)
            goto Done;
        accessed(self);

        result = 0;
    }
    else
    {
        if (PyObject_GenericSetAttr((PyObject *)self, name, v) < 0)
            goto Done;
        result = 1;
    }

Done:
  Py_XDECREF(converted);
  return result;
}
Esempio n. 17
0
QDataStream &operator<<(QDataStream& out, const PyObjectWrapper& myObj)
{
    if (Py_IsInitialized() == 0) {
        qWarning() << "Stream operator for PyObject called without python interpreter.";
        return out;
    }

    static PyObject *reduce_func  = 0;

    Shiboken::GilState gil;
    if (!reduce_func) {
        Shiboken::AutoDecRef pickleModule(PyImport_ImportModule("pickle"));
        reduce_func = PyObject_GetAttrString(pickleModule, "dumps");
    }
    Shiboken::AutoDecRef repr(PyObject_CallFunctionObjArgs(reduce_func, (PyObject*)myObj, NULL));
    if (repr.object()) {
        const char* buff = 0;
        Py_ssize_t size  = 0;
        if (PyBytes_Check(repr.object())) {
            buff = PyBytes_AS_STRING(repr.object());
            size = PyBytes_GET_SIZE(repr.object());
        } else if (Shiboken::String::check(repr.object())) {
            buff = Shiboken::String::toCString(repr.object());
            size = Shiboken::String::len(repr.object());
        }
        QByteArray data(buff, size);
        out << data;
    }
    return out;
}
Esempio n. 18
0
File: lxc.c Progetto: asmundg/lxc
static PyObject *
Container_snapshot(Container *self, PyObject *args, PyObject *kwds)
{
    char *comment_path = NULL;
    static char *kwlist[] = {"comment_path", NULL};
    int retval = 0;
    int ret = 0;
    char newname[20];
    PyObject *py_comment_path;

    if (! PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist,
                                      PyUnicode_FSConverter, &py_comment_path))
        return NULL;

    if (py_comment_path != NULL) {
        comment_path = PyBytes_AS_STRING(py_comment_path);
        assert(comment_path != NULL);
    }

    retval = self->container->snapshot(self->container, comment_path);

    Py_XDECREF(py_comment_path);

    if (retval < 0) {
        Py_RETURN_FALSE;
    }

    ret = snprintf(newname, 20, "snap%d", retval);
    if (ret < 0 || ret >= 20)
        return NULL;


    return PyUnicode_FromString(newname);
}
Esempio n. 19
0
static PyObject *
oss_read(oss_audio_t *self, PyObject *args)
{
    Py_ssize_t size, count;
    PyObject *rv;

    if (!_is_fd_valid(self->fd))
        return NULL;

    if (!PyArg_ParseTuple(args, "n:read", &size))
        return NULL;

    rv = PyBytes_FromStringAndSize(NULL, size);
    if (rv == NULL)
        return NULL;

    count = _Py_read(self->fd, PyBytes_AS_STRING(rv), size);
    if (count == -1) {
        Py_DECREF(rv);
        return NULL;
    }

    self->icount += count;
    _PyBytes_Resize(&rv, count);
    return rv;
}
Esempio n. 20
0
File: lxc.c Progetto: asmundg/lxc
static int
Container_init(Container *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"name", "config_path", NULL};
    char *name = NULL;
    PyObject *fs_config_path = NULL;
    char *config_path = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O&", kwlist,
                                      &name,
                                      PyUnicode_FSConverter, &fs_config_path))
        return -1;

    if (fs_config_path != NULL) {
        config_path = PyBytes_AS_STRING(fs_config_path);
        assert(config_path != NULL);
    }

    self->container = lxc_container_new(name, config_path);
    if (!self->container) {
        Py_XDECREF(fs_config_path);
        fprintf(stderr, "%d: error creating container %s\n", __LINE__, name);
        return -1;
    }

    Py_XDECREF(fs_config_path);
    return 0;
}
Esempio n. 21
0
/* Internal routine to get a line from the buffer of a BytesIO
   object. Returns the length between the current position to the
   next newline character. */
static Py_ssize_t
scan_eol(bytesio *self, Py_ssize_t len)
{
    const char *start, *n;
    Py_ssize_t maxlen;

    assert(self->buf != NULL);
    assert(self->pos >= 0);

    if (self->pos >= self->string_size)
        return 0;

    /* Move to the end of the line, up to the end of the string, s. */
    maxlen = self->string_size - self->pos;
    if (len < 0 || len > maxlen)
        len = maxlen;

    if (len) {
        start = PyBytes_AS_STRING(self->buf) + self->pos;
        n = memchr(start, '\n', len);
        if (n)
            /* Get the length from the current position to the end of
               the line. */
            len = n - start + 1;
    }
    assert(len >= 0);
    assert(self->pos < PY_SSIZE_T_MAX - len);

    return len;
}
Esempio n. 22
0
static PyObject *py_zstd_uncompress(PyObject* self, PyObject *args) {

    PyObject *result;
    const char *source;
    uint32_t source_size;
    uint32_t dest_size;
    uint32_t header_size;
    size_t cSize;

#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTuple(args, "y#", &source, &source_size))
        return NULL;
#else
    if (!PyArg_ParseTuple(args, "s#", &source, &source_size))
        return NULL;
#endif

    header_size = sizeof(dest_size);

    memcpy(&dest_size, source, header_size);
    result = PyBytes_FromStringAndSize(NULL, dest_size);

    source += header_size;

    if (result != NULL && dest_size > 0) {
        char *dest = PyBytes_AS_STRING(result);

        cSize = ZSTD_decompress(dest, dest_size, source, source_size - header_size);
        if (ZSTD_isError(cSize))
            PyErr_Format(ZstdError, "Decompression error: %s", ZSTD_getErrorName(cSize));
    }

    return result;
}
Esempio n. 23
0
get the ending index of the completion scope");


/* Set the tab-completion word-delimiters that readline uses */

static PyObject *
set_completer_delims(PyObject *self, PyObject *string)
{
    char *break_chars;
    PyObject *encoded = encode(string);
    if (encoded == NULL) {
        return NULL;
    }
    /* Keep a reference to the allocated memory in the module state in case
       some other module modifies rl_completer_word_break_characters
       (see issue #17289). */
    break_chars = strdup(PyBytes_AS_STRING(encoded));
    Py_DECREF(encoded);
    if (break_chars) {
        free(completer_word_break_characters);
        completer_word_break_characters = break_chars;
        rl_completer_word_break_characters = break_chars;
        Py_RETURN_NONE;
    }
    else
        return PyErr_NoMemory();
}
Esempio n. 24
0
static PyObject*
get_http_header_key(const char *s, int len)
{
    PyObject *obj;
    char *dest;
    char c;

    obj = PyBytes_FromStringAndSize(NULL, len + prefix_len);
    dest = (char*)PyBytes_AS_STRING(obj);

    *dest++ = 'H';
    *dest++ = 'T';
    *dest++ = 'T';
    *dest++ = 'P';
    *dest++ = '_';

    while(len--) {
        c = *s++;
        if(c == '-'){
            *dest++ = '_';
        }else if(c >= 'a' && c <= 'z'){
            *dest++ = c - ('a'-'A');
        }else{
            *dest++ = c;
        }
    }

    return obj;
}
Esempio n. 25
0
static int
dbm_contains(PyObject *self, PyObject *arg)
{
    dbmobject *dp = (dbmobject *)self;
    datum key, val;
    Py_ssize_t size;

    if ((dp)->di_dbm == NULL) {
        PyErr_SetString(DbmError,
                        "DBM object has already been closed");
         return -1;
    }
    if (PyUnicode_Check(arg)) {
        key.dptr = PyUnicode_AsUTF8AndSize(arg, &size);
        key.dsize = size;
        if (key.dptr == NULL)
            return -1;
    }
    else if (!PyBytes_Check(arg)) {
        PyErr_Format(PyExc_TypeError,
                     "dbm key must be bytes or string, not %.100s",
                     arg->ob_type->tp_name);
        return -1;
    }
    else {
        key.dptr = PyBytes_AS_STRING(arg);
        key.dsize = PyBytes_GET_SIZE(arg);
    }
    val = dbm_fetch(dp->di_dbm, key);
    return val.dptr != NULL;
}
Esempio n. 26
0
int
_Py_stat(PyObject *path, struct stat *statbuf)
{
#ifdef MS_WINDOWS
    int err;
    struct _stat wstatbuf;
    wchar_t *wpath;

    wpath = PyUnicode_AsUnicode(path);
    if (wpath == NULL)
        return -2;
    err = _wstat(wpath, &wstatbuf);
    if (!err)
        statbuf->st_mode = wstatbuf.st_mode;
    return err;
#else
    int ret;
    PyObject *bytes = PyUnicode_EncodeFSDefault(path);
    if (bytes == NULL)
        return -2;
    ret = stat(PyBytes_AS_STRING(bytes), statbuf);
    Py_DECREF(bytes);
    return ret;
#endif
}
Esempio n. 27
0
static PyObject *
oss_read(oss_audio_t *self, PyObject *args)
{
    int size, count;
    char *cp;
    PyObject *rv;

    if (!_is_fd_valid(self->fd))
        return NULL;

    if (!PyArg_ParseTuple(args, "i:read", &size))
        return NULL;
    rv = PyBytes_FromStringAndSize(NULL, size);
    if (rv == NULL)
        return NULL;
    cp = PyBytes_AS_STRING(rv);

    Py_BEGIN_ALLOW_THREADS
    count = read(self->fd, cp, size);
    Py_END_ALLOW_THREADS

    if (count < 0) {
        PyErr_SetFromErrno(PyExc_IOError);
        Py_DECREF(rv);
        return NULL;
    }
    self->icount += count;
    _PyBytes_Resize(&rv, count);
    return rv;
}
Esempio n. 28
0
/* Exposed as _p_getattr method.  Test whether base getattr should be used */
static PyObject *
Per__p_getattr(cPersistentObject *self, PyObject *name)
{
    PyObject *result = NULL;    /* guilty until proved innocent */
    PyObject *converted;
    char *s;

    converted = convert_name(name);
    if (!converted)
        goto Done;
    s = PyBytes_AS_STRING(converted);

    if (*s != '_' || unghost_getattr(s))
    {
        if (unghostify(self) < 0)
            goto Done;
        accessed(self);
        result = Py_False;
    }
    else
        result = Py_True;

    Py_INCREF(result);

Done:
    Py_XDECREF(converted);
    return result;
}
Esempio n. 29
0
// Initialize the global decimal character and thousands separator character, used when parsing decimal
// objects.
//
static void init_locale_info()
{
    Object module(PyImport_ImportModule("locale"));
    if (!module)
    {
        PyErr_Clear();
        return;
    }

    Object ldict(PyObject_CallMethod(module, "localeconv", 0));
    if (!ldict)
    {
        PyErr_Clear();
        return;
    }

    PyObject* value = PyDict_GetItemString(ldict, "decimal_point");
    if (value)
    {
        if (PyBytes_Check(value) && PyBytes_Size(value) == 1)
            chDecimal = (Py_UNICODE)PyBytes_AS_STRING(value)[0];
        if (PyUnicode_Check(value) && PyUnicode_GET_SIZE(value) == 1)
            chDecimal = PyUnicode_AS_UNICODE(value)[0];
    }
}
Esempio n. 30
0
static int
Per_setattro(cPersistentObject *self, PyObject *name, PyObject *v)
{
    int result = -1;    /* guilty until proved innocent */
    PyObject *converted;
    char *s;

    converted = convert_name(name);
    if (!converted)
        goto Done;
    s = PyBytes_AS_STRING(converted);

    if (strncmp(s, "_p_", 3) != 0)
    {
        if (unghostify(self) < 0)
            goto Done;
        accessed(self);
        if (strncmp(s, "_v_", 3) != 0
            && self->state != cPersistent_CHANGED_STATE)
            {
            if (changed(self) < 0)
                goto Done;
            }
    }
    result = PyObject_GenericSetAttr((PyObject *)self, name, v);

Done:
    Py_XDECREF(converted);
    return result;
}