[3.13] gh-71810: Fix corner case (length==0) for int.to_bytes() (GH-138739) (#138783)

gh-71810: Fix corner case (length==0) for int.to_bytes() (GH-138739)

```pycon
>>> (0).to_bytes(0, 'big', signed=True)
b''
>>> (-1).to_bytes(0, 'big', signed=True)  # was b''
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    (-1).to_bytes(0, 'big', signed=True)
    ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
OverflowError: int too big to convert
```
(cherry picked from commit 011179a79a)

Co-authored-by: Sergey B Kirpichev <skirpichev@gmail.com>
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2025-09-11 12:53:27 +02:00 committed by GitHub
parent 72b28cad91
commit 7195d7f3d4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 10 additions and 3 deletions

View file

@ -1322,17 +1322,22 @@ class LongTest(unittest.TestCase):
check(tests4, 'little', signed=False)
self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
self.assertRaises(OverflowError, (128).to_bytes, 1, 'big', signed=True)
self.assertRaises(OverflowError, (128).to_bytes, 1, 'little', signed=True)
self.assertRaises(OverflowError, (-129).to_bytes, 1, 'big', signed=True)
self.assertRaises(OverflowError, (-129).to_bytes, 1, 'little', signed=True)
self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False)
self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
self.assertEqual((0).to_bytes(0, 'big'), b'')
self.assertEqual((0).to_bytes(0, 'big', signed=True), b'')
self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
self.assertEqual((-1).to_bytes(5, 'big', signed=True),
b'\xff\xff\xff\xff\xff')
self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
self.assertRaises(OverflowError, (-1).to_bytes, 0, 'big', signed=True)
self.assertRaises(OverflowError, (-1).to_bytes, 0, 'little', signed=True)
# gh-98783
class SubStr(str):