More efficient preface parsing (#7406)

- Slice before turning the buffer into a Span
- Use SequenceEqual instead of a loop
This commit is contained in:
David Fowler 2019-02-08 21:13:42 -08:00 committed by GitHub
parent db7218b2fc
commit 8f49bdf195
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 13 deletions

View File

@ -357,29 +357,25 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
return false;
}
private bool ParsePreface(ReadOnlySequence<byte> readableBuffer, out SequencePosition consumed, out SequencePosition examined)
private bool ParsePreface(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
{
consumed = readableBuffer.Start;
examined = readableBuffer.End;
consumed = buffer.Start;
examined = buffer.End;
if (readableBuffer.Length < ClientPreface.Length)
if (buffer.Length < ClientPreface.Length)
{
return false;
}
var span = readableBuffer.IsSingleSegment
? readableBuffer.First.Span
: readableBuffer.ToSpan();
var preface = buffer.Slice(0, ClientPreface.Length);
var span = preface.ToSpan();
for (var i = 0; i < ClientPreface.Length; i++)
if (!span.SequenceEqual(ClientPreface))
{
if (ClientPreface[i] != span[i])
{
throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorInvalidPreface, Http2ErrorCode.PROTOCOL_ERROR);
}
throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorInvalidPreface, Http2ErrorCode.PROTOCOL_ERROR);
}
consumed = examined = readableBuffer.GetPosition(ClientPreface.Length);
consumed = examined = preface.End;
return true;
}