Skip to content
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
73 changes: 65 additions & 8 deletions src/Apache.Arrow/DecimalUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,44 @@ private static bool TryGetDecimalViaBigInteger(ReadOnlySpan<byte> value, int sca
}
}

// The most chars formatting or parsing a decimal puts on the stack
private const int StackAllocThreshold = 256;

/// <summary>
/// The most decimal digits a value of <paramref name="byteWidth"/> bytes can have: a byte
/// holds fewer than 2.5 digits.
/// </summary>
private static int MaxDigits(int byteWidth) => byteWidth * 5 / 2 + 1;

/// <summary>
/// The zeros to append to the digits of <paramref name="value"/> to give it
/// <paramref name="scale"/> digits after the point. The scale comes from the type, which
/// can come from untrusted data, so this doesn't pad further than any value can use: a
/// nonzero value padded more than the width holds overflows, and padding zero changes
/// nothing.
/// </summary>
private static int ParsePadding(string value, int scale, int neededScale, int byteWidth)
{
int padding = scale - neededScale;
if (padding <= MaxDigits(byteWidth))
{
return padding;
}

foreach (char c in value)
{
if (c > '0' && c <= '9')
{
throw new OverflowException($"Decimal size greater than {byteWidth} bytes: {value} with scale {scale}");
}
if (c != '0' && c != '.' && c != '-' && c != '+')
{
throw new ArgumentException($"Unable to parse {value} as decimal");
}
}
return 0;
}

#if NETCOREAPP
internal unsafe static string GetString(in ArrowBuffer valueBuffer, int index, int precision, int scale, int byteWidth)
{
Expand All @@ -209,8 +247,17 @@ internal unsafe static string GetString(in ArrowBuffer valueBuffer, int index, i
integerValue = -integerValue;
}

// The precision and scale come from the type, which can come from untrusted data, so
// size the buffer by the digits the value can have, and keep large buffers off the stack.
int start = scale + 3;
Span<char> result = stackalloc char[start + precision];
long bufferLength = (long)start + Math.Min(precision, MaxDigits(byteWidth));
if (bufferLength < 0 || bufferLength > int.MaxValue)
{
throw new OverflowException($"Value: {integerValue} cannot be formatted with scale {scale}");
}
Span<char> result = bufferLength <= StackAllocThreshold
? stackalloc char[StackAllocThreshold].Slice(0, (int)bufferLength)
: new char[bufferLength];
if (!integerValue.TryFormat(result.Slice(start), out int charsWritten) || charsWritten > precision)
{
throw new OverflowException($"Value: {integerValue} cannot be formatted");
Expand Down Expand Up @@ -267,7 +314,14 @@ internal unsafe static string GetString(in ArrowBuffer valueBuffer, int index, i
throw new OverflowException($"Value: {integerValue} cannot be formatted");
}

char[] result = new char[precision + 2];
// The precision comes from the type, which can come from untrusted data, so size the
// buffer by the value instead.
long bufferLength = (long)Math.Max(charsWritten, scale) + 3;
if (bufferLength > int.MaxValue)
{
throw new OverflowException($"Value: {integerValue} cannot be formatted with scale {scale}");
}
char[] result = new char[bufferLength];
int pos = 0;
if (negative)
{
Expand Down Expand Up @@ -483,7 +537,11 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi

#if NETCOREAPP
ReadOnlySpan<char> src = value.AsSpan();
Span<char> buffer = stackalloc char[precision + start + 1];
int padding = ParsePadding(value, scale, neededScale, byteWidth);
int bufferLength = value.Length + padding;
Span<char> buffer = bufferLength <= StackAllocThreshold
? stackalloc char[StackAllocThreshold]
: new char[bufferLength];

int end;
if (pos == -1)
Expand All @@ -498,10 +556,9 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi
end = src.Length - 1;
}

while (neededScale < scale)
for (int i = 0; i < padding; i++)
{
buffer[end++] = '0';
neededScale++;
}

if (!BigInteger.TryParse(buffer.Slice(0, end), out BigInteger bigInt))
Expand All @@ -514,7 +571,8 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi
throw new OverflowException("Could not extract bytes from integer value " + bigInt);
}
#else
char[] buffer = new char[precision + start + 1];
int padding = ParsePadding(value, scale, neededScale, byteWidth);
char[] buffer = new char[value.Length + padding];

int end;
if (pos == -1)
Expand All @@ -529,10 +587,9 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi
end = value.Length - 1;
}

while (neededScale < scale)
for (int i = 0; i < padding; i++)
{
buffer[end++] = '0';
neededScale++;
}

if (!BigInteger.TryParse(new string(buffer, 0, end), out BigInteger bigInt))
Expand Down
124 changes: 124 additions & 0 deletions test/Apache.Arrow.Tests/DecimalUtilityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

using System;
using System.Data.SqlTypes;
using System.Numerics;
using Apache.Arrow.Types;
using Xunit;

