Skip to content

Commit

Permalink
Fix Add (#43)
Browse files Browse the repository at this point in the history
* Fix Add

* Fix Int256
  • Loading branch information
benaadams authored Jan 7, 2025
1 parent 2e9a2d8 commit fb48cac
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
25 changes: 25 additions & 0 deletions src/Nethermind.Int256.Test/UInt256Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ public virtual void Add((BigInteger A, BigInteger B) test)
res.Convert(out BigInteger resUInt256);

resUInt256.Should().Be(resBigInt);

// Test reusing input as output
a.Add(b, out a);
a.Convert(out resUInt256);
resUInt256.Should().Be(resBigInt);

a = convert(test.A);

// Test reusing input as output
a.Add(b, out b);
b.Convert(out resUInt256);
resUInt256.Should().Be(resBigInt);
}

[TestCaseSource(typeof(BinaryOps), nameof(BinaryOps.TestCases))]
Expand Down Expand Up @@ -186,6 +198,19 @@ public virtual void Multiply((BigInteger A, BigInteger B) test)
res.Convert(out BigInteger resUInt256);

resUInt256.Should().Be(resBigInt);

// Test reusing input as output
uint256a.Multiply(uint256b, out uint256a);
uint256a.Convert(out resUInt256);

resUInt256.Should().Be(resBigInt);

uint256a = convert(test.A);

uint256a.Multiply(uint256b, out uint256b);
uint256b.Convert(out resUInt256);

resUInt256.Should().Be(resBigInt);
}

[TestCaseSource(typeof(TernaryOps), nameof(TernaryOps.TestCases))]
Expand Down
8 changes: 4 additions & 4 deletions src/Nethermind.Int256/Int256.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,18 +168,18 @@ public static void SubtractMod(in Int256 x, in Int256 y, in Int256 m, out Int256
public static void Multiply(in Int256 a, in Int256 b, out Int256 res)
{
Int256 av = a, bv = b;
if (a.Sign < 0)
int aSign = a.Sign;
int bSign = b.Sign;
if (aSign < 0)
{
a.Neg(out av);
}
if (b.Sign < 0)
if (bSign < 0)
{
b.Neg(out bv);
}
UInt256.Multiply(av._value, bv._value, out UInt256 ures);
res = new Int256(ures);
int aSign = a.Sign;
int bSign = b.Sign;
if ((aSign < 0 && bSign < 0) || (aSign >= 0 && bSign >= 0))
{
return;
Expand Down
5 changes: 3 additions & 2 deletions src/Nethermind.Int256/UInt256.cs
Original file line number Diff line number Diff line change
Expand Up @@ -407,11 +407,12 @@ public static bool AddImpl(in UInt256 a, in UInt256 b, out UInt256 res)
if ((a.u1 | a.u2 | a.u3 | b.u1 | b.u2 | b.u3) == 0)
{
// Fast add for numbers less than 2^64 (18,446,744,073,709,551,615)
ulong u0 = a.u0 + b.u0;
ulong a0 = a.u0; // copy to local as we need to check after result clear
ulong u0 = a0 + b.u0;
// Assignment to res after in case is used as input for a or b (by ref aliasing)
res = default;
Unsafe.AsRef(in res.u0) = u0;
if (u0 < a.u0)
if (u0 < a0)
{
Unsafe.AsRef(in res.u1) = 1;
}
Expand Down

0 comments on commit fb48cac

Please sign in to comment.