using System;
namespace Keyki.XNA.Video
{
///
/// Some internal utilities for handling arrays.
///
///
internal static class ByteArrayUtils
{
///
/// Check if the array contains needle at specified position.
///
///
/// Source array to check for needle.
/// Needle we are searching for.
/// Start index in source array.
///
/// Returns true if the source array contains the needle at
/// the specified index. Otherwise it returns false.
///
public static bool Compare(byte[] array, byte[] needle, int startIndex)
{
int needleLen = needle.Length;
// compare
for (int i = 0, p = startIndex; i < needleLen; i++, p++)
{
if (array[p] != needle[i])
{
return false;
}
}
return true;
}
///
/// Find subarray in the source array.
///
///
/// Source array to search for needle.
/// Needle we are searching for.
/// Start index in source array.
/// Number of bytes in source array, where the needle is searched for.
///
/// Returns starting position of the needle if it was found or -1 otherwise.
///
public static int Find(byte[] array, byte[] needle, int startIndex, int sourceLength)
{
int needleLen = needle.Length;
int index;
while (sourceLength >= needleLen)
{
// find needle's starting element
index = Array.IndexOf(array, needle[0], startIndex, sourceLength - needleLen + 1);
// if we did not find even the first element of the needls, then the search is failed
if (index == -1)
return -1;
int i, p;
// check for needle
for (i = 0, p = index; i < needleLen; i++, p++)
{
if (array[p] != needle[i])
{
break;
}
}
if (i == needleLen)
{
// needle was found
return index;
}
// continue to search for needle
sourceLength -= (index - startIndex + 1);
startIndex = index + 1;
}
return -1;
}
}
}