Skip to content

Commit f3b8e5c

Browse files
author
Dmitry Pentin
committed
gfoidl IsOutOfRange
1 parent 1f9ef3e commit f3b8e5c

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

src/ImageSharp/Common/Helpers/Numerics.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -963,5 +963,14 @@ public static uint RotateRight(uint value, int offset)
963963
public static uint RotateRightSoftwareFallback(uint value, int offset)
964964
=> (value >> offset) | (value << (32 - offset));
965965
#endif
966+
967+
/// <summary>
968+
/// Tells whether input value is outside of the given range.
969+
/// </summary>
970+
/// <param name="value">Value.</param>
971+
/// <param name="min">Mininum value, inclusive.</param>
972+
/// <param name="max">Maximum value, inclusive.</param>
973+
public static bool IsOutOfRange(int value, int min, int max)
974+
=> (uint)(value - min) > (uint)(max - min);
966975
}
967976
}

src/ImageSharp/Formats/Jpeg/JpegDecoderCore.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,13 +1031,13 @@ private void ProcessStartOfFrameMarker(BufferedReadStream stream, int remaining,
10311031
int v = hv & 15;
10321032

10331033
// Validate: 1-4 range
1034-
if (h is < 1 or > 4)
1034+
if (Numerics.IsOutOfRange(h, 1, 4))
10351035
{
10361036
JpegThrowHelper.ThrowBadSampling(h);
10371037
}
10381038

10391039
// Validate: 1-4 range
1040-
if (v is < 1 or > 4)
1040+
if (Numerics.IsOutOfRange(v, 1, 4))
10411041
{
10421042
JpegThrowHelper.ThrowBadSampling(v);
10431043
}

tests/ImageSharp.Tests/Common/NumericsTests.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,5 +97,25 @@ public void DivideCeil_RandomValues(int seed, int count)
9797
Assert.True(expected == actual, $"Expected: {expected}\nActual: {actual}\n{value} / {divisor} = {expected}");
9898
}
9999
}
100+
101+
private static bool IsOutOfRange_ReferenceImplementation(int value, int min, int max) => value < min || value > max;
102+
103+
[Theory]
104+
[InlineData(1, 100)]
105+
public void IsOutOfRange(int seed, int count)
106+
{
107+
var rng = new Random(seed);
108+
for (int i = 0; i < count; i++)
109+
{
110+
int value = rng.Next();
111+
int min = rng.Next();
112+
int max = rng.Next(min, int.MaxValue);
113+
114+
bool expected = IsOutOfRange_ReferenceImplementation(value, min, max);
115+
bool actual = Numerics.IsOutOfRange(value, min, max);
116+
117+
Assert.True(expected == actual, $"IsOutOfRange({value}, {min}, {max})");
118+
}
119+
}
100120
}
101121
}

0 commit comments

Comments
 (0)