Skip to content

Commit 1d0c616

Browse files
author
Matt Wozniski
committed
Reverse int to bytes buffer overflow conditionals
Rather than jumping to a label when an overflow is known to have occurred, return early when one is known not to have.
1 parent fb7bb40 commit 1d0c616

File tree

1 file changed

+16
-27
lines changed

1 file changed

+16
-27
lines changed

py/objint.c

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -303,43 +303,32 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co
303303
void mp_obj_int_buffer_overflow_check(mp_obj_t self_in, size_t nbytes, bool is_signed)
304304
{
305305
if (is_signed) {
306-
// edge = 1 << (nbytes * 8 - 1)
306+
// self must be < 2**(bits - 1)
307307
mp_obj_t edge = mp_binary_op(MP_BINARY_OP_INPLACE_LSHIFT,
308308
mp_obj_new_int(1),
309309
mp_obj_new_int(nbytes * 8 - 1));
310310

311-
// if self >= edge, we don't fit
312-
if (mp_binary_op(MP_BINARY_OP_MORE_EQUAL, self_in, edge) == mp_const_true) {
313-
goto raise;
314-
}
315-
316-
// edge = -edge
317-
edge = mp_unary_op(MP_UNARY_OP_NEGATIVE, edge);
318-
319-
// if self < edge, we don't fit
320311
if (mp_binary_op(MP_BINARY_OP_LESS, self_in, edge) == mp_const_true) {
321-
goto raise;
312+
// and >= -2**(bits - 1)
313+
edge = mp_unary_op(MP_UNARY_OP_NEGATIVE, edge);
314+
if (mp_binary_op(MP_BINARY_OP_MORE_EQUAL, self_in, edge) == mp_const_true) {
315+
return;
316+
}
322317
}
323318
} else {
324-
if (mp_obj_int_sign(self_in) < 0) {
325-
// Negative numbers never fit in an unsigned value
326-
goto raise;
327-
}
328-
329-
// edge = 1 << (nbytes * 8)
330-
mp_obj_t edge = mp_binary_op(MP_BINARY_OP_INPLACE_LSHIFT,
331-
mp_obj_new_int(1),
332-
mp_obj_new_int(nbytes * 8));
333-
334-
// if self >= edge, we don't fit
335-
if (mp_binary_op(MP_BINARY_OP_MORE_EQUAL, self_in, edge) == mp_const_true) {
336-
goto raise;
319+
// self must be >= 0
320+
if (mp_obj_int_sign(self_in) >= 0) {
321+
// and < 2**(bits)
322+
mp_obj_t edge = mp_binary_op(MP_BINARY_OP_INPLACE_LSHIFT,
323+
mp_obj_new_int(1),
324+
mp_obj_new_int(nbytes * 8));
325+
326+
if (mp_binary_op(MP_BINARY_OP_LESS, self_in, edge) == mp_const_true) {
327+
return;
328+
}
337329
}
338330
}
339331

340-
return;
341-
342-
raise:
343332
mp_raise_OverflowError_varg(translate("value would overflow a %d byte buffer"), nbytes);
344333
}
345334

0 commit comments

Comments
 (0)