Expand Down Expand Up @@ -188,6 +189,129 @@ private void TestFromString(string s, int precision, int scale, int byteWidth, s
Assert.Equal(result, DecimalUtility.GetString(new ArrowBuffer(bytes), 0, precision, scale, byteWidth));
}

// The precision and scale come from the type, which may come from untrusted data, so
// they must not decide how much stack is used.
[Theory]
[InlineData(100_000_000)]
[InlineData(int.MaxValue)]
public void ToStringWithAHugePrecision(int precision)
{
foreach (int byteWidth in new[] { 4, 8, 16, 32 })
{
var bytes = new byte[byteWidth];
DecimalUtility.GetBytes(-100.12m, 9, 2, byteWidth, bytes);
Assert.Equal("-100.12", DecimalUtility.GetString(new ArrowBuffer(bytes), 0, precision, 2, byteWidth));
}
}

[Theory]
[InlineData(4)]
[InlineData(8)]
[InlineData(16)]
[InlineData(32)]
public void ToStringOfTheLargestValuesWithAHugePrecision(int byteWidth)
{
var largest = new byte[byteWidth];
largest.AsSpan().Fill(0xFF);
largest[byteWidth - 1] = 0x7F;
var smallest = new byte[byteWidth];
smallest[byteWidth - 1] = 0x80;

foreach (byte[] bytes in new[] { largest, smallest })
{
string digits = new BigInteger(bytes).ToString();
string expected = digits.Substring(0, digits.Length - 1) + "." + digits.Substring(digits.Length - 1);
Assert.Equal(expected, DecimalUtility.GetString(new ArrowBuffer(bytes), 0, int.MaxValue, 1, byteWidth));
}
}

[Fact]
public void ToStringWithAHugeScale()
{
const int scale = 1_000_000;
foreach (int byteWidth in new[] { 4, 8, 16, 32 })
{
var bytes = new byte[byteWidth];
bytes[0] = 1;
string expected = "0." + new string('0', scale - 1) + "1";
Assert.Equal(expected, DecimalUtility.GetString(new ArrowBuffer(bytes), 0, 10, scale, byteWidth));
}
}

[Theory]
[InlineData(100_000_000)]
[InlineData(int.MaxValue - 10)]
public void FromStringWithAHugePrecision(int precision)
{
foreach (int byteWidth in new[] { 4, 8, 16, 32 })
{
var bytes = new byte[byteWidth];
DecimalUtility.GetBytes("-100.12", precision, 3, byteWidth, bytes);
Assert.Equal("-100.120", DecimalUtility.GetString(new ArrowBuffer(bytes), 0, 10, 3, byteWidth));
}
}

// Parsing pads the digits with zeros up to the scale. Buffers of up to 256 chars are
// on the stack and larger ones on the heap, so cover both sides of that boundary.
[Theory]
[InlineData(254)]
[InlineData(255)]
[InlineData(256)]
[InlineData(257)]
[InlineData(1_000_000)]
public void FromStringPaddedToALargeScale(int scale)
{
string expected = "0." + new string('0', scale);
foreach (int byteWidth in new[] { 4, 8, 16, 32 })
{
TestFromString("0", int.MaxValue, scale, byteWidth, expected);
}
}

[Theory]
[InlineData(254)]
[InlineData(255)]
[InlineData(256)]
[InlineData(257)]
[InlineData(1_000_000)]
public void FromStringWithALongFraction(int scale)
{
string value = "0." + new string('0', scale - 1) + "1";
foreach (int byteWidth in new[] { 4, 8, 16, 32 })
{
TestFromString(value, int.MaxValue, scale, byteWidth, value);
}
}

[Theory]
[InlineData(4)]
[InlineData(8)]
[InlineData(16)]
[InlineData(32)]
public void FromStringPaddedBeyondTheWidth_Throws(int byteWidth)
{
byte[] bytes = new byte[byteWidth];
Assert.Throws<OverflowException>(() => DecimalUtility.GetBytes("1", int.MaxValue, 300, byteWidth, bytes));
}

// Padding to a huge scale must not allocate for it: zero stays zero, a nonzero value
// overflows, and an invalid string is still rejected as one.
[Theory]
[InlineData(4)]
[InlineData(8)]
[InlineData(16)]
[InlineData(32)]
public void FromStringWithAHugeScale(int byteWidth)
{
byte[] bytes = new byte[byteWidth];
bytes.AsSpan().Fill(0xFF);
DecimalUtility.GetBytes("-0.0", int.MaxValue, int.MaxValue, byteWidth, bytes);
Assert.All(bytes, b => Assert.Equal(0, b));

Assert.Throws<OverflowException>(() => DecimalUtility.GetBytes("0.01", int.MaxValue, int.MaxValue, byteWidth, bytes));
Assert.Throws<ArgumentException>(() => DecimalUtility.GetBytes("0x", int.MaxValue, int.MaxValue, byteWidth, bytes));
}

[Theory]
[InlineData("", 10, 2, 16, typeof(ArgumentException))]
[InlineData("", 10, 2, 32, typeof(ArgumentException))]
Expand Down
Loading