Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 9 additions & 0 deletions src/ImageSharp/Common/Helpers/Numerics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -963,5 +963,14 @@ public static uint RotateRight(uint value, int offset)
public static uint RotateRightSoftwareFallback(uint value, int offset)
=> (value >> offset) | (value << (32 - offset));
#endif

/// <summary>
/// Tells whether input value is outside of the given range.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="min">Mininum value, inclusive.</param>
/// <param name="max">Maximum value, inclusive.</param>
public static bool IsOutOfRange(int value, int min, int max)
=> (uint)(value - min) > (uint)(max - min);
}
}
4 changes: 2 additions & 2 deletions src/ImageSharp/Formats/Jpeg/JpegDecoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1031,13 +1031,13 @@ private void ProcessStartOfFrameMarker(BufferedReadStream stream, int remaining,
int v = hv & 15;

// Validate: 1-4 range
if (h is < 1 or > 4)
if (Numerics.IsOutOfRange(h, 1, 4))
{
JpegThrowHelper.ThrowBadSampling(h);
}

// Validate: 1-4 range
if (v is < 1 or > 4)
if (Numerics.IsOutOfRange(v, 1, 4))
{
JpegThrowHelper.ThrowBadSampling(v);
}
Expand Down
20 changes: 20 additions & 0 deletions tests/ImageSharp.Tests/Common/NumericsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,25 @@ public void DivideCeil_RandomValues(int seed, int count)
Assert.True(expected == actual, $"Expected: {expected}\nActual: {actual}\n{value} / {divisor} = {expected}");
}
}

private static bool IsOutOfRange_ReferenceImplementation(int value, int min, int max) => value < min || value > max;

[Theory]
[InlineData(1, 100)]
public void IsOutOfRange(int seed, int count)
{
var rng = new Random(seed);
for (int i = 0; i < count; i++)
{
int value = rng.Next();
int min = rng.Next();
int max = rng.Next(min, int.MaxValue);

bool expected = IsOutOfRange_ReferenceImplementation(value, min, max);
bool actual = Numerics.IsOutOfRange(value, min, max);

Assert.True(expected == actual, $"IsOutOfRange({value}, {min}, {max})");
}
}
}
}