本文整理汇总了C++中PyBytes_Check函数的典型用法代码示例。如果您正苦于以下问题:C++ PyBytes_Check函数的具体用法?C++ PyBytes_Check怎么用?C++ PyBytes_Check使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyBytes_Check函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: PyCode_Optimize
PyObject *
PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
PyObject *lineno_obj)
{
Py_ssize_t i, j, codelen;
int nops, h, adj;
int tgt, tgttgt, opcode;
unsigned char *codestr = NULL;
unsigned char *lineno;
int *addrmap = NULL;
int new_line, cum_orig_line, last_line, tabsiz;
int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
unsigned int *blocks = NULL;
char *name;
/* Bail out if an exception is set */
if (PyErr_Occurred())
goto exitError;
/* Bypass optimization when the lineno table is too complex */
assert(PyBytes_Check(lineno_obj));
lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj);
tabsiz = PyBytes_GET_SIZE(lineno_obj);
if (memchr(lineno, 255, tabsiz) != NULL)
goto exitUnchanged;
/* Avoid situations where jump retargeting could overflow */
assert(PyBytes_Check(code));
codelen = PyBytes_GET_SIZE(code);
if (codelen > 32700)
goto exitUnchanged;
/* Make a modifiable copy of the code string */
codestr = (unsigned char *)PyMem_Malloc(codelen);
if (codestr == NULL)
goto exitError;
codestr = (unsigned char *)memcpy(codestr,
PyBytes_AS_STRING(code), codelen);
/* Verify that RETURN_VALUE terminates the codestring. This allows
the various transformation patterns to look ahead several
instructions without additional checks to make sure they are not
looking beyond the end of the code string.
*/
if (codestr[codelen-1] != RETURN_VALUE)
goto exitUnchanged;
/* Mapping to new jump targets after NOPs are removed */
addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
if (addrmap == NULL)
goto exitError;
blocks = markblocks(codestr, codelen);
if (blocks == NULL)
goto exitError;
assert(PyList_Check(consts));
for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
reoptimize_current:
opcode = codestr[i];
lastlc = cumlc;
cumlc = 0;
switch (opcode) {
/* Replace UNARY_NOT POP_JUMP_IF_FALSE
with POP_JUMP_IF_TRUE */
case UNARY_NOT:
if (codestr[i+1] != POP_JUMP_IF_FALSE
|| !ISBASICBLOCK(blocks,i,4))
continue;
j = GETARG(codestr, i+1);
codestr[i] = POP_JUMP_IF_TRUE;
SETARG(codestr, i, j);
codestr[i+3] = NOP;
goto reoptimize_current;
/* not a is b --> a is not b
not a in b --> a not in b
not a is not b --> a is b
not a not in b --> a in b
*/
case COMPARE_OP:
j = GETARG(codestr, i);
if (j < 6 || j > 9 ||
codestr[i+3] != UNARY_NOT ||
!ISBASICBLOCK(blocks,i,4))
continue;
SETARG(codestr, i, (j^1));
codestr[i+3] = NOP;
break;
/* Replace LOAD_GLOBAL/LOAD_NAME None/True/False
with LOAD_CONST None/True/False */
case LOAD_NAME:
case LOAD_GLOBAL:
j = GETARG(codestr, i);
name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j));
h = load_global(codestr, i, name, consts);
if (h < 0)
//.........这里部分代码省略.........
示例2: GetParameterInfo
static bool GetParameterInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info)
{
// Determines the type of SQL parameter that will be used for this parameter based on the Python data type.
//
// Populates `info`.
// TODO: if the param is a SQLParameter object, then bind to the wrapped value and use the input/output type from that
// Hold a reference to param until info is freed, because info will often be holding data borrowed from param.
if (PyObject_TypeCheck(param, (PyTypeObject*)SQLParameter_type))
{
info.pParam = ((SQLParameter*)param)->value;
info.InputOutputType = ((SQLParameter*)param)->type;
}
else
{
info.pParam = param;
info.InputOutputType = SQL_PARAM_INPUT;
}
if (info.pParam == Py_None)
return GetNullInfo(cur, index, info);
if (info.pParam == null_binary)
return GetNullBinaryInfo(cur, index, info);
if (PyBytes_Check(info.pParam))
return GetBytesInfo(cur, index, info.pParam, info);
if (PyUnicode_Check(info.pParam))
return GetUnicodeInfo(cur, index, info.pParam, info);
if (PyBool_Check(info.pParam))
return GetBooleanInfo(cur, index, info.pParam, info);
if (PyDateTime_Check(info.pParam))
return GetDateTimeInfo(cur, index, info.pParam, info);
if (PyDate_Check(info.pParam))
return GetDateInfo(cur, index, info.pParam, info);
if (PyTime_Check(info.pParam))
return GetTimeInfo(cur, index, info.pParam, info);
if (PyLong_Check(info.pParam))
return GetLongInfo(cur, index, info.pParam, info);
if (PyFloat_Check(info.pParam))
return GetFloatInfo(cur, index, info.pParam, info);
if (PyDecimal_Check(info.pParam))
return GetDecimalInfo(cur, index, info.pParam, info);
#if PY_VERSION_HEX >= 0x02060000
if (PyByteArray_Check(info.pParam))
return GetByteArrayInfo(cur, index, info.pParam, info);
#endif
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(info.pParam))
return GetIntInfo(cur, index, info.pParam, info);
if (PyBuffer_Check(info.pParam))
return GetBufferInfo(cur, index, info.pParam, info);
#endif
RaiseErrorV("HY105", ProgrammingError, "Invalid parameter type. param-index=%zd param-type=%s", index, Py_TYPE(info.pParam)->tp_name);
return false;
}
示例3: log_to_postgres
static PyObject *
log_to_postgres(PyObject *self, PyObject *args, PyObject *kwargs)
{
char *message = NULL;
char *hintstr = NULL,
*detailstr = NULL;
int level = 1;
int severity;
PyObject *hint,
*p_message,
*detail;
if (!PyArg_ParseTuple(args, "O|i", &p_message, &level))
{
errorCheck();
Py_INCREF(Py_None);
return Py_None;
}
if (PyBytes_Check(p_message))
{
message = PyBytes_AsString(p_message);
}
else if (PyUnicode_Check(p_message))
{
message = strdup(PyUnicode_AsPgString(p_message));
}
else
{
PyObject *temp = PyObject_Str(p_message);
errorCheck();
message = strdup(PyString_AsString(temp));
errorCheck();
Py_DECREF(temp);
}
switch (level)
{
case 0:
severity = DEBUG1;
break;
case 1:
severity = NOTICE;
break;
case 2:
severity = WARNING;
break;
case 3:
severity = ERROR;
break;
case 4:
severity = FATAL;
break;
default:
severity = INFO;
break;
}
hint = PyDict_GetItemString(kwargs, "hint");
detail = PyDict_GetItemString(kwargs, "detail");
if (errstart(severity, __FILE__, __LINE__, PG_FUNCNAME_MACRO, TEXTDOMAIN))
{
errmsg("%s", message);
if (hint != NULL && hint != Py_None)
{
hintstr = PyString_AsString(hint);
errhint("%s", hintstr);
}
if (detail != NULL && detail != Py_None)
{
detailstr = PyString_AsString(detail);
errdetail("%s", detailstr);
}
Py_DECREF(args);
Py_DECREF(kwargs);
errfinish(0);
}
else
{
Py_DECREF(args);
Py_DECREF(kwargs);
}
Py_INCREF(Py_None);
return Py_None;
}
示例4: _pyccn_cmd_encode_ContentObject
PyObject *
_pyccn_cmd_encode_ContentObject(PyObject *UNUSED(self), PyObject *args)
{
PyObject *py_content_object, *py_name, *py_content, *py_signed_info,
*py_key;
PyObject *py_o = NULL, *ret = NULL;
struct ccn_charbuf *name, *signed_info, *content_object = NULL;
struct ccn_pkey *private_key;
const char *digest_alg = NULL;
char *content;
Py_ssize_t content_len;
int r;
if (!PyArg_ParseTuple(args, "OOOOO", &py_content_object, &py_name,
&py_content, &py_signed_info, &py_key))
return NULL;
if (strcmp(py_content_object->ob_type->tp_name, "ContentObject")) {
PyErr_SetString(PyExc_TypeError, "Must pass a ContentObject as arg 1");
return NULL;
}
if (!CCNObject_IsValid(NAME, py_name)) {
PyErr_SetString(PyExc_TypeError, "Must pass a CCN Name as arg 2");
return NULL;
} else
name = CCNObject_Get(NAME, py_name);
if (py_content != Py_None && !PyBytes_Check(py_content)) {
PyErr_SetString(PyExc_TypeError, "Must pass a Bytes as arg 3");
return NULL;
} else if (py_content == Py_None) {
content = NULL;
content_len = 0;
} else {
r = PyBytes_AsStringAndSize(py_content, &content, &content_len);
if (r < 0)
return NULL;
}
if (!CCNObject_IsValid(SIGNED_INFO, py_signed_info)) {
PyErr_SetString(PyExc_TypeError, "Must pass a CCN SignedInfo as arg 4");
return NULL;
} else
signed_info = CCNObject_Get(SIGNED_INFO, py_signed_info);
if (strcmp(py_key->ob_type->tp_name, "Key")) {
PyErr_SetString(PyExc_TypeError, "Must pass a Key as arg 4");
return NULL;
}
// DigestAlgorithm
py_o = PyObject_GetAttrString(py_content_object, "digestAlgorithm");
if (py_o != Py_None) {
PyErr_SetString(PyExc_NotImplementedError, "non-default digest"
" algorithm not yet supported");
goto error;
}
Py_CLEAR(py_o);
// Key
private_key = Key_to_ccn_private(py_key);
// Note that we don't load this key into the keystore hashtable in the library
// because it makes this method require access to a ccn handle, and in fact,
// ccn_sign_content just uses what's in signedinfo (after an error check by
// chk_signing_params and then calls ccn_encode_ContentObject anyway
//
// Encode the content object
// Build the ContentObject here.
content_object = ccn_charbuf_create();
JUMP_IF_NULL_MEM(content_object, error);
r = ccn_encode_ContentObject(content_object, name, signed_info, content,
content_len, digest_alg, private_key);
debug("ccn_encode_ContentObject res=%d\n", r);
if (r < 0) {
ccn_charbuf_destroy(&content_object);
PyErr_SetString(g_PyExc_CCNError, "Unable to encode ContentObject");
goto error;
}
ret = CCNObject_New(CONTENT_OBJECT, content_object);
error:
Py_XDECREF(py_o);
return ret;
}
示例5: weechat_python_exec
void *
weechat_python_exec (struct t_plugin_script *script,
int ret_type, const char *function,
char *format, void **argv)
{
struct t_plugin_script *old_python_current_script;
PyThreadState *old_interpreter;
PyObject *evMain, *evDict, *evFunc, *rc;
void *argv2[16], *ret_value;
int i, argc, *ret_int;
ret_value = NULL;
/* PyEval_AcquireLock (); */
old_python_current_script = python_current_script;
python_current_script = script;
old_interpreter = NULL;
if (script->interpreter)
{
old_interpreter = PyThreadState_Swap (NULL);
PyThreadState_Swap (script->interpreter);
}
evMain = PyImport_AddModule ((char *) "__main__");
evDict = PyModule_GetDict (evMain);
evFunc = PyDict_GetItemString (evDict, function);
if ( !(evFunc && PyCallable_Check (evFunc)) )
{
weechat_printf (NULL,
weechat_gettext ("%s%s: unable to run function \"%s\""),
weechat_prefix ("error"), PYTHON_PLUGIN_NAME, function);
/* PyEval_ReleaseThread (python_current_script->interpreter); */
goto end;
}
if (argv && argv[0])
{
argc = strlen (format);
for (i = 0; i < 16; i++)
{
argv2[i] = (i < argc) ? argv[i] : NULL;
}
rc = PyObject_CallFunction (evFunc, format,
argv2[0], argv2[1],
argv2[2], argv2[3],
argv2[4], argv2[5],
argv2[6], argv2[7],
argv2[8], argv2[9],
argv2[10], argv2[11],
argv2[12], argv2[13],
argv2[14], argv2[15]);
}
else
{
rc = PyObject_CallFunction (evFunc, NULL);
}
/*
* ugly hack : rc = NULL while 'return weechat.WEECHAT_RC_OK ....
* because of '#define WEECHAT_RC_OK 0'
*/
if (rc == NULL)
rc = PyLong_FromLong ((long)0);
if (PyErr_Occurred())
{
PyErr_Print ();
Py_XDECREF(rc);
}
else if ((ret_type == WEECHAT_SCRIPT_EXEC_STRING) && (PyUnicode_Check (rc)))
{
ret_value = weechat_python_unicode_to_string (rc);
Py_XDECREF(rc);
}
else if ((ret_type == WEECHAT_SCRIPT_EXEC_STRING) && (PyBytes_Check (rc)))
{
if (PyBytes_AsString (rc))
ret_value = strdup (PyBytes_AsString (rc));
else
ret_value = NULL;
Py_XDECREF(rc);
}
else if ((ret_type == WEECHAT_SCRIPT_EXEC_INT) && (PY_INTEGER_CHECK(rc)))
{
ret_int = malloc (sizeof (*ret_int));
if (ret_int)
*ret_int = (int) PyLong_AsLong (rc);
ret_value = ret_int;
Py_XDECREF(rc);
}
else if (ret_type == WEECHAT_SCRIPT_EXEC_HASHTABLE)
{
ret_value = weechat_python_dict_to_hashtable (rc,
WEECHAT_SCRIPT_HASHTABLE_DEFAULT_SIZE,
WEECHAT_HASHTABLE_STRING,
WEECHAT_HASHTABLE_STRING);
Py_XDECREF(rc);
}
//.........这里部分代码省略.........
示例6: io_open
static PyObject *
io_open(PyObject *self, PyObject *args, PyObject *kwds)
{
char *kwlist[] = {"file", "mode", "buffering",
"encoding", "errors", "newline",
"closefd", NULL};
PyObject *file;
char *mode = "r";
int buffering = -1, closefd = 1;
char *encoding = NULL, *errors = NULL, *newline = NULL;
unsigned i;
int reading = 0, writing = 0, appending = 0, updating = 0;
int text = 0, binary = 0, universal = 0;
char rawmode[5], *m;
int line_buffering;
long isatty;
PyObject *raw, *modeobj = NULL, *buffer, *wrapper, *result = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist,
&file, &mode, &buffering,
&encoding, &errors, &newline,
&closefd)) {
return NULL;
}
if (!PyUnicode_Check(file) &&
!PyBytes_Check(file) &&
!PyNumber_Check(file)) {
PyObject *repr = PyObject_Repr(file);
if (repr != NULL) {
PyErr_Format(PyExc_TypeError, "invalid file: %s",
PyString_AS_STRING(repr));
Py_DECREF(repr);
}
return NULL;
}
/* Decode mode */
for (i = 0; i < strlen(mode); i++) {
char c = mode[i];
switch (c) {
case 'r':
reading = 1;
break;
case 'w':
writing = 1;
break;
case 'a':
appending = 1;
break;
case '+':
updating = 1;
break;
case 't':
text = 1;
break;
case 'b':
binary = 1;
break;
case 'U':
universal = 1;
reading = 1;
break;
default:
goto invalid_mode;
}
/* c must not be duplicated */
if (strchr(mode+i+1, c)) {
invalid_mode:
PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
return NULL;
}
}
m = rawmode;
if (reading) *(m++) = 'r';
if (writing) *(m++) = 'w';
if (appending) *(m++) = 'a';
if (updating) *(m++) = '+';
*m = '\0';
/* Parameters validation */
if (universal) {
if (writing || appending) {
PyErr_SetString(PyExc_ValueError,
"can't use U and writing mode at once");
return NULL;
}
reading = 1;
}
if (text && binary) {
PyErr_SetString(PyExc_ValueError,
"can't have text and binary mode at once");
//.........这里部分代码省略.........
示例7: PyErr_Format
PyObject *Connection_query(Connection *self, PyObject *args)
{
void *ret;
PyObject *inQuery = NULL;
PyObject *query = NULL;
PyObject *iterable = NULL;
PyObject *escapedQuery = NULL;
if (!UMConnection_IsConnected(self->conn))
{
return PyErr_Format(PyExc_RuntimeError, "Not connected");
}
if (!PyArg_ParseTuple (args, "O|O", &inQuery, &iterable))
{
return NULL;
}
if (iterable)
{
PyObject *iterator = PyObject_GetIter(iterable);
if (iterator == NULL)
{
PyErr_Clear();
return PyErr_Format(PyExc_TypeError, "Expected iterable");
}
Py_DECREF(iterator);
}
if (!PyBytes_Check(inQuery))
{
if (!PyBytes_Check(inQuery))
{
PRINTMARK();
return PyErr_Format(PyExc_TypeError, "Query argument must be either String or Unicode");
}
query = self->PFN_PyUnicode_Encode(PyBytes_AS_STRING(inQuery), PyBytes_GET_SIZE(inQuery), NULL);
if (query == NULL)
{
if (!PyErr_Occurred())
{
PyErr_SetObject(PyExc_ValueError, query);
return NULL;
}
return NULL;
}
}
else
{
query = inQuery;
Py_INCREF(query);
}
if (iterable)
{
PRINTMARK();
escapedQuery = EscapeQueryArguments(self, query, iterable);
Py_DECREF(query);
if (escapedQuery == NULL)
{
if (!PyErr_Occurred())
{
return PyErr_Format(PyExc_RuntimeError, "Exception not set in EscapeQueryArguments chain");
}
return NULL;
}
}
else
{
escapedQuery = query;
}
ret = UMConnection_Query(self->conn, PyBytes_AS_STRING(escapedQuery), PyBytes_GET_SIZE(escapedQuery));
Py_DECREF(escapedQuery);
PRINTMARK();
if (ret == NULL)
{
return HandleError(self, "query");
}
PRINTMARK();
return (PyObject *) ret;
}
示例8: PyUnicode_AsLatin1String
PyObject *_a85_encode(PyObject *module, PyObject *args)
{
unsigned char *inData;
int length, blocks, extra, i, k, lim;
unsigned long block, res;
char *buf;
PyObject *retVal=NULL, *inObj, *_o1=NULL;
if(!PyArg_ParseTuple(args, "O", &inObj)) return NULL;
if(PyUnicode_Check(inObj)){
_o1 = PyUnicode_AsLatin1String(inObj);
if(!_o1){
PyErr_SetString(PyExc_ValueError,"argument not decodable as latin1");
ERROR_EXIT();
}
inData = PyBytes_AsString(_o1);
inObj = _o1;
if(!inData){
PyErr_SetString(PyExc_ValueError,"argument not converted to internal char string");
ERROR_EXIT();
}
}
else if(!PyBytes_Check(inObj)){
PyErr_SetString(PyExc_ValueError,"argument should be " BYTESNAME " or latin1 decodable " STRNAME);
ERROR_EXIT();
}
inData = PyBytes_AsString(inObj);
length = PyBytes_GET_SIZE(inObj);
blocks = length / 4;
extra = length % 4;
buf = (char*)malloc((blocks+1)*5+3);
lim = 4*blocks;
for(k=i=0; i<lim; i += 4){
/*
* If you evere have trouble with this consider using masking to ensure
* that the shifted quantity is only 8 bits long
*/
block = ((unsigned long)inData[i]<<24)|((unsigned long)inData[i+1]<<16)
|((unsigned long)inData[i+2]<<8)|((unsigned long)inData[i+3]);
if (block == 0) buf[k++] = 'z';
else {
res = block/a85_4;
buf[k++] = (char)(res+33);
block -= res*a85_4;
res = block/a85_3;
buf[k++] = (char)(res+33);
block -= res*a85_3;
res = block/a85_2;
buf[k++] = (char)(res+33);
block -= res*a85_2;
res = block / a85_1;
buf[k++] = (char)(res+33);
buf[k++] = (char)(block-res*a85_1+33);
}
}
if(extra>0){
block = 0L;
for (i=0; i<extra; i++)
block += (unsigned long)inData[length-extra+i] << (24-8*i);
res = block/a85_4;
buf[k++] = (char)(res+33);
if(extra>=1){
block -= res*a85_4;
res = block/a85_3;
buf[k++] = (char)(res+33);
if(extra>=2){
block -= res*a85_3;
res = block/a85_2;
buf[k++] = (char)(res+33);
if(extra>=3) buf[k++] = (char)((block-res*a85_2)/a85_1+33);
}
}
}
buf[k++] = '~';
buf[k++] = '>';
retVal = PyUnicode_FromStringAndSize(buf, k);
free(buf);
if(!retVal){
PyErr_SetString(PyExc_ValueError,"failed to create return " STRNAME " value" );
ERROR_EXIT();
}
L_exit:
Py_XDECREF(_o1);
return retVal;
L_ERR:
ADD_TB(module,"asciiBase85Encode");
goto L_exit;
}
示例9: _io__IOBase_readline_impl
static PyObject *
_io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
/*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
{
/* For backwards compatibility, a (slowish) readline(). */
PyObject *peek, *buffer, *result;
Py_ssize_t old_size = -1;
if (_PyObject_LookupAttr(self, _PyIO_str_peek, &peek) < 0) {
return NULL;
}
buffer = PyByteArray_FromStringAndSize(NULL, 0);
if (buffer == NULL) {
Py_XDECREF(peek);
return NULL;
}
while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
Py_ssize_t nreadahead = 1;
PyObject *b;
if (peek != NULL) {
PyObject *readahead = PyObject_CallFunctionObjArgs(peek, _PyLong_One, NULL);
if (readahead == NULL) {
/* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
when EINTR occurs so we needn't do it ourselves. */
if (_PyIO_trap_eintr()) {
continue;
}
goto fail;
}
if (!PyBytes_Check(readahead)) {
PyErr_Format(PyExc_OSError,
"peek() should have returned a bytes object, "
"not '%.200s'", Py_TYPE(readahead)->tp_name);
Py_DECREF(readahead);
goto fail;
}
if (PyBytes_GET_SIZE(readahead) > 0) {
Py_ssize_t n = 0;
const char *buf = PyBytes_AS_STRING(readahead);
if (limit >= 0) {
do {
if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
break;
if (buf[n++] == '\n')
break;
} while (1);
}
else {
do {
if (n >= PyBytes_GET_SIZE(readahead))
break;
if (buf[n++] == '\n')
break;
} while (1);
}
nreadahead = n;
}
Py_DECREF(readahead);
}
b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
if (b == NULL) {
/* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
when EINTR occurs so we needn't do it ourselves. */
if (_PyIO_trap_eintr()) {
continue;
}
goto fail;
}
if (!PyBytes_Check(b)) {
PyErr_Format(PyExc_OSError,
"read() should have returned a bytes object, "
"not '%.200s'", Py_TYPE(b)->tp_name);
Py_DECREF(b);
goto fail;
}
if (PyBytes_GET_SIZE(b) == 0) {
Py_DECREF(b);
break;
}
old_size = PyByteArray_GET_SIZE(buffer);
if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
Py_DECREF(b);
goto fail;
}
memcpy(PyByteArray_AS_STRING(buffer) + old_size,
PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
Py_DECREF(b);
if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
break;
}
result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
//.........这里部分代码省略.........
示例10: PyBytes_GET_SIZE
PyObject *EscapeQueryArguments(Connection *self, PyObject *inQuery, PyObject *iterable)
{
size_t cbOutQuery = 0;
char *obuffer;
char *optr;
char *iptr;
int heap = 0;
int hasArg = 0;
int appendLen;
PyObject *retobj;
PyObject *iterator;
PyObject *arg;
// Estimate output length
cbOutQuery += PyBytes_GET_SIZE(inQuery);
iterator = PyObject_GetIter(iterable);
while ( (arg = PyIter_Next(iterator)))
{
// Quotes;
cbOutQuery += 2;
// Worst case escape and utf-8
if (PyBytes_Check(arg))
cbOutQuery += (PyBytes_GET_SIZE(arg) * 2);
else
if (PyBytes_Check(arg))
cbOutQuery += (PyBytes_GET_SIZE(arg) * 6);
else
cbOutQuery += 64;
Py_DECREF(arg);
}
Py_DECREF(iterator);
if (cbOutQuery > (1024 * 64))
{
/*
FIXME: Allocate a PyString and resize it just like the Python code does it */
obuffer = (char *) PyObject_Malloc(cbOutQuery);
heap = 1;
}
else
{
obuffer = (char *) alloca (cbOutQuery);
}
optr = obuffer;
iptr = PyBytes_AS_STRING(inQuery);
hasArg = 0;
iterator = PyObject_GetIter(iterable);
while (1)
{
switch (*iptr)
{
case '\0':
goto END_PARSE;
case '%':
iptr ++;
if (*iptr != 's' && *iptr != '%')
{
Py_DECREF(iterator);
if (heap) PyObject_Free(obuffer);
return PyErr_Format (PyExc_ValueError, "Found character %c expected %%", *iptr);
}
if (*iptr == '%')
{
*(optr++) = *(iptr)++;
break;
}
iptr ++;
arg = PyIter_Next(iterator);
if (arg == NULL)
{
Py_DECREF(iterator);
if (heap) PyObject_Free(obuffer);
return PyErr_Format (PyExc_ValueError, "Unexpected end of iterator found");
}
appendLen = AppendEscapedArg(self, optr, obuffer + cbOutQuery, arg);
Py_DECREF(arg);
if (appendLen == -1)
{
Py_DECREF(iterator);
//.........这里部分代码省略.........
示例11: pylzma_calculate_key
static PyObject *
pylzma_calculate_key(PyObject *self, PyObject *args, PyObject *kwargs)
{
char *password;
PARSE_LENGTH_TYPE pwlen;
int cycles;
PyObject *pysalt=NULL;
char *salt;
Py_ssize_t saltlen;
char *digest="sha256";
char key[32];
// possible keywords for this function
static char *kwlist[] = {"password", "cycles", "salt", "digest", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#i|Os", kwlist, &password, &pwlen, &cycles, &pysalt, &digest))
return NULL;
if (pysalt == Py_None) {
pysalt = NULL;
} else if (!PyBytes_Check(pysalt)) {
PyErr_Format(PyExc_TypeError, "salt must be a string, got a %s", pysalt->ob_type->tp_name);
return NULL;
}
if (strcmp(digest, "sha256") != 0) {
PyErr_Format(PyExc_TypeError, "digest %s is unsupported", digest);
return NULL;
}
if (pysalt != NULL) {
salt = PyBytes_AS_STRING(pysalt);
saltlen = PyBytes_Size(pysalt);
} else {
salt = NULL;
saltlen = 0;
}
if (cycles == 0x3f) {
int pos;
int i;
for (pos = 0; pos < saltlen; pos++)
key[pos] = salt[pos];
for (i = 0; i<pwlen && pos < 32; i++)
key[pos++] = password[i];
for (; pos < 32; pos++)
key[pos] = 0;
} else {
CSha256 sha;
long round;
int i;
long rounds = (long) 1 << cycles;
unsigned char temp[8] = { 0,0,0,0,0,0,0,0 };
Py_BEGIN_ALLOW_THREADS
Sha256_Init(&sha);
for (round = 0; round < rounds; round++) {
Sha256_Update(&sha, (Byte *) salt, saltlen);
Sha256_Update(&sha, (Byte *) password, pwlen);
Sha256_Update(&sha, (Byte *) temp, 8);
for (i = 0; i < 8; i++)
if (++(temp[i]) != 0)
break;
}
Sha256_Final(&sha, (Byte *) &key);
Py_END_ALLOW_THREADS
}
return PyBytes_FromStringAndSize(key, 32);
}
示例12: arrayflags_getitem
static PyObject *
arrayflags_getitem(PyArrayFlagsObject *self, PyObject *ind)
{
char *key = NULL;
char buf[16];
int n;
if (PyUnicode_Check(ind)) {
PyObject *tmp_str;
tmp_str = PyUnicode_AsASCIIString(ind);
if (tmp_str == NULL) {
return NULL;
}
key = PyBytes_AS_STRING(tmp_str);
n = PyBytes_GET_SIZE(tmp_str);
if (n > 16) {
Py_DECREF(tmp_str);
goto fail;
}
memcpy(buf, key, n);
Py_DECREF(tmp_str);
key = buf;
}
else if (PyBytes_Check(ind)) {
key = PyBytes_AS_STRING(ind);
n = PyBytes_GET_SIZE(ind);
}
else {
goto fail;
}
switch(n) {
case 1:
switch(key[0]) {
case 'C':
return arrayflags_contiguous_get(self);
case 'F':
return arrayflags_fortran_get(self);
case 'W':
return arrayflags_writeable_get(self);
case 'B':
return arrayflags_behaved_get(self);
case 'O':
return arrayflags_owndata_get(self);
case 'A':
return arrayflags_aligned_get(self);
case 'U':
return arrayflags_updateifcopy_get(self);
default:
goto fail;
}
break;
case 2:
if (strncmp(key, "CA", n) == 0) {
return arrayflags_carray_get(self);
}
if (strncmp(key, "FA", n) == 0) {
return arrayflags_farray_get(self);
}
break;
case 3:
if (strncmp(key, "FNC", n) == 0) {
return arrayflags_fnc_get(self);
}
break;
case 4:
if (strncmp(key, "FORC", n) == 0) {
return arrayflags_forc_get(self);
}
break;
case 6:
if (strncmp(key, "CARRAY", n) == 0) {
return arrayflags_carray_get(self);
}
if (strncmp(key, "FARRAY", n) == 0) {
return arrayflags_farray_get(self);
}
if (strncmp(key, "MASKNA", n) == 0) {
return arrayflags_maskna_get(self);
}
break;
case 7:
if (strncmp(key,"FORTRAN",n) == 0) {
return arrayflags_fortran_get(self);
}
if (strncmp(key,"BEHAVED",n) == 0) {
return arrayflags_behaved_get(self);
}
if (strncmp(key,"OWNDATA",n) == 0) {
return arrayflags_owndata_get(self);
}
if (strncmp(key,"ALIGNED",n) == 0) {
return arrayflags_aligned_get(self);
}
break;
case 9:
if (strncmp(key,"WRITEABLE",n) == 0) {
return arrayflags_writeable_get(self);
}
if (strncmp(key, "OWNMASKNA", n) == 0) {
return arrayflags_ownmaskna_get(self);
}
//.........这里部分代码省略.........
示例13: PyBytes_Check
/****************************
* SV* Py2Pl(PyObject *obj)
*
* Converts arbitrary Python data structures to Perl data structures
* Note on references: does not Py_DECREF(obj).
*
* Modifications by Eric Wilhelm 2004-07-11 marked as elw
*
****************************/
SV *Py2Pl(PyObject * const obj) {
/* elw: see what python says things are */
#if PY_MAJOR_VERSION >= 3
int const is_string = PyBytes_Check(obj) || PyUnicode_Check(obj);
#else
int const is_string = PyString_Check(obj) || PyUnicode_Check(obj);
#endif
#ifdef I_PY_DEBUG
PyObject *this_type = PyObject_Type(obj); /* new reference */
PyObject *t_string = PyObject_Str(this_type); /* new reference */
#if PY_MAJOR_VERSION >= 3
PyObject *type_str_bytes = PyUnicode_AsUTF8String(t_string); /* new reference */
char *type_str = PyBytes_AsString(type_str_bytes);
#else
char *type_str = PyString_AsString(t_string);
#endif
Printf(("type is %s\n", type_str));
printf("Py2Pl object:\n\t");
PyObject_Print(obj, stdout, Py_PRINT_RAW);
printf("\ntype:\n\t");
PyObject_Print(this_type, stdout, Py_PRINT_RAW);
printf("\n");
Printf(("String check: %i\n", is_string));
Printf(("Number check: %i\n", PyNumber_Check(obj)));
Printf(("Int check: %i\n", PyInt_Check(obj)));
Printf(("Long check: %i\n", PyLong_Check(obj)));
Printf(("Float check: %i\n", PyFloat_Check(obj)));
Printf(("Type check: %i\n", PyType_Check(obj)));
#if PY_MAJOR_VERSION < 3
Printf(("Class check: %i\n", PyClass_Check(obj)));
Printf(("Instance check: %i\n", PyInstance_Check(obj)));
#endif
Printf(("Dict check: %i\n", PyDict_Check(obj)));
Printf(("Mapping check: %i\n", PyMapping_Check(obj)));
Printf(("Sequence check: %i\n", PySequence_Check(obj)));
Printf(("Iter check: %i\n", PyIter_Check(obj)));
Printf(("Function check: %i\n", PyFunction_Check(obj)));
Printf(("Module check: %i\n", PyModule_Check(obj)));
Printf(("Method check: %i\n", PyMethod_Check(obj)));
#if PY_MAJOR_VERSION < 3
if ((obj->ob_type->tp_flags & Py_TPFLAGS_HEAPTYPE))
printf("heaptype true\n");
if ((obj->ob_type->tp_flags & Py_TPFLAGS_HAVE_CLASS))
printf("has class\n");
#else
Py_DECREF(type_str_bytes);
#endif
Py_DECREF(t_string);
Py_DECREF(this_type);
#endif
/* elw: this needs to be early */
/* None (like undef) */
if (!obj || obj == Py_None) {
Printf(("Py2Pl: Py_None\n"));
return &PL_sv_undef;
}
else
#ifdef EXPOSE_PERL
/* unwrap Perl objects */
if (PerlObjObject_Check(obj)) {
Printf(("Py2Pl: Obj_object\n"));
return ((PerlObj_object *) obj)->obj;
}
/* unwrap Perl code refs */
else if (PerlSubObject_Check(obj)) {
Printf(("Py2Pl: Sub_object\n"));
SV * ref = ((PerlSub_object *) obj)->ref;
if (! ref) { /* probably an inherited method */
if (! ((PerlSub_object *) obj)->obj)
croak("Error: could not find a code reference or object method for PerlSub");
SV * const sub_obj = (SV*)SvRV(((PerlSub_object *) obj)->obj);
HV * const pkg = SvSTASH(sub_obj);
#if PY_MAJOR_VERSION >= 3
char * const sub = PyBytes_AsString(((PerlSub_object *) obj)->sub);
#else
PyObject *obj_sub_str = PyObject_Str(((PerlSub_object *) obj)->sub); /* new ref. */
char * const sub = PyString_AsString(obj_sub_str);
#endif
GV * const gv = Perl_gv_fetchmethod_autoload(aTHX_ pkg, sub, TRUE);
if (gv && isGV(gv)) {
ref = (SV *)GvCV(gv);
}
#if PY_MAJOR_VERSION < 3
Py_DECREF(obj_sub_str);
#endif
}
return newRV_inc((SV *) ref);
}
//.........这里部分代码省略.........
示例14: pyhashxx_hashxx
static PyObject *
pyhashxx_hashxx(PyObject* self, PyObject *args, PyObject *kwds)
{
unsigned int seed = 0;
const char* err_msg = NULL;
PyObject* err_obj = NULL;
Py_ssize_t args_len = 0;
unsigned int digest = 0;
void* state = NULL;
if (kwds != NULL) {
Py_ssize_t kwds_size = PyDict_Size(kwds);
PyObject* seed_obj = PyDict_GetItemString(kwds, "seed");
if (kwds_size > 1) {
err_msg = "Unexpected keyword arguments, only 'seed' is supported.";
goto badarg;
}
if (kwds_size == 1) {
if (seed_obj == NULL) {
err_msg = "Unexpected keyword argument, only 'seed' is supported.";
goto badarg;
}
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(seed_obj))
seed = PyInt_AsLong(seed_obj);
else
#endif
if (PyLong_Check(seed_obj))
seed = PyLong_AsLong(seed_obj);
else {
err_msg = "Unexpected seed value type: %S";
err_obj = seed_obj;
goto badseed;
}
}
}
args_len = PyTuple_GET_SIZE(args);
if (args_len == 0) {
err_msg = "Received no arguments to be hashed.";
goto badarg;
}
// If possible, use the shorter, faster version that elides
// allocating the state variable because it knows there is only
// one input.
if (args_len == 1) {
PyObject* hash_obj = PyTuple_GetItem(args, 0);
int did_hash = 1;
#if PY_MAJOR_VERSION >= 3
if (PyBytes_Check(hash_obj)) {
digest = XXH32(PyBytes_AsString(hash_obj), PyBytes_Size(hash_obj), seed);
}
#else
if (PyString_Check(hash_obj)) {
digest = XXH32(PyString_AsString(hash_obj), PyString_Size(hash_obj), seed);
}
#endif
else if (PyByteArray_Check(hash_obj)) {
digest = XXH32(PyByteArray_AsString(hash_obj), PyByteArray_Size(hash_obj), seed);
}
else if (hash_obj == Py_None) {
// Nothing to hash
digest = XXH32("", 0, seed);
}
else {
did_hash = 0;
}
if (did_hash)
return Py_BuildValue("I", digest);
}
// Otherwise, do it the long, slower way
state = XXH32_init(seed);
if (_update_hash(state, args) == NULL) {
XXH32_destroy(state);
return NULL;
}
digest = XXH32_digest(state);
XXH32_destroy(state);
return Py_BuildValue("I", digest);
badarg:
PyErr_SetString(PyExc_TypeError, err_msg);
return NULL;
badseed:
PyErr_Format(PyExc_TypeError, err_msg, Py_TYPE(err_obj));
return NULL;
}
示例15: weechat_python_dict_to_hashtable
struct t_hashtable *
weechat_python_dict_to_hashtable (PyObject *dict, int size,
const char *type_keys,
const char *type_values)
{
struct t_hashtable *hashtable;
PyObject *key, *value;
Py_ssize_t pos;
char *str_key, *str_value;
hashtable = weechat_hashtable_new (size, type_keys, type_values,
NULL, NULL);
if (!hashtable)
return NULL;
pos = 0;
while (PyDict_Next (dict, &pos, &key, &value))
{
str_key = NULL;
str_value = NULL;
if (PyBytes_Check (key))
{
if (PyBytes_AsString (key))
str_key = strdup (PyBytes_AsString (key));
}
else
{
str_key = weechat_python_unicode_to_string (key);
}
if (PyBytes_Check (value))
{
if (PyBytes_AsString (value))
str_value = strdup (PyBytes_AsString (value));
}
else
{
str_value = weechat_python_unicode_to_string (value);
}
if (str_key)
{
if (strcmp (type_values, WEECHAT_HASHTABLE_STRING) == 0)
{
weechat_hashtable_set (hashtable, str_key, str_value);
}
else if (strcmp (type_values, WEECHAT_HASHTABLE_POINTER) == 0)
{
weechat_hashtable_set (hashtable, str_key,
plugin_script_str2ptr (weechat_python_plugin,
NULL, NULL,
str_value));
}
}
if (str_key)
free (str_key);
if (str_value)
free (str_value);
}
return hashtable;
}