提交 34d64980 authored 作者: Evgenij Ryazanov's avatar Evgenij Ryazanov

Optimize ValueLong.add() and ValueLong.subtract()

上级 0407175b
...@@ -61,19 +61,17 @@ public class ValueLong extends Value { ...@@ -61,19 +61,17 @@ public class ValueLong extends Value {
@Override @Override
public Value add(Value v) { public Value add(Value v) {
ValueLong other = (ValueLong) v; long x = value;
long result = value + other.value; long y = ((ValueLong) v).value;
int sv = Long.signum(value); long result = x + y;
int so = Long.signum(other.value); /*
int sr = Long.signum(result); * If signs of both summands are different from the sign of the sum there is an
// if the operands have different signs overflow can not occur * overflow.
// if the operands have the same sign, */
// and the result has a different sign, then it is an overflow if (((x ^ result) & (y ^ result)) < 0) {
// it can not be an overflow when one of the operands is 0 throw getOverflow();
if (sv != so || sr == so || sv == 0 || so == 0) {
return ValueLong.get(result);
} }
throw getOverflow(); return ValueLong.get(result);
} }
@Override @Override
...@@ -96,17 +94,17 @@ public class ValueLong extends Value { ...@@ -96,17 +94,17 @@ public class ValueLong extends Value {
@Override @Override
public Value subtract(Value v) { public Value subtract(Value v) {
ValueLong other = (ValueLong) v; long x = value;
int sv = Long.signum(value); long y = ((ValueLong) v).value;
int so = Long.signum(other.value); long result = x - y;
// if the operands have the same sign, then overflow can not occur /*
// if the second operand is 0, then overflow can not occur * If minuend and subtrahend have different signs and minuend and difference
if (sv == so || so == 0) { * have different signs there is an overflow.
return ValueLong.get(value - other.value); */
if (((x ^ y) & (x ^ result)) < 0) {
throw getOverflow();
} }
// now, if the other value is Long.MIN_VALUE, it must be an overflow return ValueLong.get(result);
// x - Long.MIN_VALUE overflows for x>=0
return add(other.negate());
} }
@Override @Override
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论