@@ -359,13 +359,16 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
359
359
Copy the Python integer value to a native *buffer* of size *n_bytes*::
360
360
361
361
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 );
363
363
if (bytes < 0 ) {
364
364
// Error occurred
365
365
return NULL;
366
366
}
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
369
372
}
370
373
371
374
*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.
379
382
Unless an exception is raised, all *n_bytes * of the buffer will be written
380
383
with as much of the value as can fit. This allows the caller to ignore all
381
384
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.
383
386
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.
389
393
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.
391
395
392
396
.. note ::
393
397
0 commit comments