Browse Source

Merge pull request #4178 from georgkoester/issue/int64toString_fails

Fix Int64.toString issue for boundary value.
Nicolas Cannasse 10 years ago
parent
commit
4b44ff3a66
2 changed files with 18 additions and 3 deletions
  1. 8 3
      std/haxe/Int64.hx
  2. 10 0
      tests/unit/src/unit/TestInt64.hx

+ 8 - 3
std/haxe/Int64.hx

@@ -133,13 +133,18 @@ abstract Int64(__Int64) from __Int64 to __Int64
 		var neg = false;
 		if( i.isNeg() ) {
 			neg = true;
-			i = -i;
+			// i = -i; cannot negate here as --9223372036854775808 = -9223372036854775808
 		}
 		var ten : Int64 = 10;
 		while( i != 0 ) {
 			var r = i.divMod( ten );
-			str = r.modulus.low + str;
-			i = r.quotient;
+			if (r.modulus.isNeg()) {
+				str = Int64.neg(r.modulus).low + str;
+				i = Int64.neg(r.quotient);
+			} else {
+				str = r.modulus.low + str;
+				i = r.quotient;
+			}
 		}
 		if( neg ) str = "-" + str;
 		return str;

+ 10 - 0
tests/unit/src/unit/TestInt64.hx

@@ -89,6 +89,16 @@ class TestInt64 extends Test {
 
 		a = Int64.make(1,1);
 		eq( a.toStr(), "4294967297" );
+
+		// set a to 2^63 (overflows to the smallest negative number)
+		a = Int64.ofInt(2);
+		for (i in 0...62) {
+			a = Int64.mul(a, 2);
+		}
+
+		eq( Int64.add(a, -1).toStr(), "9223372036854775807" ); // largest positive
+		eq( Int64.add(a, 1).toStr(), "-9223372036854775807" ); // smallest negative - 1
+		eq( a.toStr(), "-9223372036854775808" ); // smallest negative
 	}
 
 	public function testComparison() {