Skip to content

Commit

Permalink
reduce alloc in ReplaceInvalidFileNameChars (#1244)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp authored Jul 16, 2024
1 parent 8f0543a commit 9f2f1c5
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions src/Verify/FileNameCleaner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,20 @@ public static string ReplaceInvalidFileNameChars(this string value)
return value;
}

var chars = value.ToCharArray();
span[..index]
.CopyTo(chars);
chars[index] = '-';
Span<char> target = stackalloc char[value.Length];
span.CopyTo(target);

target[index] = '-';
index++;
for (; index < chars.Length; index++)
for (; index < target.Length; index++)
{
if (IsInvalid(chars[index]))
if (IsInvalid(target[index]))
{
chars[index] = '-';
target[index] = '-';
}
}

return new(chars);
return target.ToString();
}

static int IndexOfInvalidChar(CharSpan span) =>
Expand All @@ -83,7 +83,6 @@ static int IndexOfInvalidChar(CharSpan span) =>
span.IndexOfAny(invalidFileNameChars.AsSpan());
#endif


static bool IsInvalid(char ch) =>
#if NET8_0_OR_GREATER
invalidFileNameSearchValues.Contains(ch);
Expand Down

0 comments on commit 9f2f1c5

Please sign in to comment.