Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions Doc/library/struct.rst
Original file line number Diff line number Diff line change
Expand Up @@ -357,8 +357,11 @@ Notes:
are used. Note that for :func:`unpack`, the ``'p'`` type code consumes
``count`` bytes, but that the :class:`!bytes` object returned can never contain more than 255
bytes.
When packing, arguments of types :class:`bytes` and :class:`bytearray`
are accepted.
When packing, any contiguous :term:`bytes-like object` is accepted.

.. versionchanged:: next
Previously only :class:`bytes` and :class:`bytearray` objects were
accepted.

(9)
For the ``'s'`` type code, the count is interpreted as the length of the
Expand All @@ -373,8 +376,11 @@ Notes:
unpacking, the resulting :class:`!bytes` object always has exactly the specified number
of bytes. As a special case, ``'0s'`` means a single, empty byte string (while
``'0c'`` means 0 characters).
When packing, arguments of types :class:`bytes` and :class:`bytearray`
are accepted.
When packing, any contiguous :term:`bytes-like object` is accepted.

.. versionchanged:: next
Previously only :class:`bytes` and :class:`bytearray` objects were
accepted.

(10)
For the ``'F'`` and ``'D'`` type codes, the packed representation uses
Expand Down
31 changes: 31 additions & 0 deletions Lib/test/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,37 @@ def test_p_code(self):
(got,) = struct.unpack(code, got)
self.assertEqual(got, expectedback)

def test_pack_s_p_bytes_like(self):
# gh-148529: the 's' and 'p' format codes accept any contiguous
# bytes-like object when packing, not only bytes and bytearray.
data = b'abcd'
providers = [
('memoryview', memoryview(data)),
('memoryview(bytearray)', memoryview(bytearray(data))),
('array', array.array('b', data)),
]
for code in ('4s', '10s', '0s', '4p', '10p', '1p'):
expected = struct.pack(code, data)
s = struct.Struct(code)
for name, value in providers:
with self.subTest(code=code, provider=name):
self.assertEqual(struct.pack(code, value), expected)
self.assertEqual(s.pack(value), expected)
buf = bytearray(s.size)
struct.pack_into(code, buf, 0, value)
self.assertEqual(bytes(buf), expected)

# Non-contiguous buffers cannot be packed and raise struct.error.
noncontig = memoryview(bytearray(b'abcdefgh'))[::2]
self.assertRaises(struct.error, struct.pack, '4s', noncontig)
self.assertRaises(struct.error, struct.pack, '4p', noncontig)

# Objects that do not support the buffer protocol still raise
# struct.error for the 's' and 'p' codes.
for bad in (5, 'string', None, [1, 2, 3]):
self.assertRaises(struct.error, struct.pack, '4s', bad)
self.assertRaises(struct.error, struct.pack, '4p', bad)

def test_705836(self):
# SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
# from the low-order discarded bits could propagate into the exponent
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:func:`struct.pack`, :func:`struct.pack_into` and :meth:`struct.Struct.pack`
now accept any contiguous :term:`bytes-like object` (such as
:class:`memoryview` or :class:`array.array`) for the ``'s'`` and ``'p'``
format codes, instead of only :class:`bytes` and :class:`bytearray`.
52 changes: 34 additions & 18 deletions Modules/_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -2347,44 +2347,58 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args,
PyObject *v = args[i++];
if (strcmp(e->format, "s") == 0) {
Py_ssize_t n;
int isstring;
const void *p;
isstring = PyBytes_Check(v);
if (!isstring && !PyByteArray_Check(v)) {
PyErr_SetString(state->StructError,
"argument for 's' must be a bytes object");
return -1;
}
if (isstring) {
Py_buffer view;
int gotview = 0;
if (PyBytes_Check(v)) {
n = PyBytes_GET_SIZE(v);
p = PyBytes_AS_STRING(v);
}
else {
else if (PyByteArray_Check(v)) {
n = PyByteArray_GET_SIZE(v);
p = PyByteArray_AS_STRING(v);
}
else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
n = view.len;
p = view.buf;
gotview = 1;
}
else {
PyErr_Format(state->StructError,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is better to only raise StructError if there were no error set or it was a TypeError. Otherwise it can shadow errors like MemoryError, OverflowError or KeyboardInterrupt.

"argument for 's' must be a bytes-like object, "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"must be a contiguous bytes-like object"

Otherwise it will be confusing for non-contiguous memoryview.

"not %.200s", Py_TYPE(v)->tp_name);
return -1;
}
if (n > code->size)
n = code->size;
if (n > 0)
memcpy(res, p, n);
if (gotview)
PyBuffer_Release(&view);
} else if (strcmp(e->format, "p") == 0) {
Py_ssize_t n;
int isstring;
const void *p;
isstring = PyBytes_Check(v);
if (!isstring && !PyByteArray_Check(v)) {
PyErr_SetString(state->StructError,
"argument for 'p' must be a bytes object");
return -1;
}
if (isstring) {
Py_buffer view;
int gotview = 0;
if (PyBytes_Check(v)) {
n = PyBytes_GET_SIZE(v);
p = PyBytes_AS_STRING(v);
}
else {
else if (PyByteArray_Check(v)) {
n = PyByteArray_GET_SIZE(v);
p = PyByteArray_AS_STRING(v);
}
else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) {
n = view.len;
p = view.buf;
gotview = 1;
}
else {
PyErr_Format(state->StructError,
"argument for 'p' must be a bytes-like object, "
"not %.200s", Py_TYPE(v)->tp_name);
return -1;
}
if (code->size == 0) {
n = 0;
}
Expand All @@ -2396,6 +2410,8 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args,
if (n > 255)
n = 255;
*res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
if (gotview)
PyBuffer_Release(&view);
} else {
if (e->pack(state, res, v, e) < 0) {
if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
Expand Down
Loading