Skip to content

Commit 8f49bdf

Browse files
authored
More efficient preface parsing (#7406)
- Slice before turning the buffer into a Span - Use SequenceEqual instead of a loop
1 parent db7218b commit 8f49bdf

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -357,29 +357,25 @@ private async Task<bool> TryReadPrefaceAsync()
357357
return false;
358358
}
359359

360-
private bool ParsePreface(ReadOnlySequence<byte> readableBuffer, out SequencePosition consumed, out SequencePosition examined)
360+
private bool ParsePreface(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
361361
{
362-
consumed = readableBuffer.Start;
363-
examined = readableBuffer.End;
362+
consumed = buffer.Start;
363+
examined = buffer.End;
364364

365-
if (readableBuffer.Length < ClientPreface.Length)
365+
if (buffer.Length < ClientPreface.Length)
366366
{
367367
return false;
368368
}
369369

370-
var span = readableBuffer.IsSingleSegment
371-
? readableBuffer.First.Span
372-
: readableBuffer.ToSpan();
370+
var preface = buffer.Slice(0, ClientPreface.Length);
371+
var span = preface.ToSpan();
373372

374-
for (var i = 0; i < ClientPreface.Length; i++)
373+
if (!span.SequenceEqual(ClientPreface))
375374
{
376-
if (ClientPreface[i] != span[i])
377-
{
378-
throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorInvalidPreface, Http2ErrorCode.PROTOCOL_ERROR);
379-
}
375+
throw new Http2ConnectionErrorException(CoreStrings.Http2ErrorInvalidPreface, Http2ErrorCode.PROTOCOL_ERROR);
380376
}
381377

382-
consumed = examined = readableBuffer.GetPosition(ClientPreface.Length);
378+
consumed = examined = preface.End;
383379
return true;
384380
}
385381

0 commit comments

Comments
 (0)