bpo-22385: Support output separators in hex methods. (#13578)

* bpo-22385: Support output separators in hex methods.

Also in binascii.hexlify aka b2a_hex.

The underlying implementation behind all hex generation in CPython uses the
same pystrhex.c implementation.  This adds support to bytes, bytearray,
and memoryview objects.

The binascii module functions exist rather than being slated for deprecation
because they return bytes rather than requiring an intermediate step through a
str object.

This change was inspired by MicroPython which supports sep in its binascii
implementation (and does not yet support the .hex methods).

https://bugs.python.org/issue22385
This commit is contained in:
Gregory P. Smith 2019-05-29 11:46:58 -07:00 committed by GitHub
parent aacc77fbd7
commit 0c2f930564
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 624 additions and 64 deletions

View file

@ -2416,18 +2416,36 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
return NULL;
}
PyDoc_STRVAR(hex__doc__,
"B.hex() -> string\n\
\n\
Create a string of hexadecimal numbers from a bytes object.\n\
Example: b'\\xb9\\x01\\xef'.hex() -> 'b901ef'.");
/*[clinic input]
bytes.hex
sep: object = NULL
An optional single character or byte to separate hex bytes.
bytes_per_sep: int = 1
How many bytes between separators. Positive values count from the
right, negative values count from the left.
Create a str of hexadecimal numbers from a bytes object.
Example:
>>> value = b'\xb9\x01\xef'
>>> value.hex()
'b901ef'
>>> value.hex(':')
'b9:01:ef'
>>> value.hex(':', 2)
'b9:01ef'
>>> value.hex(':', -2)
'b901:ef'
[clinic start generated code]*/
static PyObject *
bytes_hex(PyBytesObject *self, PyObject *Py_UNUSED(ignored))
bytes_hex_impl(PyBytesObject *self, PyObject *sep, int bytes_per_sep)
/*[clinic end generated code: output=1f134da504064139 input=f1238d3455990218]*/
{
char* argbuf = PyBytes_AS_STRING(self);
Py_ssize_t arglen = PyBytes_GET_SIZE(self);
return _Py_strhex(argbuf, arglen);
return _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
}
static PyObject *
@ -2452,7 +2470,7 @@ bytes_methods[] = {
{"find", (PyCFunction)bytes_find, METH_VARARGS,
_Py_find__doc__},
BYTES_FROMHEX_METHODDEF
{"hex", (PyCFunction)bytes_hex, METH_NOARGS, hex__doc__},
BYTES_HEX_METHODDEF
{"index", (PyCFunction)bytes_index, METH_VARARGS, _Py_index__doc__},
{"isalnum", stringlib_isalnum, METH_NOARGS,
_Py_isalnum__doc__},