Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ public string GetScript()
commandName = this.ModuleName + "\\" + commandName;
}

if (commandName.IndexOf(' ') != -1)
if (commandName.Contains(' '))
{
builder.AppendFormat("& \"{0}\"", commandName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,21 +435,21 @@ private static bool Matches(WildcardPattern filterPattern, string commandName, s
/// <returns>Return match result.</returns>
private static bool MatchesEvenIfInPlural(string commandName, string filter)
{
if (commandName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1)
if (commandName.Contains(filter, StringComparison.OrdinalIgnoreCase))
{
return true;
}

if (filter.Length > 5 && filter.EndsWith("es", StringComparison.OrdinalIgnoreCase))
{
filter = filter.Substring(0, filter.Length - 2);
return commandName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1;
ReadOnlySpan<char> filterSpan = filter.AsSpan(0, filter.Length - 2);
return commandName.AsSpan().Contains(filterSpan, StringComparison.OrdinalIgnoreCase);
}

if (filter.Length > 4 && filter.EndsWith("s", StringComparison.OrdinalIgnoreCase))
{
filter = filter.Substring(0, filter.Length - 1);
return commandName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1;
ReadOnlySpan<char> filterSpan = filter.AsSpan(0, filter.Length - 1);
return commandName.AsSpan().Contains(filterSpan, StringComparison.OrdinalIgnoreCase);
}

return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,8 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot
return exceptionSafeReturn(delegate
{
int indexOfLastColon = cimIntrinsicValue.LastIndexOf(':');
int port = int.Parse(cimIntrinsicValue.Substring(indexOfLastColon + 1), NumberStyles.Integer, CultureInfo.InvariantCulture);
IPAddress address = IPAddress.Parse(cimIntrinsicValue.Substring(0, indexOfLastColon));
int port = int.Parse(cimIntrinsicValue.AsSpan(indexOfLastColon + 1), NumberStyles.Integer, CultureInfo.InvariantCulture);
IPAddress address = IPAddress.Parse(cimIntrinsicValue.AsSpan(0, indexOfLastColon));
return new IPEndPoint(address, port);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public string Culture
if (trimmedValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
if ((trimmedValue.Length > 2) &&
int.TryParse(trimmedValue.Substring(2), NumberStyles.AllowHexSpecifier,
int.TryParse(trimmedValue.AsSpan(2), NumberStyles.AllowHexSpecifier,
CultureInfo.CurrentCulture, out cultureNumber))
{
_cultureInfo = new CultureInfo(cultureNumber);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ private bool CanProcessRecordForOneCommand()

try
{
_commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1);
_commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.Contains('\\'));
_showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough);
}
catch (TargetInvocationException ti)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1865,8 +1865,11 @@ private char GetCharacterUnderCursor(Coordinates cursorPosition)
/// <returns>The string with any \0 characters removed...</returns>
private string RemoveNulls(string input)
{
if (input.IndexOf('\0') == -1)
if (input.Contains('\0'))
{
return input;
}

StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.WSMan.Management/ConfigProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4105,7 +4105,7 @@ private bool ItemExistListenerOrClientCertificate(object sessionobj, string Reso
PSObject obj = (PSObject)objcache[CurrentNode];

CurrentNode = RemainingPath.Substring(pos + 1);
if (CurrentNode.IndexOf(WSManStringLiterals.DefaultPathSeparator) != -1)
if (CurrentNode.Contains(WSManStringLiterals.DefaultPathSeparator))
{
// No more directories allowed after listeners objects
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ private string GenerateRow(string[] values, ReadOnlySpan<int> alignment, Display
}

sb.Append(GenerateRowField(values[k], _si.columnInfo[k].width, alignment[k], dc, addPadding));
if (values[k].IndexOf(ESC) != -1)
if (values[k].Contains(ESC))
{
// Reset the console output if the content of this column contains ESC
sb.Append(ResetConsoleVt100Code);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ internal static bool FindPartialMatch(string key, string normalizedKey)
if (key.Length < normalizedKey.Length)
{
// shorter, could be an abbreviation
if (string.Equals(key, normalizedKey.Substring(0, key.Length), StringComparison.OrdinalIgnoreCase))
if (key.AsSpan().Equals(normalizedKey.AsSpan(0, key.Length), StringComparison.OrdinalIgnoreCase))
{
// found abbreviation
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3173,7 +3173,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys
for (int i = 0; i < parameterName.Length; i++)
{
// try Upper case
if (char.IsUpper(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1))
if (char.IsUpper(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i]))
{
label.Insert(i, hotKeyPrefix);
usedHotKeys.Append(parameterName[i]);
Expand All @@ -3187,7 +3187,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys
// try Lower case
for (int i = 0; i < parameterName.Length; i++)
{
if (char.IsLower(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1))
if (char.IsLower(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i]))
{
label.Insert(i, hotKeyPrefix);
usedHotKeys.Append(parameterName[i]);
Expand All @@ -3202,7 +3202,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys
// try non-letters
for (int i = 0; i < parameterName.Length; i++)
{
if (!char.IsLetter(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1))
if (!char.IsLetter(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i]))
{
label.Insert(i, hotKeyPrefix);
usedHotKeys.Append(parameterName[i]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ internal static Type GetStructType(int args)
// See if we can find an existing type
foreach (Type t in s_generatedTypes)
{
int arity = int.Parse(t.Name.Substring("VariantArray".Length), CultureInfo.InvariantCulture);
int arity = int.Parse(t.Name.AsSpan("VariantArray".Length), NumberStyles.Integer, CultureInfo.InvariantCulture);
if (size == arity)
{
return t;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1514,19 +1514,18 @@ private List<CompletionResult> GetResultForString(CompletionContext completionCo
var analysis = new CompletionAnalysis(_ast, _tokens, _cursorPosition, _options);
var subContext = analysis.CreateCompletionContext(completionContext.TypeInferenceContext);

int subReplaceIndex, subReplaceLength;
var subResult = analysis.GetResultHelper(subContext, out subReplaceIndex, out subReplaceLength, true);
var subResult = analysis.GetResultHelper(subContext, out int subReplaceIndex, out _, true);

if (subResult != null && subResult.Count > 0)
{
result = new List<CompletionResult>();
replacementIndex = stringStartIndex + 1 + (cursorIndexInString - subInput.Length);
replacementLength = subInput.Length;
string prefix = subInput.Substring(0, subReplaceIndex);
ReadOnlySpan<char> prefix = subInput.AsSpan(0, subReplaceIndex);

foreach (CompletionResult entry in subResult)
{
string completionText = prefix + entry.CompletionText;
string completionText = string.Concat(prefix, entry.CompletionText.AsSpan());
if (entry.ResultType == CompletionResultType.Property)
{
completionText = TokenKind.DollarParen.Text() + completionText + TokenKind.RParen.Text();
Expand Down Expand Up @@ -1565,7 +1564,7 @@ private List<CompletionResult> GetResultForString(CompletionContext completionCo
result = new List<CompletionResult>(CompletionCompleters.CompleteFilename(completionContext));

// Try command name completion only if the text contains '-'
if (wordToComplete.IndexOf('-') != -1)
if (wordToComplete.Contains('-'))
{
var commandNameResult = CompletionCompleters.CompleteCommand(completionContext);
if (commandNameResult != null && commandNameResult.Count > 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1164,7 +1164,7 @@ internal static List<CompletionResult> CompleteCommandArgument(CompletionContext
var tryCmdletCompletion = false;
var clearLiteralPathsKey = TurnOnLiteralPathOption(context);

if (context.WordToComplete.IndexOf('-') != -1)
if (context.WordToComplete.Contains('-'))
{
tryCmdletCompletion = true;
}
Expand Down Expand Up @@ -1224,7 +1224,7 @@ internal static List<CompletionResult> CompleteCommandArgument(CompletionContext
}

// Handle member completion with wildcard: echo $a.*<tab>
if (pathAst.Value.IndexOf('*') != -1 && secondToLastMemberAst != null &&
if (pathAst.Value.Contains('*') && secondToLastMemberAst != null &&
secondToLastMemberAst.Extent.EndLineNumber == pathAst.Extent.StartLineNumber &&
secondToLastMemberAst.Extent.EndColumnNumber == pathAst.Extent.StartColumnNumber)
{
Expand Down Expand Up @@ -1328,7 +1328,7 @@ internal static List<CompletionResult> CompleteCommandArgument(CompletionContext
context.Options.Remove("LiteralPaths");
}

if (context.WordToComplete != string.Empty && context.WordToComplete.IndexOf('-') != -1)
if (context.WordToComplete != string.Empty && context.WordToComplete.Contains('-'))
{
var commandResults = CompleteCommand(context);
if (commandResults != null)
Expand Down Expand Up @@ -3844,7 +3844,7 @@ private static void NativeCompletionTypeName(CompletionContext context, List<Com
wordToComplete = wordToComplete.Substring(1, wordToComplete.Length - (endQuoted ? 2 : 1));
}

if (wordToComplete.IndexOf('[') != -1)
if (wordToComplete.Contains('['))
{
var cursor = (InternalScriptPosition)context.CursorPosition;
cursor = cursor.CloneWithNewOffset(cursor.Offset - context.TokenAtCursor.Extent.StartOffset - (isQuoted ? 1 : 0));
Expand Down Expand Up @@ -5632,7 +5632,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string
// If the completion included a namespace and ToStringCodeMethods.Type found
// an accelerator, then just use the type's FullName instead because the user
// probably didn't want the accelerator.
if (keyMatched.IndexOf('.') != -1 && completion.IndexOf('.') == -1)
if (keyMatched.Contains('.') && !completion.Contains('.'))
{
completion = Type.FullName;
}
Expand Down Expand Up @@ -6624,7 +6624,7 @@ internal static void CompleteMemberHelper(
}

string tooltip = memberInfo.ToString();
if (tooltip.IndexOf("),", StringComparison.Ordinal) != -1)
if (tooltip.Contains("),", StringComparison.Ordinal))
{
var overloads = tooltip.Split(new[] { ")," }, StringSplitOptions.RemoveEmptyEntries);
var newTooltip = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ private static void LogError(PSEventId eventId, params object[] args)
/// </summary>
internal static bool IsEngineFeatureName(string featureName)
{
return featureName.Length > 2 && featureName.IndexOf('.') == -1 && featureName.StartsWith("PS", StringComparison.Ordinal);
return featureName.Length > 2 && !featureName.Contains('.') && featureName.StartsWith("PS", StringComparison.Ordinal);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ private void AssertNameDoesNotResolveToAPath(string[] names, string stringFormat
{
foreach (var n in names)
{
if (n.IndexOf(StringLiterals.DefaultPathSeparator) != -1 || n.IndexOf(StringLiterals.AlternatePathSeparator) != -1)
if (n.Contains(StringLiterals.DefaultPathSeparator) || n.Contains(StringLiterals.AlternatePathSeparator))
{
string errorMessage = StringUtil.Format(stringFormat, n);
var argumentException = new ArgumentException(errorMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ internal List<PSModuleInfo> GetModule(string[] names, bool all, bool refresh)
{
foreach (var n in names)
{
if (n.IndexOf(StringLiterals.DefaultPathSeparator) != -1 || n.IndexOf(StringLiterals.AlternatePathSeparator) != -1)
if (n.Contains(StringLiterals.DefaultPathSeparator) || n.Contains(StringLiterals.AlternatePathSeparator))
{
modulePaths.Add(n);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ internal void BindParameters(Collection<CommandParameterInternal> parameters)

if (parameter.ParameterNameSpecified)
{
Diagnostics.Assert(parameter.ParameterText.IndexOf(' ') == -1, "Parameters cannot have whitespace");
Diagnostics.Assert(!parameter.ParameterText.Contains(' '), "Parameters cannot have whitespace");
PossiblyGlobArg(parameter.ParameterText, usedQuotes: false);

if (parameter.SpaceAfterParameter)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ internal static void AddArgumentsToCommandProcessor(CommandProcessorBase command
{
param = CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, paramText.Substring(1, colonIndex - 1), paramText,
/*argumentAst*/null, paramText.Substring(colonIndex + 1).Trim(),
/*argumentAst*/null, paramText.AsSpan(colonIndex + 1).Trim().ToString(),
Copy link
Member

Choose a reason for hiding this comment

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

ToString() here results in an allocation, can we just update that method to accept a readonlyspan?

Copy link
Collaborator Author

@iSazonov iSazonov Feb 20, 2020

Choose a reason for hiding this comment

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

No, it is used then in class ctor-s.

Copy link
Collaborator

Choose a reason for hiding this comment

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

ReadOnlySpan<char> typically is an implicit cast from string, isn't it?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@vexx32 No, only string -> ReadOnlySpan

Copy link
Collaborator

@vexx32 vexx32 Feb 21, 2020

Choose a reason for hiding this comment

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

Right, so if the method parameter is currently using string we should be able to change it to ReadOnlySpan<char> and have the implicit cast handle it, shouldn't we? Or am I missing some context here? 🙂

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I missing some context here

CreateParameterWithArgument() passes the string to a constructor so it makes no sense to convert to span here.

false);
}
else if (argIndex == arguments.Length - 1 || paramText[paramText.Length - 1] != ':')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ internal static string GetParameterTypeString(Type type, IEnumerable<Attribute>
}

// If the type is really an array, but the typename didn't include [], then add it.
if (type.IsArray && (parameterTypeString.IndexOf("[]", StringComparison.Ordinal) == -1))
if (type.IsArray && !parameterTypeString.Contains("[]", StringComparison.Ordinal))
{
var t = type;
while (t.IsArray)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ private bool CommandInfoMatches(CommandInfo commandInfo)
// If the breakpoint looks like it might have specified a module name and the command
// we're checking is in a module, try matching the module\command against the pattern
// in the breakpoint.
if (!string.IsNullOrEmpty(commandInfo.ModuleName) && Command.IndexOf('\\') != -1)
if (!string.IsNullOrEmpty(commandInfo.ModuleName) && Command.Contains('\\'))
{
if (CommandPattern.IsMatch(commandInfo.ModuleName + "\\" + commandInfo.Name))
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1247,7 +1247,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection<ChoiceDescription> ch
if (andPos + 1 < choices[i].Label.Length)
{
splitLabel.Append(choices[i].Label.Substring(andPos + 1));
hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.Substring(andPos + 1, 1).Trim());
hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.AsSpan(andPos + 1, 1).Trim().ToString());
}

hotkeysAndPlainLabels[1, i] = splitLabel.ToString().Trim();
Expand Down
4 changes: 2 additions & 2 deletions src/System.Management.Automation/engine/parser/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out
var parser = new Parser();
if (!string.IsNullOrEmpty(fileName) && fileName.Length > scriptSchemaExtension.Length && fileName.EndsWith(scriptSchemaExtension, StringComparison.OrdinalIgnoreCase))
{
parser._keywordModuleName = Path.GetFileName(fileName.Substring(0, fileName.Length - scriptSchemaExtension.Length));
parser._keywordModuleName = Path.GetFileName(fileName.AsSpan(0, fileName.Length - scriptSchemaExtension.Length)).ToString();
parseDscResource = true;
}

Expand Down Expand Up @@ -8107,7 +8107,7 @@ internal class ParserEventSource : EventSource

internal static string GetFileOrScript(string fileName, string input)
{
return fileName ?? input.Substring(0, Math.Min(256, input.Length)).Trim();
return fileName ?? input.AsSpan(0, Math.Min(256, input.Length)).Trim().ToString();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ internal static string VerboseMessage(IScriptExtent position)
: sourceLine.Length - position.StartColumnNumber + 1;

// Expand tabs before figuring out if we need to truncate the line
if (sourceLine.IndexOf('\t') != -1)
if (sourceLine.Contains('\t'))
{
var copyLine = new StringBuilder(sourceLine.Length * 2);

Expand Down
Loading