From 88490d98ffa44bbd1adc604a9413b84e4555ba5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Foidl?= Date: Thu, 10 Apr 2025 17:55:07 +0200 Subject: [PATCH] Replaced comparison with -1 w/ equivalent comparison to 0 This allows the cpu to fuse the compare and jump. --- .../Endpoints/src/FormMapping/FormDataReader.cs | 6 +++--- .../src/Circuits/ServerComponentDeserializer.cs | 4 ++-- .../DataProtection/src/TypeForwardingActivator.cs | 4 ++-- src/DefaultBuilder/src/WebApplicationBuilder.cs | 2 +- .../Embedded/src/EmbeddedFileProvider.cs | 2 +- .../Embedded/src/Manifest/EmbeddedFilesManifest.cs | 6 +++--- .../Headers/src/ContentDispositionHeaderValue.cs | 2 +- src/Http/Headers/src/HeaderUtilities.cs | 2 +- src/Http/Headers/src/MediaTypeHeaderValue.cs | 8 ++++---- .../src/Internal/HeaderSegmentCollection.cs | 8 ++++---- src/Http/Http.Abstractions/src/PathString.cs | 2 +- .../src/Constraints/FileNameRouteConstraint.cs | 2 +- src/Http/Routing/src/InlineRouteParameterParser.cs | 2 +- .../src/Matching/NegotiationMatcherPolicy.cs | 4 ++-- src/Http/Routing/src/PathTokenizer.cs | 8 ++++---- .../Routing/src/Patterns/RoutePatternMatcher.cs | 2 +- .../Routing/src/Patterns/RoutePatternParser.cs | 2 +- src/Http/Routing/src/RouteCollection.cs | 2 +- src/Http/WebUtilities/src/FormPipeReader.cs | 4 ++-- .../WebUtilities/src/HttpRequestStreamReader.cs | 2 +- src/Http/WebUtilities/src/QueryHelpers.cs | 4 ++-- .../src/DefaultPersonalDataProtector.cs | 2 +- .../src/ForwardedHeadersMiddleware.cs | 2 +- src/Middleware/Rewrite/src/RedirectRule.cs | 2 +- .../Mvc.Core/src/Formatters/AcceptHeaderParser.cs | 2 +- .../ModelBinding/JQueryKeyValuePairNormalizer.cs | 6 +++--- .../Mvc.Core/src/ModelBinding/PrefixContainer.cs | 8 ++++---- src/Mvc/Mvc.Razor/src/RazorFileHierarchy.cs | 4 ++-- .../src/ApplicationModels/PageRouteModelFactory.cs | 6 +++--- .../src/Infrastructure/PageViewLocationExpander.cs | 2 +- src/Mvc/Mvc.TagHelpers/src/GlobbingUrlBuilder.cs | 2 +- .../src/TagHelperOutputExtensions.cs | 4 ++-- .../Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs | 2 +- src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs | 2 +- .../src/Extensions/JsonTypeInfoExtensions.cs | 2 +- .../Negotiate/src/Internal/LdapAdapter.cs | 2 +- src/Servers/HttpSys/src/Helpers.cs | 6 +++--- .../HttpSys/src/RequestProcessing/RequestStream.cs | 6 +++--- src/Servers/IIS/IIS/src/Core/IISHttpContext.IO.cs | 2 +- .../Kestrel/Core/src/Internal/Http/HttpParser.cs | 4 ++-- .../Kestrel/Core/src/Internal/Http2/Http2Stream.cs | 4 ++-- .../Core/src/Internal/Http3/Http3Connection.cs | 2 +- .../Core/src/Internal/Http3/Http3ControlStream.cs | 4 ++-- .../Kestrel/Core/src/Internal/Http3/Http3Stream.cs | 4 ++-- .../Core/src/Internal/Http3/QPackHeaderWriter.cs | 2 +- .../ActivatorUtilities/ActivatorUtilities.cs | 2 +- .../CommandLineUtils/CommandLine/AnsiConsole.cs | 2 +- src/Shared/Hpack/DynamicHPackEncoder.cs | 12 ++++++------ src/Shared/HttpRuleParser.cs | 4 ++-- .../RequestProcessing/NativeRequestContext.cs | 2 +- .../HttpSys/RequestProcessing/RawUrlHelper.cs | 4 ++-- src/Shared/RoslynUtils/BoundedCacheWithFactory.cs | 4 ++-- .../ServerInfrastructure/BufferExtensions.cs | 4 ++-- src/Shared/UrlDecoder/UrlDecoder.cs | 14 +++++++------- src/SignalR/common/Shared/TextMessageParser.cs | 2 +- 55 files changed, 105 insertions(+), 105 deletions(-) diff --git a/src/Components/Endpoints/src/FormMapping/FormDataReader.cs b/src/Components/Endpoints/src/FormMapping/FormDataReader.cs index 85c65e363e93..7105aafdd53f 100644 --- a/src/Components/Endpoints/src/FormMapping/FormDataReader.cs +++ b/src/Components/Endpoints/src/FormMapping/FormDataReader.cs @@ -138,7 +138,7 @@ internal IReadOnlyDictionary> ProcessFormKeys() while (startIndex >= 0) { var endIndex = key.Value.Span[startIndex..].IndexOf(']') + startIndex; - if (endIndex == -1) + if (endIndex < 0) { // Ignore malformed keys break; @@ -157,7 +157,7 @@ internal IReadOnlyDictionary> ProcessFormKeys() var nextOpenBracket = key.Value.Span[(endIndex + 1)..].IndexOf('['); - startIndex = nextOpenBracket != -1 ? endIndex + 1 + nextOpenBracket : -1; + startIndex = nextOpenBracket >= 0 ? endIndex + 1 + nextOpenBracket : -1; } } @@ -264,7 +264,7 @@ internal readonly bool TryGetValues(out StringValues values) => internal string GetLastPrefixSegment() { var index = _currentPrefixBuffer.Span.LastIndexOfAny(".["); - if (index == -1) + if (index < 0) { return _currentPrefixBuffer.ToString(); } diff --git a/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs b/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs index ca292c529da8..8f94a8aefbf7 100644 --- a/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs +++ b/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs @@ -113,7 +113,7 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone // check covers that the sequence starts by 0. if (lastSequence != serverComponent.Sequence - 1) { - if (lastSequence == -1) + if (lastSequence < 0) { Log.DescriptorSequenceMustStartAtZero(_logger, serverComponent.Sequence); } @@ -125,7 +125,7 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone return false; } - if (lastSequence != -1 && !previousInstance.InvocationId.Equals(serverComponent.InvocationId)) + if (lastSequence >= 0 && !previousInstance.InvocationId.Equals(serverComponent.InvocationId)) { Log.MismatchedInvocationId(_logger, previousInstance.InvocationId.ToString("N"), serverComponent.InvocationId.ToString("N")); descriptors.Clear(); diff --git a/src/DataProtection/DataProtection/src/TypeForwardingActivator.cs b/src/DataProtection/DataProtection/src/TypeForwardingActivator.cs index 29b5cc98c65d..b0e87d997c54 100644 --- a/src/DataProtection/DataProtection/src/TypeForwardingActivator.cs +++ b/src/DataProtection/DataProtection/src/TypeForwardingActivator.cs @@ -79,11 +79,11 @@ protected static string RemoveVersionFromAssemblyName(string forwardedTypeName) // Type, Assembly, Version={Version}, Culture={Culture}, PublicKeyToken={Token} var versionStartIndex = forwardedTypeName.IndexOf(", Version=", StringComparison.Ordinal); - while (versionStartIndex != -1) + while (versionStartIndex >= 0) { var versionEndIndex = forwardedTypeName.IndexOf(',', versionStartIndex + ", Version=".Length); - if (versionEndIndex == -1) + if (versionEndIndex < 0) { // No end index, so are done and can remove the rest return forwardedTypeName.Substring(0, versionStartIndex); diff --git a/src/DefaultBuilder/src/WebApplicationBuilder.cs b/src/DefaultBuilder/src/WebApplicationBuilder.cs index 2cff4ae4ffb9..e0d67edf52a9 100644 --- a/src/DefaultBuilder/src/WebApplicationBuilder.cs +++ b/src/DefaultBuilder/src/WebApplicationBuilder.cs @@ -501,7 +501,7 @@ sourceValue is List sourceDescriptions && destinationValue is List destinationDescriptions) { var wireUpIndex = destinationDescriptions.IndexOf(typeof(WireSourcePipeline).FullName!); - if (wireUpIndex != -1) + if (wireUpIndex >= 0) { destinationDescriptions.RemoveAt(wireUpIndex); destinationDescriptions.InsertRange(wireUpIndex, sourceDescriptions); diff --git a/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs b/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs index b1feb2a33cad..743ae0d8f587 100644 --- a/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs +++ b/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs @@ -180,7 +180,7 @@ public IChangeToken Watch(string pattern) private static bool HasInvalidPathChars(string path) { - return path.IndexOfAny(_invalidFileNameChars) != -1; + return path.IndexOfAny(_invalidFileNameChars) >= 0; } #region Helper methods diff --git a/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs b/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs index f21e34b5b0e9..34acf3ef6fab 100644 --- a/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs +++ b/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs @@ -63,13 +63,13 @@ internal EmbeddedFilesManifest(ManifestDirectory rootDirectory) private static StringSegment RemoveLeadingAndTrailingDirectorySeparators(string path) { Debug.Assert(path.Length > 0); - var start = Array.IndexOf(_separators, path[0]) == -1 ? 0 : 1; + var start = Array.IndexOf(_separators, path[0]) < 0 ? 0 : 1; if (start == path.Length) { return StringSegment.Empty; } - var end = Array.IndexOf(_separators, path[path.Length - 1]) == -1 ? path.Length : path.Length - 1; + var end = Array.IndexOf(_separators, path[path.Length - 1]) < 0 ? path.Length : path.Length - 1; var trimmed = new StringSegment(path, start, end - start); return trimmed; } @@ -84,5 +84,5 @@ internal EmbeddedFilesManifest Scope(string path) throw new InvalidOperationException($"Invalid path: '{path}'"); } - private static bool HasInvalidPathChars(string path) => path.IndexOfAny(_invalidFileNameChars) != -1; + private static bool HasInvalidPathChars(string path) => path.IndexOfAny(_invalidFileNameChars) >= 0; } diff --git a/src/Http/Headers/src/ContentDispositionHeaderValue.cs b/src/Http/Headers/src/ContentDispositionHeaderValue.cs index c4782a32b82e..4eb307d9c721 100644 --- a/src/Http/Headers/src/ContentDispositionHeaderValue.cs +++ b/src/Http/Headers/src/ContentDispositionHeaderValue.cs @@ -487,7 +487,7 @@ private StringSegment EncodeAndQuoteMime(StringSegment input) if (needsQuotes) { - if (result.IndexOfAny(EscapeChars) != -1) + if (result.IndexOfAny(EscapeChars) >= 0) { // '\' and '"' must be escaped in a quoted string result = result.ToString().Replace(@"\", @"\\").Replace(@"""", @"\"""); diff --git a/src/Http/Headers/src/HeaderUtilities.cs b/src/Http/Headers/src/HeaderUtilities.cs index ec93bb8723ab..d3bb20224a0f 100644 --- a/src/Http/Headers/src/HeaderUtilities.cs +++ b/src/Http/Headers/src/HeaderUtilities.cs @@ -196,7 +196,7 @@ private static int AdvanceCacheDirectiveIndex(int current, string headerValue) // Find the next delimiter current = headerValue.IndexOf(',', current); - if (current == -1) + if (current < 0) { // If no delimiter found, skip to the end return headerValue.Length; diff --git a/src/Http/Headers/src/MediaTypeHeaderValue.cs b/src/Http/Headers/src/MediaTypeHeaderValue.cs index 693ebcef886d..63b02e983f80 100644 --- a/src/Http/Headers/src/MediaTypeHeaderValue.cs +++ b/src/Http/Headers/src/MediaTypeHeaderValue.cs @@ -278,7 +278,7 @@ public StringSegment SubTypeWithoutSuffix { var subType = SubType; var startOfSuffix = subType.LastIndexOf(PlusCharacter); - if (startOfSuffix == -1) + if (startOfSuffix < 0) { return subType; } @@ -303,7 +303,7 @@ public StringSegment Suffix { var subType = SubType; var startOfSuffix = subType.LastIndexOf(PlusCharacter); - if (startOfSuffix == -1) + if (startOfSuffix < 0) { return default(StringSegment); } @@ -718,7 +718,7 @@ private bool MatchesSubtype(StringSegment mediaType) StringSegment suffix; var startOfSuffix = subType.LastIndexOf(PlusCharacter); - if (startOfSuffix == -1) + if (startOfSuffix < 0) { suffix = default(StringSegment); } @@ -756,7 +756,7 @@ private bool MatchesSubtypeWithoutSuffix(MediaTypeHeaderValue set) private bool MatchesSubtypeWithoutSuffix(StringSegment subType, int startOfSuffix) { StringSegment subTypeWithoutSuffix; - if (startOfSuffix == -1) + if (startOfSuffix < 0) { subTypeWithoutSuffix = subType; } diff --git a/src/Http/Http.Abstractions/src/Internal/HeaderSegmentCollection.cs b/src/Http/Http.Abstractions/src/Internal/HeaderSegmentCollection.cs index d65cd7585b9d..f956b9828c9e 100644 --- a/src/Http/Http.Abstractions/src/Internal/HeaderSegmentCollection.cs +++ b/src/Http/Http.Abstractions/src/Internal/HeaderSegmentCollection.cs @@ -141,7 +141,7 @@ public bool MoveNext() _trailingStart = -1; if (_offset == _headerLength && - _leadingStart != -1 && + _leadingStart >= 0 && _leadingStart != _offset) { // Also produce trailing whitespace @@ -186,9 +186,9 @@ public bool MoveNext() switch (attr) { case Attr.Delimiter: - _valueStart = _valueStart == -1 ? _offset : _valueStart; - _valueEnd = _valueEnd == -1 ? _offset : _valueEnd; - _trailingStart = _trailingStart == -1 ? _offset : _trailingStart; + _valueStart = _valueStart < 0 ? _offset : _valueStart; + _valueEnd = _valueEnd < 0 ? _offset : _valueEnd; + _trailingStart = _trailingStart < 0 ? _offset : _trailingStart; _leadingEnd = _offset; _mode = Mode.Produce; break; diff --git a/src/Http/Http.Abstractions/src/PathString.cs b/src/Http/Http.Abstractions/src/PathString.cs index fae60dc640b0..71509cff82e6 100644 --- a/src/Http/Http.Abstractions/src/PathString.cs +++ b/src/Http/Http.Abstractions/src/PathString.cs @@ -180,7 +180,7 @@ private static string ToEscapedUriComponent(string value, int i) public static PathString FromUriComponent(string uriComponent) { int position = uriComponent.IndexOf('%'); - if (position == -1) + if (position < 0) { return new PathString(uriComponent); } diff --git a/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs b/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs index b3d4b30ae16a..4099fd3b6127 100644 --- a/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs @@ -134,7 +134,7 @@ internal static bool IsFileName(ReadOnlySpan value) } var dotIndex = value.IndexOf('.'); - if (dotIndex == -1) + if (dotIndex < 0) { // No dot. return false; diff --git a/src/Http/Routing/src/InlineRouteParameterParser.cs b/src/Http/Routing/src/InlineRouteParameterParser.cs index 5dacbbd6f204..9e980d2d76e3 100644 --- a/src/Http/Routing/src/InlineRouteParameterParser.cs +++ b/src/Http/Routing/src/InlineRouteParameterParser.cs @@ -167,7 +167,7 @@ private static ConstraintParseResults ParseConstraints( // determine if the terminator needs to be consumed as part of the current constraint // specification. var indexOfClosingParantheses = routeParameter.IndexOf(')', currentIndex + 1); - if (indexOfClosingParantheses == -1) + if (indexOfClosingParantheses < 0) { constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex); inlineConstraints.Add(new InlineConstraint(constraintText)); diff --git a/src/Http/Routing/src/Matching/NegotiationMatcherPolicy.cs b/src/Http/Routing/src/Matching/NegotiationMatcherPolicy.cs index c6670eace440..b0b543cb7405 100644 --- a/src/Http/Routing/src/Matching/NegotiationMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/NegotiationMatcherPolicy.cs @@ -431,7 +431,7 @@ public override int GetDestination(HttpContext httpContext) if (valueQuality > currentQuality) { var newDestination = GetDestination(valueToken); - if (newDestination != -1) + if (newDestination >= 0) { currentSelectedValue = valueToken; selectedDestination = newDestination; @@ -447,7 +447,7 @@ public override int GetDestination(HttpContext httpContext) if (newServerQuality > currentServerQuality) { var newDestination = GetDestination(valueToken); - if (newDestination != -1) + if (newDestination >= 0) { currentSelectedValue = valueToken; selectedDestination = newDestination; diff --git a/src/Http/Routing/src/PathTokenizer.cs b/src/Http/Routing/src/PathTokenizer.cs index 0b8da0f3100d..a70582ca04dc 100644 --- a/src/Http/Routing/src/PathTokenizer.cs +++ b/src/Http/Routing/src/PathTokenizer.cs @@ -29,7 +29,7 @@ public int Count { get { - if (_count == -1) + if (_count < 0) { // We haven't computed the real count of segments yet. if (_path.Length == 0) @@ -79,7 +79,7 @@ public StringSegment this[int index] // Skip the first `/`. var delimiterIndex = 1; - while ((delimiterIndex = _path.IndexOf('/', delimiterIndex)) != -1) + while ((delimiterIndex = _path.IndexOf('/', delimiterIndex)) >= 0) { if (currentSegmentIndex++ == index) { @@ -158,7 +158,7 @@ public bool MoveNext() return false; } - if (_index == -1) + if (_index < 0) { // Skip the first `/`. _index = 1; @@ -176,7 +176,7 @@ public bool MoveNext() } var delimiterIndex = _path.IndexOf('/', _index); - if (delimiterIndex != -1) + if (delimiterIndex >= 0) { _length = delimiterIndex - _index; return true; diff --git a/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs b/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs index cc814b6b0d7c..08e9603c997d 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs @@ -390,7 +390,7 @@ private static bool MatchComplexSegmentCore( StringComparison.OrdinalIgnoreCase); } - if (indexOfLiteral == -1) + if (indexOfLiteral < 0) { // If we couldn't find this literal index, this segment cannot match return false; diff --git a/src/Http/Routing/src/Patterns/RoutePatternParser.cs b/src/Http/Routing/src/Patterns/RoutePatternParser.cs index 31ae156ea530..88c9157a089d 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternParser.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternParser.cs @@ -545,7 +545,7 @@ public string Capture() private string DebuggerToString() { - if (_index == -1) + if (_index < 0) { return _template; } diff --git a/src/Http/Routing/src/RouteCollection.cs b/src/Http/Routing/src/RouteCollection.cs index 21a6d509f4bb..9f29e822479b 100644 --- a/src/Http/Routing/src/RouteCollection.cs +++ b/src/Http/Routing/src/RouteCollection.cs @@ -157,7 +157,7 @@ public virtual async Task RouteAsync(RouteContext context) var urlWithoutQueryString = url; var queryString = string.Empty; - if (indexOfSeparator != -1) + if (indexOfSeparator >= 0) { urlWithoutQueryString = url.Substring(0, indexOfSeparator); queryString = url.Substring(indexOfSeparator); diff --git a/src/Http/WebUtilities/src/FormPipeReader.cs b/src/Http/WebUtilities/src/FormPipeReader.cs index 7e2c8ede417a..b19657907440 100644 --- a/src/Http/WebUtilities/src/FormPipeReader.cs +++ b/src/Http/WebUtilities/src/FormPipeReader.cs @@ -167,7 +167,7 @@ private void ParseFormValuesFast(ReadOnlySpan span, var ampersand = span.IndexOf(andDelimiter); ReadOnlySpan keyValuePair; int equals; - var foundAmpersand = ampersand != -1; + var foundAmpersand = ampersand >= 0; if (foundAmpersand) { @@ -196,7 +196,7 @@ private void ParseFormValuesFast(ReadOnlySpan span, equals = keyValuePair.IndexOf(equalsDelimiter); - if (equals == -1) + if (equals < 0) { // Too long for the whole segment to be a key. if (keyValuePair.Length > KeyLengthLimit) diff --git a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs index da6d8a4e2c16..25e8332e002a 100644 --- a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs +++ b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs @@ -397,7 +397,7 @@ private ReadLineStepResult ReadLineStep(ref StringBuilder? sb, ref bool consumeL var index = span.IndexOfAny(carriageReturn, lineFeed); - if (index != -1) + if (index >= 0) { if (span[index] == carriageReturn) { diff --git a/src/Http/WebUtilities/src/QueryHelpers.cs b/src/Http/WebUtilities/src/QueryHelpers.cs index 0441447fb4ee..2f7448e115cf 100644 --- a/src/Http/WebUtilities/src/QueryHelpers.cs +++ b/src/Http/WebUtilities/src/QueryHelpers.cs @@ -84,14 +84,14 @@ public static string AddQueryString( var uriToBeAppended = uri.AsSpan(); var anchorText = ReadOnlySpan.Empty; // If there is an anchor, then the query string must be inserted before its first occurrence. - if (anchorIndex != -1) + if (anchorIndex >= 0) { anchorText = uriToBeAppended.Slice(anchorIndex); uriToBeAppended = uriToBeAppended.Slice(0, anchorIndex); } var queryIndex = uriToBeAppended.IndexOf('?'); - var hasQuery = queryIndex != -1; + var hasQuery = queryIndex >= 0; var sb = new StringBuilder(); sb.Append(uriToBeAppended); diff --git a/src/Identity/Extensions.Core/src/DefaultPersonalDataProtector.cs b/src/Identity/Extensions.Core/src/DefaultPersonalDataProtector.cs index b52c459b11be..a5e339a86c3b 100644 --- a/src/Identity/Extensions.Core/src/DefaultPersonalDataProtector.cs +++ b/src/Identity/Extensions.Core/src/DefaultPersonalDataProtector.cs @@ -35,7 +35,7 @@ public DefaultPersonalDataProtector(ILookupProtectorKeyRing keyRing, ILookupProt { Debug.Assert(data != null); var split = data.IndexOf(':'); - if (split == -1 || split == data.Length - 1) + if (split < 0 || split == data.Length - 1) { throw new InvalidOperationException("Malformed data."); } diff --git a/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs b/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs index 6b2a118cb132..2fb197ed9989 100644 --- a/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs +++ b/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs @@ -434,7 +434,7 @@ private static bool TryValidateHost(string host) } var firstNonHostCharIdx = host.AsSpan().IndexOfAnyExcept(HostChars); - if (firstNonHostCharIdx == -1) + if (firstNonHostCharIdx < 0) { // no port return true; diff --git a/src/Middleware/Rewrite/src/RedirectRule.cs b/src/Middleware/Rewrite/src/RedirectRule.cs index d934aa8dd66a..dbb035e6286e 100644 --- a/src/Middleware/Rewrite/src/RedirectRule.cs +++ b/src/Middleware/Rewrite/src/RedirectRule.cs @@ -65,7 +65,7 @@ public void ApplyRule(RewriteContext context) schemeSplit += Uri.SchemeDelimiter.Length; var pathSplit = newPath.IndexOf('/', schemeSplit); - if (pathSplit == -1) + if (pathSplit < 0) { host = new HostString(newPath.Substring(schemeSplit)); newPath = "/"; diff --git a/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs b/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs index 7695fd196a57..23fced0a4e39 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs @@ -91,7 +91,7 @@ private static bool TryParseValue(string value, ref int index, out MediaTypeSegm { // The parsing failed. currentIndex = value.IndexOf(',', currentIndex); - if (currentIndex == -1) + if (currentIndex < 0) { index = value.Length; return false; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryKeyValuePairNormalizer.cs b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryKeyValuePairNormalizer.cs index 4fb2765325f5..65dac9115f85 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryKeyValuePairNormalizer.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryKeyValuePairNormalizer.cs @@ -45,7 +45,7 @@ private static string NormalizeJQueryToMvc(StringBuilder builder, string key) } var indexOpen = key.IndexOf('['); - if (indexOpen == -1) + if (indexOpen < 0) { // Fast path, no normalization needed. // This skips string conversion and allocating the string builder. @@ -55,7 +55,7 @@ private static string NormalizeJQueryToMvc(StringBuilder builder, string key) var position = 0; while (position < key.Length) { - if (indexOpen == -1) + if (indexOpen < 0) { // No more brackets. builder.Append(key, position, key.Length - position); @@ -66,7 +66,7 @@ private static string NormalizeJQueryToMvc(StringBuilder builder, string key) // Find closing bracket. var indexClose = key.IndexOf(']', indexOpen); - if (indexClose == -1) + if (indexClose < 0) { throw new ArgumentException( message: Resources.FormatJQueryFormValueProviderFactory_MissingClosingBracket(key), diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs b/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs index aeab151eb80f..758e58bd184e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs @@ -58,7 +58,7 @@ public bool ContainsPrefix(string prefix) return true; // Empty prefix matches all elements. } - return BinarySearch(prefix) > -1; + return BinarySearch(prefix) >= 0; } /// @@ -110,7 +110,7 @@ private static void GetKeyFromEmptyPrefix(string entry, IDictionary GetViewStartPaths(string path) var builder = new StringBuilder(path); var maxIterations = 255; var index = path.Length; - while (maxIterations-- > 0 && index > 1 && (index = path.LastIndexOf('/', index - 1)) != -1) + while (maxIterations-- > 0 && index > 1 && (index = path.LastIndexOf('/', index - 1)) >= 0) { builder.Length = index + 1; builder.Append(ViewStartFileName); diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs index 5b2b8ca79c09..50f44873eba6 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs @@ -69,7 +69,7 @@ private static void PopulateRouteModel(PageRouteModel model, string pageRoute, s selectorModel.AttributeRouteModel!.SuppressLinkGeneration = true; var index = pageRoute.LastIndexOf('/'); - var parentDirectoryPath = index == -1 ? + var parentDirectoryPath = index < 0 ? string.Empty : pageRoute.Substring(0, index); model.Selectors.Add(CreateSelectorModel(parentDirectoryPath, routeTemplate)); @@ -89,7 +89,7 @@ internal bool TryParseAreaPath( Debug.Assert(relativePath.StartsWith('/')); // Parse the area root directory. var areaRootEndIndex = relativePath.IndexOf('/', startIndex: 1); - if (areaRootEndIndex == -1 || + if (areaRootEndIndex < 0 || areaRootEndIndex >= relativePath.Length - 1 || // There's at least one token after the area root. !relativePath.StartsWith(_normalizedAreaRootDirectory, StringComparison.OrdinalIgnoreCase)) // The path must start with area root. { @@ -99,7 +99,7 @@ internal bool TryParseAreaPath( // The first directory that follows the area root is the area name. var areaEndIndex = relativePath.IndexOf('/', startIndex: areaRootEndIndex + 1); - if (areaEndIndex == -1 || areaEndIndex == relativePath.Length) + if (areaEndIndex < 0 || areaEndIndex == relativePath.Length) { Log.UnsupportedAreaPath(_logger, relativePath); return false; diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageViewLocationExpander.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageViewLocationExpander.cs index 6891699b5680..0847c6a49367 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageViewLocationExpander.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageViewLocationExpander.cs @@ -55,7 +55,7 @@ IEnumerable ExpandPageHierarchy() // This is easy because the 'page' token already trims the root directory. var end = context.PageName.Length; - while (end > 0 && (end = context.PageName.LastIndexOf('/', end - 1)) != -1) + while (end > 0 && (end = context.PageName.LastIndexOf('/', end - 1)) >= 0) { // PageName always starts with `/` yield return location.Replace("/{1}/", context.PageName.Substring(0, end + 1)); diff --git a/src/Mvc/Mvc.TagHelpers/src/GlobbingUrlBuilder.cs b/src/Mvc/Mvc.TagHelpers/src/GlobbingUrlBuilder.cs index 0deb9113f551..695bdbc5b34a 100644 --- a/src/Mvc/Mvc.TagHelpers/src/GlobbingUrlBuilder.cs +++ b/src/Mvc/Mvc.TagHelpers/src/GlobbingUrlBuilder.cs @@ -305,7 +305,7 @@ private static string NormalizePath(StringSegment value) private static bool IsWhiteSpace(string value, int index) { var ch = value[index]; - return ValidAttributeWhitespaceChars.AsSpan().IndexOf(ch) != -1; + return ValidAttributeWhitespaceChars.AsSpan().IndexOf(ch) >= 0; } private static StringSegment Trim(StringSegment value) diff --git a/src/Mvc/Mvc.TagHelpers/src/TagHelperOutputExtensions.cs b/src/Mvc/Mvc.TagHelpers/src/TagHelperOutputExtensions.cs index 8acb3ee4fa08..5a668d6fc7fc 100644 --- a/src/Mvc/Mvc.TagHelpers/src/TagHelperOutputExtensions.cs +++ b/src/Mvc/Mvc.TagHelpers/src/TagHelperOutputExtensions.cs @@ -296,7 +296,7 @@ private static void CopyHtmlAttribute( { var previousName = allAttributes[i].Name; var index = IndexOfFirstMatch(previousName, tagHelperOutput.Attributes); - if (index != -1) + if (index >= 0) { tagHelperOutput.Attributes.Insert(index + 1, existingAttribute); return; @@ -311,7 +311,7 @@ private static void CopyHtmlAttribute( { var nextName = allAttributes[i].Name; var index = IndexOfFirstMatch(nextName, tagHelperOutput.Attributes); - if (index != -1) + if (index >= 0) { tagHelperOutput.Attributes.Insert(index, existingAttribute); return; diff --git a/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs b/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs index 9674433ba5f1..b5a1887eee61 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs @@ -373,7 +373,7 @@ public virtual TagBuilder GenerateLabel( if (resolvedLabelText == null && expression != null) { var index = expression.LastIndexOf('.'); - if (index == -1) + if (index < 0) { // Expression does not contain a dot separator. resolvedLabelText = expression; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs index 778023689045..ba0a790fe4c7 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs @@ -143,7 +143,7 @@ private static string GetNextShorterExpression(string expression) } var lastDot = expression.LastIndexOf('.'); - if (lastDot == -1) + if (lastDot < 0) { return string.Empty; } diff --git a/src/OpenApi/src/Extensions/JsonTypeInfoExtensions.cs b/src/OpenApi/src/Extensions/JsonTypeInfoExtensions.cs index e09e2626444c..c652398ab953 100644 --- a/src/OpenApi/src/Extensions/JsonTypeInfoExtensions.cs +++ b/src/OpenApi/src/Extensions/JsonTypeInfoExtensions.cs @@ -108,7 +108,7 @@ internal static string GetSchemaReferenceId(this Type type, JsonSerializerOption // so we check if the name contains a backtick already. // For more information: https://github.com/dotnet/aspnetcore/issues/59092 var backtickIndex = type.Name.LastIndexOf('`'); - var isNestedGenericType = backtickIndex == -1; + var isNestedGenericType = backtickIndex < 0; var genericTypeName = isNestedGenericType ? type.Name : type.Name[..backtickIndex]; var genericArguments = type.GetGenericArguments(); diff --git a/src/Security/Authentication/Negotiate/src/Internal/LdapAdapter.cs b/src/Security/Authentication/Negotiate/src/Internal/LdapAdapter.cs index 45d3973a140f..b0b281ba9a25 100644 --- a/src/Security/Authentication/Negotiate/src/Internal/LdapAdapter.cs +++ b/src/Security/Authentication/Negotiate/src/Internal/LdapAdapter.cs @@ -21,7 +21,7 @@ public static async Task RetrieveClaimsAsync(LdapSettings settings, ClaimsIdenti { var user = identity.Name!; var userAccountNameIndex = user.IndexOf('@'); - var userAccountName = userAccountNameIndex == -1 ? user : user.Substring(0, userAccountNameIndex); + var userAccountName = userAccountNameIndex < 0 ? user : user.Substring(0, userAccountNameIndex); if (settings.ClaimsCache == null) { diff --git a/src/Servers/HttpSys/src/Helpers.cs b/src/Servers/HttpSys/src/Helpers.cs index fb68d2e67e15..5d8f8ca7ddce 100644 --- a/src/Servers/HttpSys/src/Helpers.cs +++ b/src/Servers/HttpSys/src/Helpers.cs @@ -43,11 +43,11 @@ internal static ArraySegment GetChunkHeader(int size) for (i = 0; i < 8; i++, size <<= 4) { - // offset == -1 means that we haven't found a non-zero nibble + // offset == -1 (or offset < 0) means that we haven't found a non-zero nibble // yet. If we haven't found one, and the current one is zero, // don't do anything. - if (offset == -1) + if (offset < 0) { if ((size & mask) == 0) { @@ -72,7 +72,7 @@ internal static ArraySegment GetChunkHeader(int size) // If we haven't found a non-zero nibble yet, we've found one // now, so remember that. - if (offset == -1) + if (offset < 0) { offset = i; } diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs index 14ffff214c50..bbe8c50cc685 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs @@ -113,12 +113,12 @@ public override unsafe int Read([In, Out] byte[] buffer, int offset, int size) uint dataRead = 0; - if (_dataChunkIndex != -1) + if (_dataChunkIndex >= 0) { dataRead = _requestContext.Request.GetChunks(ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size); } - if (_dataChunkIndex == -1 && dataRead == 0) + if (_dataChunkIndex < 0 && dataRead == 0) { uint statusCode = 0; uint extraDataRead = 0; @@ -204,7 +204,7 @@ public override unsafe Task ReadAsync(byte[] buffer, int offset, int size, RequestStreamAsyncResult? asyncResult = null; uint dataRead = 0; - if (_dataChunkIndex != -1) + if (_dataChunkIndex >= 0) { dataRead = _requestContext.Request.GetChunks(ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size); if (dataRead > 0) diff --git a/src/Servers/IIS/IIS/src/Core/IISHttpContext.IO.cs b/src/Servers/IIS/IIS/src/Core/IISHttpContext.IO.cs index 61d11e20c89c..3f78ff3257ec 100644 --- a/src/Servers/IIS/IIS/src/Core/IISHttpContext.IO.cs +++ b/src/Servers/IIS/IIS/src/Core/IISHttpContext.IO.cs @@ -111,7 +111,7 @@ private async Task ReadBody() } // Read was not canceled because of incoming write or IO stopping - if (read != -1) + if (read > 0) { _consumedBytes += read; _bodyInputPipe.Writer.Advance(read); diff --git a/src/Servers/Kestrel/Core/src/Internal/Http/HttpParser.cs b/src/Servers/Kestrel/Core/src/Internal/Http/HttpParser.cs index 5ef492b5d2b0..3f43e7f7ee3a 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http/HttpParser.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http/HttpParser.cs @@ -369,7 +369,7 @@ private int ParseMultiSpanHeader(TRequestHandler handler, ref SequenceReader _context.TimeoutControl; // The default error value is -1. If it hasn't been changed before abort is called then default to HTTP/3's NoError value. - private Http3ErrorCode Http3ErrorCodeOrNoError => _errorCodeFeature.Error == -1 ? Http3ErrorCode.NoError : (Http3ErrorCode)_errorCodeFeature.Error; + private Http3ErrorCode Http3ErrorCodeOrNoError => _errorCodeFeature.Error < 0 ? Http3ErrorCode.NoError : (Http3ErrorCode)_errorCodeFeature.Error; public void StopProcessingNextRequest(ConnectionEndReason reason) => StopProcessingNextRequest(serverInitiated: true, reason); diff --git a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3ControlStream.cs b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3ControlStream.cs index 216eb9fc09b9..5e84d1495835 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3ControlStream.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3ControlStream.cs @@ -76,7 +76,7 @@ private void OnStreamClosed() public KestrelTrace Log => _context.ServiceContext.Log; public long StreamTimeoutTimestamp { get; set; } - public bool IsReceivingHeader => _headerType == -1; + public bool IsReceivingHeader => _headerType < 0; public bool IsDraining => false; public bool IsRequestStream => false; public string TraceIdentifier => _context.StreamContext.ConnectionId; @@ -195,7 +195,7 @@ public async Task ProcessRequestAsync(IHttpApplication appli // avoid perf issues with the current implementation // we can defer the reading until now // (https://github.com/dotnet/aspnetcore/issues/42789) - if (_headerType == -1) + if (_headerType < 0) { _headerType = await TryReadStreamHeaderAsync(); } diff --git a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs index 36c87cd8ef7b..3ab605554a96 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs @@ -1079,9 +1079,9 @@ private bool TryValidatePseudoHeaders() } var queryIndex = path.IndexOf('?'); - QueryString = queryIndex == -1 ? string.Empty : path.Substring(queryIndex); + QueryString = queryIndex < 0 ? string.Empty : path.Substring(queryIndex); - var pathSegment = queryIndex == -1 ? path.AsSpan() : path.AsSpan(0, queryIndex); + var pathSegment = queryIndex < 0 ? path.AsSpan() : path.AsSpan(0, queryIndex); return TryValidatePath(pathSegment); } diff --git a/src/Servers/Kestrel/Core/src/Internal/Http3/QPackHeaderWriter.cs b/src/Servers/Kestrel/Core/src/Internal/Http3/QPackHeaderWriter.cs index d8c601acf212..7d98bcc987fe 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http3/QPackHeaderWriter.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http3/QPackHeaderWriter.cs @@ -103,7 +103,7 @@ private static bool Encode(Http3HeadersEnumerator headersEnumerator, Span private static bool EncodeHeader(Span buffer, int staticTableId, string name, string value, Encoding? valueEncoding, out int headerLength) { - return staticTableId == -1 + return staticTableId < 0 ? QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, value, valueEncoding, buffer, out headerLength) : QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReference(staticTableId, value, valueEncoding, buffer, out headerLength); } diff --git a/src/Shared/ActivatorUtilities/ActivatorUtilities.cs b/src/Shared/ActivatorUtilities/ActivatorUtilities.cs index 38930b75b38a..deb462a91215 100644 --- a/src/Shared/ActivatorUtilities/ActivatorUtilities.cs +++ b/src/Shared/ActivatorUtilities/ActivatorUtilities.cs @@ -45,7 +45,7 @@ public static object CreateInstance( } } - if (bestLength == -1) + if (bestLength < 0) { var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor."; throw new InvalidOperationException(message); diff --git a/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs b/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs index 70a92b1f247b..c0564d19f76d 100644 --- a/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs +++ b/src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs @@ -64,7 +64,7 @@ public void WriteLine(string message) for (; ; ) { var escapeIndex = message.IndexOf("\x1b[", escapeScan, StringComparison.Ordinal); - if (escapeIndex == -1) + if (escapeIndex < 0) { var text = message.Substring(escapeScan); Writer.Write(text); diff --git a/src/Shared/Hpack/DynamicHPackEncoder.cs b/src/Shared/Hpack/DynamicHPackEncoder.cs index a4a0aa7c0184..2131b4263d2e 100644 --- a/src/Shared/Hpack/DynamicHPackEncoder.cs +++ b/src/Shared/Hpack/DynamicHPackEncoder.cs @@ -75,7 +75,7 @@ public bool EncodeHeader(Span buffer, int staticTableIndex, HeaderEncoding { int index = ResolveDynamicTableIndex(staticTableIndex, name); - return index == -1 + return index < 0 ? HPackEncoder.EncodeLiteralHeaderFieldNeverIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten) : HPackEncoder.EncodeLiteralHeaderFieldNeverIndexing(index, value, valueEncoding, buffer, out bytesWritten); } @@ -83,7 +83,7 @@ public bool EncodeHeader(Span buffer, int staticTableIndex, HeaderEncoding // No dynamic table. Only use the static table. if (!_allowDynamicCompression || _maxHeaderTableSize == 0 || encodingHint == HeaderEncodingHint.IgnoreIndex) { - return staticTableIndex == -1 + return staticTableIndex < 0 ? HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten) : HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexing(staticTableIndex, value, valueEncoding, buffer, out bytesWritten); } @@ -95,7 +95,7 @@ public bool EncodeHeader(Span buffer, int staticTableIndex, HeaderEncoding { int index = ResolveDynamicTableIndex(staticTableIndex, name); - return index == -1 + return index < 0 ? HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten) : HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexing(index, value, valueEncoding, buffer, out bytesWritten); } @@ -105,7 +105,7 @@ public bool EncodeHeader(Span buffer, int staticTableIndex, HeaderEncoding private int ResolveDynamicTableIndex(int staticTableIndex, string name) { - if (staticTableIndex != -1) + if (staticTableIndex >= 0) { // Prefer static table index. return staticTableIndex; @@ -129,7 +129,7 @@ private bool EncodeDynamicHeader(Span buffer, int staticTableIndex, string // Doesn't exist in dynamic table. Add new entry to dynamic table. int index = ResolveDynamicTableIndex(staticTableIndex, name); - bool success = index == -1 + bool success = index < 0 ? HPackEncoder.EncodeLiteralHeaderFieldIndexingNewName(name, value, valueEncoding, buffer, out bytesWritten) : HPackEncoder.EncodeLiteralHeaderFieldIndexing(index, value, valueEncoding, buffer, out bytesWritten); @@ -204,7 +204,7 @@ private int CalculateDynamicTableIndex(string name) private int CalculateDynamicTableIndex(int index) { - return index == -1 ? -1 : index - Head.Before!.Index + 1 + H2StaticTable.Count; + return index < 0 ? -1 : index - Head.Before!.Index + 1 + H2StaticTable.Count; } private void AddHeaderEntry(string name, string value, uint headerSize) diff --git a/src/Shared/HttpRuleParser.cs b/src/Shared/HttpRuleParser.cs index e171db6ca266..ba6f9cd4d540 100644 --- a/src/Shared/HttpRuleParser.cs +++ b/src/Shared/HttpRuleParser.cs @@ -62,7 +62,7 @@ internal static int GetTokenLength(StringSegment input, int startIndex) var subspan = input.AsSpan(startIndex); var firstNonTokenCharIdx = subspan.IndexOfAnyExcept(TokenChars); - return (firstNonTokenCharIdx == -1) ? subspan.Length : firstNonTokenCharIdx; + return (firstNonTokenCharIdx < 0) ? subspan.Length : firstNonTokenCharIdx; } internal static int GetWhitespaceLength(StringSegment input, int startIndex) @@ -172,7 +172,7 @@ internal static HttpParseResult GetQuotedPairLength(StringSegment input, int sta // Quoted-char has 2 characters. Check whether there are 2 chars left ('\' + char) // If so, check whether the character is in the range 0-127. If not, it's an invalid value. - if ((startIndex + 2 > input.Length) || (input[startIndex + 1] > 127)) + if ((startIndex > input.Length - 2) || (input[startIndex + 1] > 127)) { return HttpParseResult.InvalidFormat; } diff --git a/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs b/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs index e4a6622b5271..d45cd3444363 100644 --- a/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs +++ b/src/Shared/HttpSys/RequestProcessing/NativeRequestContext.cs @@ -684,7 +684,7 @@ private uint GetChunksHelper(ref int dataChunkIndex, ref uint dataChunkOffset, b { uint dataRead = 0; - if (request->EntityChunkCount > 0 && dataChunkIndex < request->EntityChunkCount && dataChunkIndex != -1) + if (request->EntityChunkCount > 0 && dataChunkIndex < request->EntityChunkCount && dataChunkIndex >= 0) { var pDataChunk = (HTTP_DATA_CHUNK*)(fixup + (byte*)&request->pEntityChunks[dataChunkIndex]); diff --git a/src/Shared/HttpSys/RequestProcessing/RawUrlHelper.cs b/src/Shared/HttpSys/RequestProcessing/RawUrlHelper.cs index e9b1551d4c80..393dd19ad811 100644 --- a/src/Shared/HttpSys/RequestProcessing/RawUrlHelper.cs +++ b/src/Shared/HttpSys/RequestProcessing/RawUrlHelper.cs @@ -34,7 +34,7 @@ public static Span GetPath(Span raw) // between the authority and the '?' character: It's safe to just look for the first // '/' after the authority to determine the beginning of the path. pathStartIndex = Find(raw, authorityStartIndex, (byte)'/'); - if (pathStartIndex == -1) + if (pathStartIndex < 0) { // e.g. for request lines like: 'GET http://myserver' (no final '/') // At this point we can return a path with a slash. @@ -133,7 +133,7 @@ private static int FindHttpOrHttps(Span raw) private static int Find(Span raw, int begin, byte target) { var idx = raw.Slice(begin).IndexOf(target); - if (idx != -1) + if (idx >= 0) { return idx + begin; } diff --git a/src/Shared/RoslynUtils/BoundedCacheWithFactory.cs b/src/Shared/RoslynUtils/BoundedCacheWithFactory.cs index c04cc3578643..f669efeee28b 100644 --- a/src/Shared/RoslynUtils/BoundedCacheWithFactory.cs +++ b/src/Shared/RoslynUtils/BoundedCacheWithFactory.cs @@ -38,7 +38,7 @@ public TValue GetOrCreateValue(TKey key, Func valueFactory) if (!weakReferencedEntry.TryGetTarget(out var cachedEntry) || cachedEntry == null) { - if (indexToSetTarget == -1) + if (indexToSetTarget < 0) { indexToSetTarget = i; } @@ -56,7 +56,7 @@ public TValue GetOrCreateValue(TKey key, Func valueFactory) } } - if (indexToSetTarget == -1) + if (indexToSetTarget < 0) { indexToSetTarget = 0; } diff --git a/src/Shared/ServerInfrastructure/BufferExtensions.cs b/src/Shared/ServerInfrastructure/BufferExtensions.cs index 64a0704edd3e..2673cd23fa99 100644 --- a/src/Shared/ServerInfrastructure/BufferExtensions.cs +++ b/src/Shared/ServerInfrastructure/BufferExtensions.cs @@ -72,7 +72,7 @@ public static ArraySegment GetArray(this ReadOnlyMemory memory) if (source.IsSingleSegment) { int index = source.First.Span.IndexOfAny(value0, value1); - if (index != -1) + if (index >= 0) { return source.GetPosition(index); } @@ -92,7 +92,7 @@ public static ArraySegment GetArray(this ReadOnlyMemory memory) while (source.TryGet(ref position, out ReadOnlyMemory memory)) { int index = memory.Span.IndexOfAny(value0, value1); - if (index != -1) + if (index >= 0) { return source.GetPosition(index, result); } diff --git a/src/Shared/UrlDecoder/UrlDecoder.cs b/src/Shared/UrlDecoder/UrlDecoder.cs index c6ccb4884315..3a91bcefe78e 100644 --- a/src/Shared/UrlDecoder/UrlDecoder.cs +++ b/src/Shared/UrlDecoder/UrlDecoder.cs @@ -98,7 +98,7 @@ private static bool DecodeCore(ref int sourceIndex, ref int destinationIndex, Sp // preserves the original head. if the percent-encodings cannot be interpreted as sequence of UTF-8 octets, // bytes from this till the last scanned one will be copied to the memory pointed by writer. var byte1 = UnescapePercentEncoding(ref sourceIndex, buffer, isFormEncoding); - if (byte1 == -1) + if (byte1 < 0) { return false; } @@ -159,7 +159,7 @@ private static bool DecodeCore(ref int sourceIndex, ref int destinationIndex, Sp var nextSourceIndex = sourceIndex; var nextByte = UnescapePercentEncoding(ref nextSourceIndex, buffer, isFormEncoding); - if (nextByte == -1) + if (nextByte < 0) { return false; } @@ -269,13 +269,13 @@ private static int UnescapePercentEncoding(ref int scan, Span buffer, bool var probe = scan; var value1 = ReadHex(ref probe, buffer); - if (value1 == -1) + if (value1 < 0) { return -1; } var value2 = ReadHex(ref probe, buffer); - if (value2 == -1) + if (value2 < 0) { return -1; } @@ -380,7 +380,7 @@ public static int DecodeInPlace(Span buffer) // by using the first occurrence of % as the starting position both // for the source and the destination index. int position = buffer.IndexOf('%'); - if (position == -1) + if (position < 0) { return buffer.Length; } @@ -436,7 +436,7 @@ private static bool DecodeCore(ref int sourceIndex, ref int destinationIndex, Sp // preserves the original head. if the percent-encodings cannot be interpreted as sequence of UTF-8 octets, // chars from this till the last scanned one will be copied to the memory pointed by writer. var codeUnit1 = UnescapePercentEncoding(ref sourceIndex, buffer); - if (codeUnit1 == -1) + if (codeUnit1 < 0) { return false; } @@ -495,7 +495,7 @@ private static bool DecodeCore(ref int sourceIndex, ref int destinationIndex, Sp var nextSourceIndex = sourceIndex; var nextCodeUnit = UnescapePercentEncoding(ref nextSourceIndex, buffer); - if (nextCodeUnit == -1) + if (nextCodeUnit < 0) { return false; } diff --git a/src/SignalR/common/Shared/TextMessageParser.cs b/src/SignalR/common/Shared/TextMessageParser.cs index 5cd5b95a3101..b05d97d15bb1 100644 --- a/src/SignalR/common/Shared/TextMessageParser.cs +++ b/src/SignalR/common/Shared/TextMessageParser.cs @@ -16,7 +16,7 @@ public static bool TryParseMessage(ref ReadOnlySequence buffer, out ReadOn { var span = buffer.First.Span; var index = span.IndexOf(TextMessageFormatter.RecordSeparator); - if (index == -1) + if (index < 0) { payload = default; return false;