blob: ac0cf2f5f99044757cb9f3634e373164c3d22899 [file] [log] [blame]
Damien Georgeecf5b772014-04-04 11:13:51 +00001#include "misc.h"
2#include "mpconfig.h"
3#include "qstr.h"
4#include "obj.h"
5
6bool mp_small_int_mul_overflow(machine_int_t x, machine_int_t y) {
7 // Check for multiply overflow; see CERT INT32-C
8 if (x > 0) { // x is positive
9 if (y > 0) { // x and y are positive
10 if (x > (MP_SMALL_INT_MAX / y)) {
11 return true;
12 }
13 } else { // x positive, y nonpositive
14 if (y < (MP_SMALL_INT_MIN / x)) {
15 return true;
16 }
17 } // x positive, y nonpositive
18 } else { // x is nonpositive
19 if (y > 0) { // x is nonpositive, y is positive
20 if (x < (MP_SMALL_INT_MIN / y)) {
21 return true;
22 }
23 } else { // x and y are nonpositive
24 if (x != 0 && y < (MP_SMALL_INT_MAX / x)) {
25 return true;
26 }
27 } // End if x and y are nonpositive
28 } // End if x is nonpositive
29 return false;
30}
31
32machine_int_t mp_small_int_modulo(machine_int_t dividend, machine_int_t divisor) {
33 machine_int_t lsign = (dividend >= 0) ? 1 :-1;
34 machine_int_t rsign = (divisor >= 0) ? 1 :-1;
35 dividend %= divisor;
36 if (lsign != rsign) {
37 dividend += divisor;
38 }
39 return dividend;
40}
41
42
43machine_int_t mp_small_int_floor_divide(machine_int_t num, machine_int_t denom) {
44 machine_int_t lsign = num > 0 ? 1 : -1;
45 machine_int_t rsign = denom > 0 ? 1 : -1;
46 if (lsign == -1) {num *= -1;}
47 if (rsign == -1) {denom *= -1;}
48 if (lsign != rsign){
49 return - ( num + denom - 1) / denom;
50 } else {
51 return num / denom;
52 }
53}