Skip to content

fixed IndexOfBytes bug #125

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions RtspClientSharp.UnitTests/Utils/ArrayUtilsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
7 changes: 7 additions & 0 deletions RtspClientSharp/Utils/ArrayUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down