Skip to content

Commit 8ff9ff5

Browse files
author
Jacob Beck
committed
Error handling is hard
1 parent 8ec7ab0 commit 8ff9ff5

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/future/types/newint.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,8 @@ def to_bytes(self, length, byteorder='big', signed=False):
306306
if signed and self < 0:
307307
bits = length * 8
308308
num = (2**bits) + self
309+
if num <= 0:
310+
raise OverflowError("int too smal to convert")
309311
else:
310312
if self < 0:
311313
raise OverflowError("can't convert negative int to unsigned")
@@ -314,6 +316,12 @@ def to_bytes(self, length, byteorder='big', signed=False):
314316
raise ValueError("byteorder must be either 'little' or 'big'")
315317
h = b'%x' % num
316318
s = newbytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex'))
319+
if signed:
320+
high_set = s[0] & 0x80
321+
if self > 0 and high_set:
322+
raise OverflowError("int too big to convert")
323+
if self < 0 and not high_set:
324+
raise OverflowError("int too small to convert")
317325
if len(s) > length:
318326
raise OverflowError("int too big to convert")
319327
return s if byteorder == 'big' else s[::-1]

0 commit comments

Comments
 (0)