| 51 | */ |
| 52 | template<class R, class T> |
| 53 | R calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr) |
| 54 | { |
| 55 | auto wrap = [](T z) { |
| 56 | return R{z}; |
| 57 | }; |
| 58 | constexpr MathLib::bigint maxBitsShift = sizeof(MathLib::bigint) * 8; |
| 59 | // For portability we cannot shift signed integers by 63 bits |
| 60 | constexpr MathLib::bigint maxBitsSignedShift = maxBitsShift - 1; |
| 61 | switch (MathLib::encodeMultiChar(s)) { |
| 62 | case '+': |
| 63 | return wrap(x + y); |
| 64 | case '-': |
| 65 | return wrap(x - y); |
| 66 | case '*': |
| 67 | return wrap(x * y); |
| 68 | case '/': |
| 69 | if (isZero(y) || (std::is_signed<T>{} && y < 0)) { |
| 70 | if (error) |
| 71 | *error = true; |
| 72 | return R{}; |
| 73 | } |
| 74 | return wrap(x / y); |
| 75 | case '%': |
| 76 | if (isZero(MathLib::bigint(y)) || (std::is_signed<T>{} && MathLib::bigint(y) < 0)) { |
| 77 | if (error) |
| 78 | *error = true; |
| 79 | return R{}; |
| 80 | } |
| 81 | return wrap(MathLib::bigint(x) % MathLib::bigint(y)); |
| 82 | case '&': |
| 83 | return wrap(MathLib::bigint(x) & MathLib::bigint(y)); |
| 84 | case '|': |
| 85 | return wrap(MathLib::bigint(x) | MathLib::bigint(y)); |
| 86 | case '^': |
| 87 | return wrap(MathLib::bigint(x) ^ MathLib::bigint(y)); |
| 88 | case '>': |
| 89 | return wrap(x > y); |
| 90 | case '<': |
| 91 | return wrap(x < y); |
| 92 | case '<<': |
| 93 | if (y >= maxBitsSignedShift || y < 0 || x < 0) { |
| 94 | if (error) |
| 95 | *error = true; |
| 96 | return R{}; |
| 97 | } |
| 98 | return wrap(MathLib::bigint(x) << MathLib::bigint(y)); |
| 99 | case '>>': |
| 100 | if (y >= maxBitsSignedShift || y < 0 || x < 0) { |
| 101 | if (error) |
| 102 | *error = true; |
| 103 | return R{}; |
| 104 | } |
| 105 | return wrap(MathLib::bigint(x) >> MathLib::bigint(y)); |
| 106 | case '&&': |
| 107 | return wrap(!isZero(x) && !isZero(y)); |
| 108 | case '||': |
| 109 | return wrap(!isZero(x) || !isZero(y)); |
| 110 | case '==': |