Skip to content
Merged
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
9 changes: 7 additions & 2 deletions Lib/test/test_long.py
Original file line number Diff line number Diff line change
Expand Up @@ -1374,17 +1374,22 @@ def equivalent_python(n, length, byteorder, signed=False):
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):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Raise :exc:`OverflowError` for ``(-1).to_bytes()`` for signed conversions
when bytes count is zero. Patch by Sergey B Kirpichev.
2 changes: 1 addition & 1 deletion Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1209,7 +1209,7 @@ _PyLong_AsByteArray(PyLongObject* v,
*p = (unsigned char)(accum & 0xff);
p += pincr;
}
else if (j == n && n > 0 && is_signed) {
else if (j == n && is_signed) {
Copy link
Member

Choose a reason for hiding this comment

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

This change introduced an undefined behavior: unsigned char msb = *(p - pincr); read is out of the bounds if n == 0. I wrote #138873 to fix it.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh, sorry. Thanks!

/* The main loop filled the byte array exactly, so the code
just above didn't get to ensure there's a sign bit, and the
loop below wouldn't add one either. Make sure a sign bit
Expand Down
Loading