diff options
author | Daniele Varrazzo <daniele.varrazzo@gmail.com> | 2010-12-23 19:10:07 +0100 |
---|---|---|
committer | Daniele Varrazzo <daniele.varrazzo@gmail.com> | 2010-12-31 03:18:26 +0100 |
commit | b4685bba4afff9eedfa0b03c1de815cfe738151f (patch) | |
tree | e1d8302e4868e9470d483ad7547536ed2af9ae84 /psycopg/utils.c | |
parent | 03dde732f6f14581d7f19ecda260087d4e6e6aaa (diff) | |
download | psycopg2-b4685bba4afff9eedfa0b03c1de815cfe738151f.tar.gz |
Added utility function to get bytes from a str/unicode.
Diffstat (limited to 'psycopg/utils.c')
-rw-r--r-- | psycopg/utils.c | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/psycopg/utils.c b/psycopg/utils.c index f2a0ab0..e5b221f 100644 --- a/psycopg/utils.c +++ b/psycopg/utils.c @@ -92,3 +92,29 @@ psycopg_strdup(const char *from, Py_ssize_t len) return rv; } +/* Ensure a Python object is a bytes string. + * + * Useful when a char * is required out of it. + * + * Return a new reference. NULL on error. + */ +PyObject * +psycopg_ensure_bytes(PyObject *obj) +{ + PyObject *rv = NULL; + + if (PyUnicode_CheckExact(obj)) { + rv = PyUnicode_AsUTF8String(obj); + } + else if (Bytes_CheckExact(obj)) { + Py_INCREF(obj); + rv = obj; + } + else { + PyErr_Format(PyExc_TypeError, "I'm not into ensuring %s as bytes", + obj ? Py_TYPE(obj)->tp_name : "NULL"); + } + + return rv; +} + |