From 0fef5373df01b79a01e17ab15ecf707fbaf57b8b Mon Sep 17 00:00:00 2001 From: buzzweetman Date: Sat, 5 Feb 2022 13:04:35 -0500 Subject: [PATCH] fixed IndexOfBytes bug --- RtspClientSharp.UnitTests/Utils/ArrayUtilsTests.cs | 11 +++++++++++ RtspClientSharp/Utils/ArrayUtils.cs | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/RtspClientSharp.UnitTests/Utils/ArrayUtilsTests.cs b/RtspClientSharp.UnitTests/Utils/ArrayUtilsTests.cs index 9ad5924..92875ff 100644 --- a/RtspClientSharp.UnitTests/Utils/ArrayUtilsTests.cs +++ b/RtspClientSharp.UnitTests/Utils/ArrayUtilsTests.cs @@ -95,6 +95,17 @@ public void IndexOfBytes_PatternExists_ReturnsActualIndex() Assert.AreEqual(4, index); } + [TestMethod] + public void IndexOfBytes_PatternExists_BackTrack_ReturnsActualIndex() + { + var pattern = new byte[] { 0, 0, 1 }; + var bytes = new byte[] { 0, 5, 0, 0, 0, 1, 3, 4 }; + + int index = ArrayUtils.IndexOfBytes(bytes, pattern, 1, bytes.Length - 1); + + Assert.AreEqual(3, index); + } + [TestMethod] public void IndexOfBytes_PatternNotExists_ReturnsMinusOne() { diff --git a/RtspClientSharp/Utils/ArrayUtils.cs b/RtspClientSharp/Utils/ArrayUtils.cs index 7f052e0..589a78f 100644 --- a/RtspClientSharp/Utils/ArrayUtils.cs +++ b/RtspClientSharp/Utils/ArrayUtils.cs @@ -57,7 +57,14 @@ public static int IndexOfBytes(byte[] array, byte[] pattern, int startIndex, int for (; startIndex < endIndex; startIndex++) { if (array[startIndex] != pattern[foundIndex]) + { + // When the pattern is partially found but then mismatches, the start search index + // must be moved back to index just after where the original successful matching started. + // Otherwise, matches that begin within an attempted match would be missed. + // e.g., array: 123400001567, pattern: 0001, would errnoneously return -1 + startIndex -= foundIndex; // for loop will then add 1 foundIndex = 0; + } else if (++foundIndex == patternLength) return startIndex - foundIndex + 1; }