using System;
namespace NHSE.Core;
///
/// Array reusable logic
///
public static class ArrayUtil
{
//public static int ReplaceOccurrences(this Span array, ReadOnlySpan pattern, ReadOnlySpan swap)
//{
// int count = 0;
// int ofs = 0;
// while (true)
// {
// var index = array[ofs..].IndexOf(pattern);
// if (index == -1)
// return count;
// ofs += index;
//
// swap.CopyTo(array[ofs..]);
// ofs += swap.Length; // skip past swapped data
// ++count;
// }
//}
public static int ReplaceOccurrences(this Span array, ReadOnlySpan pattern, ReadOnlySpan swap)
{
int count = 0;
while (true)
{
int ofs = IndexOfBytes(array, pattern);
if (ofs == -1)
return count;
swap.CopyTo(array[ofs..]);
++count;
}
}
///
/// Finds a provided within the supplied .
///
/// Array to look in
/// Pattern to look for
/// Starting offset to look from
/// Amount of entries to look through
/// Index the pattern occurs at; if not found, returns -1.
public static int IndexOfBytes(ReadOnlySpan array, ReadOnlySpan pattern, int startIndex = 0, int length = -1)
{
int len = pattern.Length;
int endIndex = length > 0
? startIndex + length
: array.Length - len - startIndex;
endIndex = Math.Min(array.Length - pattern.Length, endIndex);
int i = startIndex;
int j = 0;
while (true)
{
if (pattern[j] != array[i + j])
{
if (++i == endIndex)
return -1;
j = 0;
}
else if (++j == len)
{
return i;
}
}
}
}