Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/coreclr/tools/Common/TypeSystem/IL/ILDisassembler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public string GetNextInstruction()
// Quick and dirty way to get the opcode name is to convert the enum value to string.
// We need some adjustments though.
string opCodeString = opCode.ToString().Replace("_", ".");
if (opCodeString.EndsWith("."))
if (opCodeString.EndsWith('.'))
opCodeString = opCodeString.Substring(0, opCodeString.Length - 1);

decodedInstruction.Append(opCodeString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)

// Entry point name
string entryPointName = _pInvokeMethodData.EntryPointName;
if (factory.Target.IsWindows && entryPointName.StartsWith("#", StringComparison.OrdinalIgnoreCase))
if (factory.Target.IsWindows && entryPointName.StartsWith('#'))
{
// Windows-specific ordinal import
// CLR-compatible behavior: Strings that can't be parsed as a signed integer are treated as zero.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<AssemblyName>ILCompiler.Compiler</AssemblyName>
<TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>$(NoWarn);CA1866;CA1867</NoWarn>
<NoWarn>$(NoWarn);CA1866</NoWarn>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<Platforms>x64;x86</Platforms>
<PlatformTarget>AnyCPU</PlatformTarget>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
<AssemblyName>ILCompiler.TypeSystem</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework>
<NoWarn>$(NoWarn);CA1866</NoWarn>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<Platforms>x64;x86</Platforms>
<PlatformTarget>AnyCPU</PlatformTarget>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ internal static bool TryFindHierarchyMount(CGroupVersion cgroupVersion, string m
{
if (cgroupVersion == CGroupVersion.CGroup1)
{
bool validCGroup1Entry = mount.FileSystemType.SequenceEqual("cgroup") && mount.SuperOptions.IndexOf(subsystem) >= 0;
bool validCGroup1Entry = mount.FileSystemType.SequenceEqual("cgroup") && mount.SuperOptions.Contains(subsystem, StringComparison.Ordinal);
if (!validCGroup1Entry)
{
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ internal static unsafe bool IsMemberOfGroup(uint gid)
if (rv >= 0)
{
// success
return groups.Slice(0, rv).IndexOf(gid) >= 0;
return groups.Slice(0, rv).Contains(gid);
}
else if (rv == -1 && Interop.Sys.GetLastError() == Interop.Error.EINVAL)
{
Expand Down
6 changes: 1 addition & 5 deletions src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,7 @@ private void Initialize(string? typeName, CodeTypeReferenceOptions options)
}

// Now see if we have some arity. baseType could be null if this is an array type.
#if NET
if (_baseType != null && _baseType.Contains('`')) // string.Contains(char) is .NetCore2.1+ specific
#else
if (_baseType != null && _baseType.IndexOf('`') != -1) // string.Contains(char) is .NetCore2.1+ specific
#endif
if (_baseType != null && _baseType.Contains('`'))
{
_needsFixup = false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,11 @@ internal static int GetKeyValuePair(string connectionString, int currentPosition
return currentPosition;
}

#pragma warning disable CA2249 // Consider using 'string.Contains' instead of 'string.IndexOf'. This file is built into libraries that don't have string.Contains(char).
private static bool IsValueValidInternal(string? keyvalue)
{
if (null != keyvalue)
{
return (-1 == keyvalue.IndexOf('\u0000')); // string.Contains(char) is .NetCore2.1+ specific
return !keyvalue.Contains('\u0000');
}
return true;
}
Expand All @@ -412,14 +411,12 @@ private static bool IsKeyNameValid([NotNullWhen(true)] string? keyname)
{
#if DEBUG
bool compValue = ConnectionStringValidKeyRegex.IsMatch(keyname);
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !char.IsWhiteSpace(keyname[0]) && !keyname.Contains('\u0000')) == compValue, "IsValueValid mismatch with regex");
#endif
// string.Contains(char) is .NetCore2.1+ specific
return ((0 < keyname.Length) && (';' != keyname[0]) && !char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
return ((0 < keyname.Length) && (';' != keyname[0]) && !char.IsWhiteSpace(keyname[0]) && !keyname.Contains('\u0000'));
}
return false;
}
#pragma warning restore CA2249 // Consider using 'string.Contains' instead of 'string.IndexOf'

#if DEBUG
private static Dictionary<string, string> SplitConnectionString(string connectionString, Dictionary<string, string>? synonyms, bool firstKey)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ internal static string GetLatestBuildDllDirectory(string machineName)
string majorVersion = majorVersions[i];

// If this looks like a key of the form v{something}.{something}, we should see if it's a usable build.
if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains(".")) // string.Contains(char) is .NetCore2.1+ specific
if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains('.'))
{
int[] currentVersion = new int[] { -1, -1, -1 };

Expand Down
3 changes: 3 additions & 0 deletions src/libraries/Common/src/System/MemoryExtensionsPolyfills.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ namespace System
/// <summary>Provides downlevel polyfills for span extension methods.</summary>
internal static class MemoryExtensionsPolyfills
{
public static bool Contains<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> =>
span.IndexOf(value) >= 0;

public static bool ContainsAnyExcept(this ReadOnlySpan<char> span, char value)
{
for (int i = 0; i < span.Length; i++)
Expand Down
18 changes: 18 additions & 0 deletions src/libraries/Common/src/System/StringPolyfills.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System
{
/// <summary>Provides downlevel polyfills for string extension methods.</summary>
internal static class StringPolyfills
{
public static bool StartsWith(this string s, char value) =>
s.Length > 0 && s[0] == value;

public static bool EndsWith(this string s, char value) =>
s.Length > 0 && s[s.Length - 1] == value;

public static bool Contains(this string s, char value) =>
s.IndexOf(value) >= 0;

Check failure on line 16 in src/libraries/Common/src/System/StringPolyfills.cs

View check run for this annotation

Azure Pipelines / runtime-dev-innerloop (Build linux-x64 debug Libraries_WithPackages)

src/libraries/Common/src/System/StringPolyfills.cs#L16

src/libraries/Common/src/System/StringPolyfills.cs(16,13): error CA2249: (NETCORE_ENGINEERING_TELEMETRY=Build) Use 'string.Contains' instead of 'string.IndexOf' to improve readability (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2249)

Check failure on line 16 in src/libraries/Common/src/System/StringPolyfills.cs

View check run for this annotation

Azure Pipelines / runtime-dev-innerloop

src/libraries/Common/src/System/StringPolyfills.cs#L16

src/libraries/Common/src/System/StringPolyfills.cs(16,13): error CA2249: (NETCORE_ENGINEERING_TELEMETRY=Build) Use 'string.Contains' instead of 'string.IndexOf' to improve readability (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2249)
}
}
1 change: 1 addition & 0 deletions src/libraries/Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@
<ItemGroup Condition="'$(IncludeSpanPolyfills)' == 'true' and
'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
<Compile Include="$(LibrariesProjectRoot)\Common\src\System\MemoryExtensionsPolyfills.cs" Link="System\MemoryExtensionsPolyfills.cs" />
<Compile Include="$(LibrariesProjectRoot)\Common\src\System\StringPolyfills.cs" Link="System\StringPolyfills.cs" />
<Compile Include="$(LibrariesProjectRoot)\Common\src\System\Buffers\SearchValuesPolyfills.cs" Link="System\Buffers\SearchValuesPolyfills.cs" />
<Compile Include="$(LibrariesProjectRoot)\Common\src\System\Text\AsciiPolyfills.cs" Link="System\Text\AsciiPolyfills.cs" />
<Compile Include="$(LibrariesProjectRoot)\Common\src\System\Text\EncodingPolyfills.cs" Link="System\Text\EncodingPolyfills.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ public override void Load()
{
keyStartIndex = 2;
}
else if (currentArg.StartsWith("-"))
else if (currentArg.StartsWith('-'))
{
keyStartIndex = 1;
}
else if (currentArg.StartsWith("/"))
else if (currentArg.StartsWith('/'))
{
// "/SomeSwitch" is equivalent to "--SomeSwitch" when interpreting switch mappings
// So we do a conversion to simplify later processing
Expand Down Expand Up @@ -141,7 +141,7 @@ private static Dictionary<string, string> GetValidatedSwitchMappingsCopy(IDictio
foreach (KeyValuePair<string, string> mapping in switchMappings)
{
// Only keys start with "--" or "-" are acceptable
if (!mapping.Key.StartsWith("-") && !mapping.Key.StartsWith("--"))
if (!mapping.Key.StartsWith('-'))
{
throw new ArgumentException(
SR.Format(SR.Error_InvalidSwitchMapping, mapping.Key),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<NoWarn>$(NoWarn);CA1866</NoWarn>
<EnableDefaultItems>true</EnableDefaultItems>
<IsPackable>true</IsPackable>
<PackageDescription>Command line configuration provider implementation for Microsoft.Extensions.Configuration. This package enables you to read configuration parameters from the command line arguments of your application. You can use CommandLineConfigurationExtensions.AddCommandLine extension method on IConfigurationBuilder to add the command line configuration provider to the configuration builder.</PackageDescription>
</PropertyGroup>

<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
<Compile Include="$(LibrariesProjectRoot)\Common\src\System\StringPolyfills.cs" Link="System\StringPolyfills.cs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration\src\Microsoft.Extensions.Configuration.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.Abstractions\src\Microsoft.Extensions.Configuration.Abstractions.csproj" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static bool IsExcluded(FileSystemInfo fileSystemInfo, ExclusionFilters fi
{
return false;
}
else if (fileSystemInfo.Name.StartsWith(".", StringComparison.Ordinal) && (filters & ExclusionFilters.DotPrefixed) != 0)
else if (fileSystemInfo.Name.StartsWith('.') && (filters & ExclusionFilters.DotPrefixed) != 0)
{
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<RootNamespace>Microsoft.Extensions.FileProviders</RootNamespace>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>$(NoWarn);CA1865;CA1866</NoWarn>
<EnableDefaultItems>true</EnableDefaultItems>
<IsPackable>true</IsPackable>
<PackageDescription>File provider for physical files for Microsoft.Extensions.FileProviders.</PackageDescription>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,24 +153,10 @@ private IChangeToken GetOrAddChangeToken(string pattern)
LazyInitializer.EnsureInitialized(ref _timer, ref _timerInitialized, ref _timerLock, _timerFactory);
}

IChangeToken changeToken;
#if NET
bool isWildCard = pattern.Contains('*');
#else
bool isWildCard = pattern.IndexOf('*') != -1;
#endif
if (isWildCard || IsDirectoryPath(pattern))
{
changeToken = GetOrAddWildcardChangeToken(pattern);
}
else
{
return pattern.Contains('*') || IsDirectoryPath(pattern)
? GetOrAddWildcardChangeToken(pattern)
// get rid of \. in Windows and ./ in UNIX's at the start of path file
var filePath = RemoveRelativePathSegment(pattern);
changeToken = GetOrAddFilePathChangeToken(filePath);
}

return changeToken;
: GetOrAddFilePathChangeToken(RemoveRelativePathSegment(pattern));
}

private static string RemoveRelativePathSegment(string pattern) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DefineConstants>$(DefineConstants);REGISTRY_ASSEMBLY</DefineConstants>
<NoWarn>$(NoWarn);CA2249</NoWarn>
<UseCompilerGeneratedDocXmlFile>false</UseCompilerGeneratedDocXmlFile>
</PropertyGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,8 @@ private string QuoteSnippetString(string value)
// If the string is short, use C style quoting (e.g "\r\n")
// Also do it if it is too long to fit in one line
// If the string contains '\0', verbatim style won't work.
#pragma warning disable CA2249 // Consider using 'string.Contains' instead of 'string.IndexOf'
if (value.Length < 256 || value.Length > 1500 || (value.IndexOf('\0') != -1)) // string.Contains(char) is .NetCore2.1+ specific
if (value.Length < 256 || value.Length > 1500 || value.Contains('\0'))
return QuoteSnippetStringCStyle(value);
#pragma warning restore CA2249

// Otherwise, use 'verbatim' style quoting (e.g. @"foo")
return QuoteSnippetStringVerbatimStyle(value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -862,11 +862,7 @@ protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression
string typeName = GetTypeOutput(e.CreateType);
Output.Write(typeName);

#if NET
if (!typeName.Contains('('))
#else
if (typeName.IndexOf('(') == -1)
#endif
{
Output.Write("()");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<NoWarn>$(NoWarn);CA2249</NoWarn>
<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>
<UseCompilerGeneratedDocXmlFile>false</UseCompilerGeneratedDocXmlFile>
<IsPackable>true</IsPackable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3078,7 +3078,7 @@ internal static string NormalizeLocationSubPath(string subPath, IConfigErrorInfo
throw new ConfigurationErrorsException(SR.Config_location_path_invalid_first_character, errorInfo);

// do not allow problematic starting characters
if (InvalidFirstSubPathCharacters.IndexOf(subPath[0]) != -1)
if (InvalidFirstSubPathCharacters.Contains(subPath[0]))
throw new ConfigurationErrorsException(SR.Config_location_path_invalid_first_character, errorInfo);

// do not allow whitespace at end of subPath, as the OS
Expand All @@ -3088,7 +3088,7 @@ internal static string NormalizeLocationSubPath(string subPath, IConfigErrorInfo
throw new ConfigurationErrorsException(SR.Config_location_path_invalid_last_character, errorInfo);

// the file system ignores trailing '.', '\', or '/', so do not allow it in a location subpath specification
if (InvalidLastSubPathCharacters.IndexOf(subPath[subPath.Length - 1]) != -1)
if (InvalidLastSubPathCharacters.Contains(subPath[subPath.Length - 1]))
throw new ConfigurationErrorsException(SR.Config_location_path_invalid_last_character, errorInfo);

// combination of URI reserved characters and OS invalid filename characters, minus / (allowed reserved character)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,7 @@ internal ConfigurationProperty(PropertyInfo info)

if (collectionAttribute != null)
{
#if NET
if (!collectionAttribute.AddItemName.Contains(','))
#else
if (collectionAttribute.AddItemName.IndexOf(',') == -1)
#endif
{
AddElementName = collectionAttribute.AddItemName;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,7 @@ public ConfigurationSection Get(string name)
throw ExceptionUtil.ParameterNullOrEmpty(nameof(name));

// prevent GetConfig from returning config not in this collection
#if NET
if (name.Contains('/'))
#else
if (name.IndexOf('/') >= 0)
#endif
return null;

// get the section from the config record
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,7 @@ public ConfigurationSectionGroup Get(string name)
throw ExceptionUtil.ParameterNullOrEmpty(nameof(name));

// prevent GetConfig from returning config not in this collection
#if NET
if (name.Contains('/'))
#else
if (name.IndexOf('/') >= 0)
#endif
return null;

// get the section group
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ private void ThrowIfReadOnly()

private static void ThrowIfContainsDelimiter(string value)
{
if (value.Contains(",")) // string.Contains(char) is .NetCore2.1+ specific
if (value.Contains(','))
throw new ConfigurationErrorsException(SR.Format(SR.Config_base_value_cannot_contain, ","));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;

namespace System.Configuration
{
public class StringValidator : ConfigurationValidatorBase
{
private readonly string _invalidChars;
private readonly SearchValues<char> _invalidChars;
private readonly int _maxLength;
private readonly int _minLength;

Expand All @@ -21,7 +23,7 @@ public StringValidator(int minLength, int maxLength, string invalidCharacters)
{
_minLength = minLength;
_maxLength = maxLength;
_invalidChars = invalidCharacters;
_invalidChars = SearchValues.Create(invalidCharacters ?? string.Empty);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How frequently are these StringValidators created?

}

public override bool CanValidate(Type type)
Expand All @@ -42,14 +44,9 @@ public override void Validate(object value)
throw new ArgumentException(SR.Format(SR.Validator_string_max_length, _maxLength));

// Check if the string contains any invalid characters
if ((len > 0) && !string.IsNullOrEmpty(_invalidChars))
if (data.AsSpan().ContainsAny(_invalidChars))
{
char[] array = new char[_invalidChars.Length];

_invalidChars.CopyTo(0, array, 0, _invalidChars.Length);

if (data.IndexOfAny(array) != -1)
throw new ArgumentException(SR.Format(SR.Validator_string_invalid_chars, _invalidChars));
throw new ArgumentException(SR.Format(SR.Validator_string_invalid_chars, _invalidChars));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private static Type GetImplicitType(string typeString)

// Don't bother to look around if we've already got something that
// is clearly not a simple type name.
if (string.IsNullOrEmpty(typeString) || typeString.IndexOf(',') != -1) // string.Contains(char) is .NetCore2.1+ specific
if (string.IsNullOrEmpty(typeString) || typeString.Contains(','))
return null;

// Ignore all exceptions, otherwise callers will get unexpected
Expand Down
Loading
Loading