Skip to content

Commit

Permalink
Clean up improper usage of linguistic string functions (dotnet#31968)
Browse files Browse the repository at this point in the history
- Optimize ToUpperInvariant/ToLowerInvariant
- Also optimize static field TextInfo.Invariant
- Rewrite ToUpper/Lower(Invariant) call sites to use optimized method
- Fix some uses of culture-aware ToUpper / ToLower to use invariant culture
- Replace Trim().Length with IsNullOrWhiteSpace where appropriate
- Use ordinal StartsWith / EndsWith where appropriate
- Avoid calling CultureInfo.InvariantCulture where possible
  • Loading branch information
GrabYourPitchforks authored Feb 13, 2020
1 parent 35a59c1 commit 036fb07
Show file tree
Hide file tree
Showing 94 changed files with 168 additions and 163 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ internal static bool TryFindHierarchyMount(string mountInfoFilePath, string subs
// the end of the optional values.

const string Separator = " - ";
int endOfOptionalFields = line.IndexOf(Separator);
int endOfOptionalFields = line.IndexOf(Separator, StringComparison.Ordinal);
if (endOfOptionalFields == -1)
{
// Malformed line.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private static string GetKeyName(StringBuilder buffer)
{
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture);
return buffer.ToString(0, count).ToLowerInvariant();
}

private static string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
Expand Down Expand Up @@ -445,7 +445,7 @@ private static Dictionary<string, string> SplitConnectionString(string connectio
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach (Capture keypair in match.Groups[KeyIndex].Captures)
{
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture);
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant();
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length)
{
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/Common/src/System/Drawing/ColorTranslator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ public static Color FromHtml(string htmlColor)
InitializeHtmlSysColorTable();
}

s_htmlSysColorTable!.TryGetValue(htmlColor.ToLower(CultureInfo.InvariantCulture), out c);
s_htmlSysColorTable!.TryGetValue(htmlColor.ToLowerInvariant(), out c);
}

// resort to type converter which will handle named colors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public static long ParseRoundTripTime(string pingOutput)
{
int timeIndex = pingOutput.IndexOf("time=", StringComparison.Ordinal);
int afterTime = timeIndex + "time=".Length;
int msIndex = pingOutput.IndexOf("ms", afterTime);
int msIndex = pingOutput.IndexOf("ms", afterTime, StringComparison.Ordinal);
int numLength = msIndex - afterTime - 1;
string timeSubstring = pingOutput.Substring(afterTime, numLength);
double parsedRtt = double.Parse(timeSubstring, CultureInfo.InvariantCulture);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ Namespace Microsoft.VisualBasic.CompilerServices
WidthChanged = False

If Length = 0 Then Return
Input = Input.ToLower(System.Globalization.CultureInfo.InvariantCulture)
Input = Input.ToLowerInvariant()

Dim ExtraChars As Integer

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Namespace Microsoft.VisualBasic
End Sub

Public Sub ChDrive(ByVal Drive As Char)
Drive = System.Char.ToUpper(Drive, CultureInfo.InvariantCulture)
Drive = System.Char.ToUpperInvariant(Drive)

If (Drive < chLetterA) OrElse (Drive > chLetterZ) Then
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Drive"))
Expand Down Expand Up @@ -110,7 +110,7 @@ Namespace Microsoft.VisualBasic
Debug.Assert(Not System.Reflection.Assembly.GetCallingAssembly() Is Utils.VBRuntimeAssembly,
"Methods in Microsoft.VisualBasic should not call FileSystem public method.")

Drive = System.Char.ToUpper(Drive, CultureInfo.InvariantCulture)
Drive = System.Char.ToUpperInvariant(Drive)
If (Drive < chLetterA OrElse Drive > chLetterZ) Then
Throw VbMakeException(New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Drive")), vbErrors.DevUnavailable)
End If
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ private void GenerateFile(List<string> typeNames, string assemblyName, bool prox
//However when a path ending with backslash, if followed by double quote, it becomes an escapte sequence
//e.g. "obj\Debug\netcoreapp2.0\", it will be converted as obj\Debug\netcoreapp2.0", which is not valid and not exist
//We need remove the ending quote for this situation
if (!outputDirectory.EndsWith("\"") || !Directory.Exists(outputDirectory = outputDirectory.Remove(outputDirectory.Length - 1)))
if (!outputDirectory.EndsWith("\"", StringComparison.Ordinal) || !Directory.Exists(outputDirectory = outputDirectory.Remove(outputDirectory.Length - 1)))
{
throw new ArgumentException(SR.Format(SR.ErrDirectoryNotExists, outputDirectory));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2703,7 +2703,7 @@ private string GetBaseTypeOutput(CodeTypeReference typeRef, bool preferBuiltInTy
return "void";
}

string lowerCaseString = s.ToLower(CultureInfo.InvariantCulture).Trim();
string lowerCaseString = s.ToLowerInvariant().Trim();

switch (lowerCaseString)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private static bool Contains(string[] array, string value, bool ignoreCase)
{
if (ignoreCase)
{
searchChar = char.ToLower(value[pos], CultureInfo.InvariantCulture);
searchChar = char.ToLowerInvariant(value[pos]);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public override bool IsValid(object value)
}

// only check string length if empty strings are not allowed
return AllowEmptyStrings || !(value is string stringValue) || stringValue.Trim().Length != 0;
return AllowEmptyStrings || !(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly)

if (s != null)
{
DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this);
DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpperInvariant(), this);
break;
}
}
Expand Down Expand Up @@ -140,7 +140,7 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly)
}
if (s != null)
{
DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this);
DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpperInvariant(), this);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ public static bool CheckPath(string value)
if (value == null)
return false;

