From abc387747dc573e05a4b31387797a0272062b2ef Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sun, 12 Apr 2009 15:51:51 +0000 Subject: Add bytes/bytearray.maketrans() to mirror str.maketrans(), and deprecate string.maketrans() which actually works on bytes. (Also closes #5675.) --- Objects/bytes_methods.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) (limited to 'Objects/bytes_methods.c') diff --git a/Objects/bytes_methods.c b/Objects/bytes_methods.c index 2d55601d39a..403b131b95c 100644 --- a/Objects/bytes_methods.c +++ b/Objects/bytes_methods.c @@ -608,3 +608,70 @@ _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len) } } + +PyDoc_STRVAR_shared(_Py_maketrans__doc__, +"B.maketrans(frm, to) -> translation table\n\ +\n\ +Return a translation table (a bytes object of length 256)\n\ +suitable for use in bytes.translate where each byte in frm is\n\ +mapped to the byte at the same position in to.\n\ +The strings frm and to must be of the same length."); + +static Py_ssize_t +_getbuffer(PyObject *obj, Py_buffer *view) +{ + PyBufferProcs *buffer = Py_TYPE(obj)->tp_as_buffer; + + if (buffer == NULL || buffer->bf_getbuffer == NULL) + { + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't support the buffer API", + Py_TYPE(obj)->tp_name); + return -1; + } + + if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0) + return -1; + return view->len; +} + +PyObject * +_Py_bytes_maketrans(PyObject *args) +{ + PyObject *frm, *to, *res = NULL; + Py_buffer bfrm, bto; + int i; + char *p; + + bfrm.len = -1; + bto.len = -1; + + if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) + return NULL; + if (_getbuffer(frm, &bfrm) < 0) + return NULL; + if (_getbuffer(to, &bto) < 0) + goto done; + if (bfrm.len != bto.len) { + PyErr_Format(PyExc_ValueError, + "maketrans arguments must have same length"); + goto done; + } + res = PyBytes_FromStringAndSize(NULL, 256); + if (!res) { + goto done; + } + p = PyBytes_AS_STRING(res); + for (i = 0; i < 256; i++) + p[i] = i; + for (i = 0; i < bfrm.len; i++) { + p[(int)((char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; + } + + done: + if (bfrm.len != -1) + PyBuffer_Release(&bfrm); + if (bto.len != -1) + PyBuffer_Release(&bto); + return res; +} -- cgit v1.2.3-65-gdbad