Skip to content

Commit

Permalink
Avoid unnecessary allocations in SanitizeEntryFilePath
Browse files Browse the repository at this point in the history
On Windows, this method was allocating a StringBuilder, the underlying char[], and the resulting string, even if nothing needed to be changed.  We now only allocate anything if something needs to change, and if it does, we only allocate the string itself.
  • Loading branch information
stephentoub committed Jun 21, 2022
1 parent 1070187 commit c18e3d9
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions src/libraries/Common/src/System/IO/Archiving.Utils.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,38 @@ internal static partial class ArchivingUtils
{
internal static string SanitizeEntryFilePath(string entryPath)
{
StringBuilder builder = new StringBuilder(entryPath);
// Find the first illegal character in the entry path.
for (int i = 0; i < entryPath.Length; i++)
{
if (((int)builder[i] >= 0 && (int)builder[i] < 32) ||
builder[i] == '?' || builder[i] == ':' ||
builder[i] == '*' || builder[i] == '"' ||
builder[i] == '<' || builder[i] == '>' ||
builder[i] == '|')
switch (entryPath[i])
{
builder[i] = '_';
// We found at least one character that needs to be replaced.
case < (char)32 or '?' or ':' or '*' or '"' or '<' or '>' or '|':
return string.Create(entryPath.Length, (i, entryPath), (dest, state) =>
{
string entryPath = state.entryPath;

// Copy over to the new string everything until the character, then
// substitute for the found character.
entryPath.AsSpan(0, state.i).CopyTo(dest);
dest[state.i] = '_';

// Continue looking for and replacing any more illegal characters.
for (int i = state.i + 1; i < entryPath.Length; i++)
{
char c = entryPath[i];
dest[i] = c switch
{
< (char)32 or '?' or ':' or '*' or '"' or '<' or '>' or '|' => '_',
_ => c,
};
}
});
}
}
return builder.ToString();

// There weren't any characters to sanitize. Just return the original string.
return entryPath;
}
}
}

0 comments on commit c18e3d9

Please sign in to comment.