protected virtual int BufferIndexOf(byte[] what)
{
// The same limitations about searching for bytes applies. See ReadTo comments for details.
int whatLength = what.Length;
int bufferLength = _incomingBuffer.Length;
// buffer should not be modified during this method (ie. call in lock(_bufferSync) only)
if (whatLength > _incomingBufferValidLength) return -1; // if the desired sequence would not fit into the buffer at all, do not bother searching it
for (int i = _incomingBufferPosition; i < _incomingBufferPosition + _incomingBufferValidLength; i++)
if (_incomingBuffer[i % bufferLength] == what[0])
{ // we have a first byte match
int j;
for (j = 1; j < whatLength; j++)
if (_incomingBuffer[(i + j) % bufferLength] != what[j]) break; // check the remaining bytes
if (j >= whatLength) // If the remaining bytes match,
return (i - _incomingBufferPosition) % bufferLength; // decode the circular position and return it;
} // else try the next byte.
return -1;
}