Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-37730: [C#] throw OverflowException in DecimalUtility if fractionalPart is too large #37731

Merged
merged 7 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions csharp/src/Apache.Arrow/DecimalUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,21 @@ internal static decimal GetDecimal(in ArrowBuffer valueBuffer, int index, int sc
{
BigInteger scaleBy = BigInteger.Pow(10, scale);
BigInteger integerPart = BigInteger.DivRem(integerValue, scaleBy, out BigInteger fractionalPart);
if (integerPart > _maxDecimal || integerPart < _minDecimal) // decimal overflow, not much we can do here - C# needs a BigDecimal

// decimal overflow, not much we can do here - C# needs a BigDecimal
if (integerPart > _maxDecimal)
{
throw new OverflowException($"Value: {integerPart} of {integerValue} is too big be represented as a decimal");
}
else if (integerPart < _minDecimal)
{
throw new OverflowException($"Value: {integerPart} too big or too small to be represented as a decimal");
throw new OverflowException($"Value: {integerPart} of {integerValue} is too small be represented as a decimal");
}
else if (fractionalPart > _maxDecimal || fractionalPart < _minDecimal)
{
throw new OverflowException($"Value: {fractionalPart} of {integerValue} is too precise be represented as a decimal");
}

return (decimal)integerPart + DivideByScale(fractionalPart, scale);
}
else
Expand Down
19 changes: 19 additions & 0 deletions csharp/test/Apache.Arrow.Tests/DecimalUtilityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,25 @@ public void HasExpectedResultOrThrows(decimal d, int precision , int scale, bool
Assert.Equal(d, result.GetValue(0));
}
}

[Theory]
[InlineData(4.56, 38, 9, false)]
[InlineData(7.89, 76, 38, true)]
public void Decimal256HasExpectedResultOrThrows(decimal d, int precision, int scale, bool shouldThrow)
{
var builder = new Decimal256Array.Builder(new Decimal256Type(precision, scale));
builder.Append(d);
Decimal256Array result = builder.Build(new TestMemoryAllocator()); ;

if (shouldThrow)
{
Assert.Throws<OverflowException>(() => result.GetValue(0));
}
else
{
Assert.Equal(d, result.GetValue(0));
}
}
}
}
}
Loading