From 8f0543a1ac8312f232f004483e256b8b53594902 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 16 Jul 2024 19:44:13 +1000 Subject: [PATCH] shortcut FileNameCleaner.AppendValid for better perf (#1243) --- src/Verify/FileNameCleaner.cs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/Verify/FileNameCleaner.cs b/src/Verify/FileNameCleaner.cs index 433f4a1021..ca39f5fc7d 100644 --- a/src/Verify/FileNameCleaner.cs +++ b/src/Verify/FileNameCleaner.cs @@ -53,11 +53,7 @@ public static string ReplaceInvalidFileNameChars(this string value) { var span = value.AsSpan(); -#if NET8_0_OR_GREATER - var index = span.IndexOfAny(invalidFileNameSearchValues); -#else - var index = span.IndexOfAny(invalidFileNameChars.AsSpan()); -#endif + var index = IndexOfInvalidChar(span); if (index == -1) { @@ -80,6 +76,14 @@ public static string ReplaceInvalidFileNameChars(this string value) return new(chars); } + static int IndexOfInvalidChar(CharSpan span) => +#if NET8_0_OR_GREATER + span.IndexOfAny(invalidFileNameSearchValues); +#else + span.IndexOfAny(invalidFileNameChars.AsSpan()); +#endif + + static bool IsInvalid(char ch) => #if NET8_0_OR_GREATER invalidFileNameSearchValues.Contains(ch); @@ -89,6 +93,15 @@ static bool IsInvalid(char ch) => public static void AppendValid(StringBuilder builder, string value) { + var span = value.AsSpan(); + var index = IndexOfInvalidChar(span); + + if (index == -1) + { + builder.Append(value); + return; + } + foreach (var ch in value) { if (IsInvalid(ch))