Skip to content

Commit

Permalink
Simplify NtProcessInfoHelper.GetProcessShortName (#71136)
Browse files Browse the repository at this point in the history
The previous code was iterating character by character through the name, looking for the last occurrence of a slash and the last occurrence of a period.  For the slash, we can just LasIndexOfAny.  For the period, it was only doing this in order to trim off ".exe" if a period was found and the text at that point was ".exe"... so we can just compare the end with ".exe".
  • Loading branch information
stephentoub authored Jun 22, 2022
1 parent bc1a872 commit 9d3f060
Showing 1 changed file with 8 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -412,59 +412,18 @@ private static unsafe ProcessInfo[] GetProcessInfos(ReadOnlySpan<byte> data, int
// Check base\screg\winreg\perfdlls\process\perfsprc.c for details.
internal static ReadOnlySpan<char> GetProcessShortName(ReadOnlySpan<char> name)
{
if (name.IsEmpty)
{
return string.Empty;
}

int slash = -1;
int period = -1;

for (int i = 0; i < name.Length; i++)
{
if (name[i] == '\\')
{
slash = i;
}
else if (name[i] == '.')
{
period = i;
}
}

if (period == -1)
{
period = name.Length - 1; // set to end of string
}
else
{
// if a period was found, then see if the extension is
// .EXE, if so drop it, if not, then use end of string
// (i.e. include extension in name)
ReadOnlySpan<char> extension = name.Slice(period);
// Trim off everything up to and including the last slash, if there is one.
// If there isn't, LastIndexOf will return -1 and this will end up as a nop.
name = name.Slice(name.LastIndexOf('\\') + 1);

if (extension.Equals(".exe", StringComparison.OrdinalIgnoreCase))
{
period--; // point to character before period
}
else
{
period = name.Length - 1; // set to end of string
}
}

if (slash == -1)
{
slash = 0; // set to start of string
}
else
// If the name ends with the ".exe" extension, then drop it, otherwise include
// it in the name.
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
slash++; // point to character next to slash
name = name.Slice(0, name.Length - 4);
}

// Slice to the characters between a slash (or start of the string)
// and a period (or end of string).
return name.Slice(slash, period - slash + 1);
return name;
}
}
}

0 comments on commit 9d3f060

Please sign in to comment.