Skip to content

Commit fb48cac

Browse files
authored
Fix Add (#43)
* Fix Add * Fix Int256
1 parent 2e9a2d8 commit fb48cac

File tree

3 files changed

+32
-6
lines changed

3 files changed

+32
-6
lines changed

src/Nethermind.Int256.Test/UInt256Tests.cs

+25
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ public virtual void Add((BigInteger A, BigInteger B) test)
3434
res.Convert(out BigInteger resUInt256);
3535

3636
resUInt256.Should().Be(resBigInt);
37+
38+
// Test reusing input as output
39+
a.Add(b, out a);
40+
a.Convert(out resUInt256);
41+
resUInt256.Should().Be(resBigInt);
42+
43+
a = convert(test.A);
44+
45+
// Test reusing input as output
46+
a.Add(b, out b);
47+
b.Convert(out resUInt256);
48+
resUInt256.Should().Be(resBigInt);
3749
}
3850

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

188200
resUInt256.Should().Be(resBigInt);
201+
202+
// Test reusing input as output
203+
uint256a.Multiply(uint256b, out uint256a);
204+
uint256a.Convert(out resUInt256);
205+
206+
resUInt256.Should().Be(resBigInt);
207+
208+
uint256a = convert(test.A);
209+
210+
uint256a.Multiply(uint256b, out uint256b);
211+
uint256b.Convert(out resUInt256);
212+
213+
resUInt256.Should().Be(resBigInt);
189214
}
190215

191216
[TestCaseSource(typeof(TernaryOps), nameof(TernaryOps.TestCases))]

src/Nethermind.Int256/Int256.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -168,18 +168,18 @@ public static void SubtractMod(in Int256 x, in Int256 y, in Int256 m, out Int256
168168
public static void Multiply(in Int256 a, in Int256 b, out Int256 res)
169169
{
170170
Int256 av = a, bv = b;
171-
if (a.Sign < 0)
171+
int aSign = a.Sign;
172+
int bSign = b.Sign;
173+
if (aSign < 0)
172174
{
173175
a.Neg(out av);
174176
}
175-
if (b.Sign < 0)
177+
if (bSign < 0)
176178
{
177179
b.Neg(out bv);
178180
}
179181
UInt256.Multiply(av._value, bv._value, out UInt256 ures);
180182
res = new Int256(ures);
181-
int aSign = a.Sign;
182-
int bSign = b.Sign;
183183
if ((aSign < 0 && bSign < 0) || (aSign >= 0 && bSign >= 0))
184184
{
185185
return;

src/Nethermind.Int256/UInt256.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,12 @@ public static bool AddImpl(in UInt256 a, in UInt256 b, out UInt256 res)
407407
if ((a.u1 | a.u2 | a.u3 | b.u1 | b.u2 | b.u3) == 0)
408408
{
409409
// Fast add for numbers less than 2^64 (18,446,744,073,709,551,615)
410-
ulong u0 = a.u0 + b.u0;
410+
ulong a0 = a.u0; // copy to local as we need to check after result clear
411+
ulong u0 = a0 + b.u0;
411412
// Assignment to res after in case is used as input for a or b (by ref aliasing)
412413
res = default;
413414
Unsafe.AsRef(in res.u0) = u0;
414-
if (u0 < a.u0)
415+
if (u0 < a0)
415416
{
416417
Unsafe.AsRef(in res.u1) = 1;
417418
}

0 commit comments

Comments
 (0)