Skip to content

Commit 10756b1

Browse files
authored
gh-111140: Minor doc fixes for PyLong_AsNativeBytes (GH-115375)
1 parent 341d787 commit 10756b1

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

Diff for: Doc/c-api/long.rst

+14-10
Original file line numberDiff line numberDiff line change
@@ -359,13 +359,16 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
359359
Copy the Python integer value to a native *buffer* of size *n_bytes*::
360360
361361
int value;
362-
Py_ssize_t bytes = PyLong_CopyBits(v, &value, sizeof(value), -1);
362+
Py_ssize_t bytes = PyLong_AsNativeBytes(v, &value, sizeof(value), -1);
363363
if (bytes < 0) {
364364
// Error occurred
365365
return NULL;
366366
}
367-
else if (bytes > sizeof(value)) {
368-
// Overflow occurred, but 'value' contains as much as could fit
367+
else if (bytes <= (Py_ssize_t)sizeof(value)) {
368+
// Success!
369+
}
370+
else {
371+
// Overflow occurred, but 'value' contains truncated value
369372
}
370373
371374
*endianness* may be passed ``-1`` for the native endian that CPython was
@@ -379,15 +382,16 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
379382
Unless an exception is raised, all *n_bytes* of the buffer will be written
380383
with as much of the value as can fit. This allows the caller to ignore all
381384
non-negative results if the intent is to match the typical behavior of a
382-
C-style downcast.
385+
C-style downcast. No exception is set for this case.
383386
384-
Values are always copied as twos-complement, and sufficient size will be
385-
requested for a sign bit. For example, this may cause an value that fits into
386-
8 bytes when treated as unsigned to request 9 bytes, even though all eight
387-
bytes were copied into the buffer. What has been omitted is the zero sign
388-
bit, which is redundant when the intention is to treat the value as unsigned.
387+
Values are always copied as two's-complement, and sufficient buffer will be
388+
requested to include a sign bit. For example, this may cause an value that
389+
fits into 8 bytes when treated as unsigned to request 9 bytes, even though
390+
all eight bytes were copied into the buffer. What has been omitted is the
391+
zero sign bit, which is redundant when the intention is to treat the value as
392+
unsigned.
389393
390-
Passing *n_bytes* of zero will always return the requested buffer size.
394+
Passing zero to *n_bytes* will return the requested buffer size.
391395
392396
.. note::
393397

0 commit comments

Comments
 (0)