summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorXiang Zhang <angwerzx@126.com>2017-03-14 07:07:15 (GMT)
committerGitHub <noreply@github.com>2017-03-14 07:07:15 (GMT)
commit7e2a54cdd977078b40b82182e46b201f8163f659 (patch)
tree2a5116ab3cd37f53f7bf5b1ba9b569fb7e887e54 /Objects
parent9e52c907b5511393ab7e44321e9521fe0967e34d (diff)
downloadcpython-7e2a54cdd977078b40b82182e46b201f8163f659.zip
cpython-7e2a54cdd977078b40b82182e46b201f8163f659.tar.gz
cpython-7e2a54cdd977078b40b82182e46b201f8163f659.tar.bz2
bpo-28856: Let %b format for bytes support objects that follow the buffer protocol (GH-546)
Diffstat (limited to 'Objects')
-rw-r--r--Objects/bytesobject.c15
1 files changed, 14 insertions, 1 deletions
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c
index c4ef495..1050a93 100644
--- a/Objects/bytesobject.c
+++ b/Objects/bytesobject.c
@@ -528,6 +528,8 @@ byte_converter(PyObject *arg, char *p)
return 0;
}
+static PyObject *_PyBytes_FromBuffer(PyObject *x);
+
static PyObject *
format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen)
{
@@ -564,8 +566,19 @@ format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen)
*plen = PyBytes_GET_SIZE(result);
return result;
}
+ /* does it support buffer protocol? */
+ if (PyObject_CheckBuffer(v)) {
+ /* maybe we can avoid making a copy of the buffer object here? */
+ result = _PyBytes_FromBuffer(v);
+ if (result == NULL)
+ return NULL;
+ *pbuf = PyBytes_AS_STRING(result);
+ *plen = PyBytes_GET_SIZE(result);
+ return result;
+ }
PyErr_Format(PyExc_TypeError,
- "%%b requires bytes, or an object that implements __bytes__, not '%.100s'",
+ "%%b requires a bytes-like object, "
+ "or an object that implements __bytes__, not '%.100s'",
Py_TYPE(v)->tp_name);
return NULL;
}