From 8f49bdf195efbcf3172eae8b3a8acbf862777b83 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Fri, 8 Feb 2019 21:13:42 -0800 Subject: [PATCH] More efficient preface parsing (#7406) - Slice before turning the buffer into a Span - Use SequenceEqual instead of a loop --- .../src/Internal/Http2/Http2Connection.cs | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs index 3179b2f82a..c2b4ffc494 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs @@ -357,29 +357,25 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2 return false; } - private bool ParsePreface(ReadOnlySequence readableBuffer, out SequencePosition consumed, out SequencePosition examined) + private bool ParsePreface(in ReadOnlySequence 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; }