value = value.Trim();
value = value.TrimStart();
if (value.Equals(string.Empty))
return false;

// Path names should start with "\\"
return value.StartsWith("\\\\");
return value.StartsWith("\\\\", StringComparison.Ordinal);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ private static string FormatClosedGeneric(Type closedGenericType)
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}

var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf("`"));
var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`'));
var args = closedGenericType.GenericTypeArguments.Select(t => Format(t));
return string.Format("{0}<{1}>", name, string.Join(", ", args));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private static string FormatClosedGeneric(Type closedGenericType)
{
Debug.Assert(closedGenericType != null);
Debug.Assert(closedGenericType.IsConstructedGenericType);
var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf("`"));
var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`'));
IEnumerable<string> args = closedGenericType.GenericTypeArguments.Select(t => Format(t));
return string.Format("{0}<{1}>", name, string.Join(SR.Formatter_ListSeparatorWithSpace, args));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ private ClientConfigPaths(string exePath, bool includeUserConfig)
if (string.IsNullOrEmpty(namePrefix))
namePrefix = Validate(ProductName, limitSize: true);
string applicationUriLower = !string.IsNullOrEmpty(ApplicationUri)
? ApplicationUri.ToLower(CultureInfo.InvariantCulture)
? ApplicationUri.ToLowerInvariant()
: null;
string hashSuffix = GetTypeAndHashSuffix(applicationUriLower);
string part2 = !string.IsNullOrEmpty(namePrefix) && !string.IsNullOrEmpty(hashSuffix)
Expand Down Expand Up @@ -272,7 +272,7 @@ private void SetNamesAndVersion(string applicationFilename, Assembly exeAssembly
// Try the remainder of the namespace
if (ns != null)
{
int lastDot = ns.LastIndexOf(".", StringComparison.Ordinal);
int lastDot = ns.LastIndexOf('.');
if ((lastDot != -1) && (lastDot < ns.Length - 1)) ProductName = ns.Substring(lastDot + 1);
else ProductName = ns;

Expand All @@ -291,7 +291,7 @@ private void SetNamesAndVersion(string applicationFilename, Assembly exeAssembly
// Try the first part of the namespace
if (ns != null)
{
int firstDot = ns.IndexOf(".", StringComparison.Ordinal);
int firstDot = ns.IndexOf('.');
_companyName = firstDot != -1 ? ns.Substring(0, firstDot) : ns;

_companyName = _companyName.Trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1138,7 +1138,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ
((_itemLockedFlag & ConfigurationValueFlags.XmlParentInherited) == 0))
{
dataToWrite = true;
writer?.WriteAttributeString(LockItemKey, true.ToString().ToLower(CultureInfo.InvariantCulture));
writer?.WriteAttributeString(LockItemKey, true.ToString().ToLowerInvariant());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,9 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string s = value as string;
if (s != null)
if (value is string s)
{
s = s.ToLower(CultureInfo.InvariantCulture);
switch (s)
switch (s.ToLowerInvariant())
{
case "all":
return UriIdnScope.All;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -788,7 +788,7 @@ internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray)
string columnName = columnNameArray[i];
if ((null != columnName) && (0 < columnName.Length))
{
columnName = columnName.ToLower(CultureInfo.InvariantCulture);
columnName = columnName.ToLowerInvariant();
int index;
if (hash.TryGetValue(columnName, out index))
{
Expand All @@ -814,7 +814,7 @@ internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray)
}
else
{
columnName = columnName.ToLower(CultureInfo.InvariantCulture);
columnName = columnName.ToLowerInvariant();
if (i != hash[columnName])
{
GenerateUniqueName(hash, ref columnNameArray[i], i, 1);
Expand All @@ -828,7 +828,7 @@ private static int GenerateUniqueName(Dictionary<string, int> hash, ref string c
for (; ; ++uniqueIndex)
{
string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture);
string lowerName = uniqueName.ToLowerInvariant();
if (hash.TryAdd(lowerName, index))
{
columnName = uniqueName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ internal string ExpandKeyword(string keyword, string replacementValue)
[Conditional("DEBUG")]
static partial void DebugTraceKeyValuePair(string keyname, string keyvalue, Dictionary<string, string> synonyms)
{
Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower");
Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower");

string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname))
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Data.Common/src/System/Data/DataTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3711,9 +3711,9 @@ internal IndexField[] ParseSortString(string sortString)
}

// handle brackets.
if (current.StartsWith("[", StringComparison.Ordinal))
if (current.StartsWith('['))
{
if (current.EndsWith("]", StringComparison.Ordinal))
if (current.EndsWith(']'))
{
current = current.Substring(1, current.Length - 2);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,7 @@ internal DataColumn FindField(DataTable table, string field)
bool attribute = false;
string colName = field;

if (field.StartsWith("@", StringComparison.Ordinal))
if (field.StartsWith('@'))
{
attribute = true;
colName = field.Substring(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,7 @@ internal void Open_ChangeDatabase(string value)
CheckState(ADP.ChangeDatabase);

// Database name must not be null, empty or whitspace
if ((null == value) || (0 == value.Trim().Length))
if (string.IsNullOrWhiteSpace(value))
{ // MDAC 62679
throw ADP.EmptyDatabaseName();
}
Expand Down
6 changes: 3 additions & 3 deletions src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ internal string ExpandDataDirectories(ref string filename, ref int position)
[System.Diagnostics.Conditional("DEBUG")]
private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms)
{
Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower");
Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower");

string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname))
Expand All @@ -505,7 +505,7 @@ private static string GetKeyName(StringBuilder buffer)
{
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture);
return buffer.ToString(0, count).ToLowerInvariant();
}

private static string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
Expand Down Expand Up @@ -795,7 +795,7 @@ private static Hashtable SplitConnectionString(string connectionString, Hashtabl
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach (Capture keypair in match.Groups[KeyIndex].Captures)
{
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture);
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant();
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length)
{
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect
value = dataRow[backendtype, DataRowVersion.Default];
if (value is string)
{
string backendtypename = ((string)value).ToLower(CultureInfo.InvariantCulture);
string backendtypename = ((string)value).ToLowerInvariant();
switch (backendtypename)
{
case "binary":
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.OleDb/src/OleDbConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ internal int QuotedIdentifierCase()
public override void ChangeDatabase(string value)
{
CheckStateOpen(ADP.ChangeDatabase);
if ((null == value) || (0 == value.Trim().Length))
if (string.IsNullOrWhiteSpace(value))
{
throw ADP.EmptyDatabaseName();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ private static void ValidateProvider(string progid)
{
throw ODB.InvalidProviderSpecified();
}
progid = progid.ToLower(CultureInfo.InvariantCulture);
progid = progid.ToLowerInvariant();
if (IsMSDASQL(progid))
{
// fail msdasql even if not on the machine.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex
if (DBSOURCETYPE_DATASOURCE_TDP == sourceType || DBSOURCETYPE_DATASOURCE_MDP == sourceType)
{
string progid = (string)row[column2];
if (!OleDbConnectionString.IsMSDASQL(progid.ToLower(CultureInfo.InvariantCulture)))
if (!OleDbConnectionString.IsMSDASQL(progid.ToLowerInvariant()))
{
if (0 > providerNames.IndexOf(progid))
{
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Data.OleDb/src/OleDbDataReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1927,7 +1927,7 @@ private int IndexOf(Hashtable hash, string name)
}

// via case insensitive search, first match with lowest ordinal matches
string tmp = name.ToLower(CultureInfo.InvariantCulture);
string tmp = name.ToLowerInvariant();
index = hash[tmp]; // match via lowercase
return ((null != index) ? (int)index : -1);
}
Expand Down Expand Up @@ -2027,7 +2027,7 @@ private void AppendSchemaInfo()
string basecolumname = _metadata[i].baseColumnName;
if (!ADP.IsEmpty(basecolumname))
{
basecolumname = basecolumname.ToLower(CultureInfo.InvariantCulture);
basecolumname = basecolumname.ToLowerInvariant();
if (!baseColumnNames.Contains(basecolumname))
{
baseColumnNames[basecolumname] = i;
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ internal Dictionary<string, OleDbPropertyInfo> GetValues()
propertyInfo._vtype = propinfo.vtType;
propertyInfo._supportedValues = propinfo.vValue;
propertyInfo._description = propinfo.pwszDescription;
propertyInfo._lowercase = propinfo.pwszDescription.ToLower(CultureInfo.InvariantCulture);
propertyInfo._lowercase = propinfo.pwszDescription.ToLowerInvariant();
propertyInfo._type = PropertyInfoSet.FromVtType(propinfo.vtType);

propertyLookup[propertyInfo._lowercase] = propertyInfo;
Expand Down
Loading

0 comments on commit 036fb07

Please sign in to comment.