Skip to content

Commit

Permalink
Fix the API name in the doc example, improve test.
Browse files Browse the repository at this point in the history
This also makes the example more realistic, people are unlikely to want
this API to get a value into a simple `int` type, we've got direct APIs
for that. So have the example use an array as if it is a bignum of its
own.

I start by fixing the API name in the doc example as scoder@ noted in
the original code review after merge.  But I noticed one thing in the
test that could be done better so I added that as well: we need to
guarantee that all bytes of the result are overwritten.  This now
pre-fills the result with data in order to ensure that.  _(assuming
ctypes isn't undoing that behind the scenes...)_
  • Loading branch information
gpshead committed Feb 12, 2024
1 parent 341d787 commit 0302840
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
10 changes: 5 additions & 5 deletions Doc/c-api/long.rst
Original file line number Diff line number Diff line change
Expand Up @@ -358,14 +358,14 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
Copy the Python integer value to a native *buffer* of size *n_bytes*::
int value;
Py_ssize_t bytes = PyLong_CopyBits(v, &value, sizeof(value), -1);
unsigned bignum[4]; // Example size chosen by random die roll.
Py_ssize_t bytes = PyLong_AsNativeBits(v, &bignum, sizeof(bignum), -1);
if (bytes < 0) {
// Error occurred
// A Python exception was set with the reason.
return NULL;
}
else if (bytes > sizeof(value)) {
// Overflow occurred, but 'value' contains as much as could fit
else if (bytes > sizeof(bignum)) {
// Overflow occurred, but 'bignum' contains as much as could fit.
}
*endianness* may be passed ``-1`` for the native endian that CPython was
Expand Down
4 changes: 3 additions & 1 deletion Lib/test/test_capi/test_long.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,9 @@ def test_long_asnativebytes(self):
]:
with self.subTest(f"{v:X}-{len(expect_be)}bytes"):
n = len(expect_be)
buffer = bytearray(n)
# Fill the buffer with dummy data to ensure all bytes
# are overwritten.
buffer = bytearray(b'\xa5'*n)
expect_le = expect_be[::-1]

self.assertEqual(expect_n, asnativebytes(v, buffer, n, 0),
Expand Down

0 comments on commit 0302840

Please sign in to comment.