diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index f4e7ee1ecd6..17d729c52ea 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -53,6 +53,10 @@ public sealed class WildcardPattern // char that escapes special chars private const char escapeChar = '`'; + // Threshold for stack allocation. + // The size is less than MaxShortPath = 260. + private const int StackAllocThreshold = 256; + // we convert a wildcard pattern to a predicate private Predicate _isMatch; @@ -203,15 +207,20 @@ internal static string Escape(string pattern, char[] charsNotToEscape) { if (pattern == null) { - throw PSTraceSource.NewArgumentNullException("pattern"); + throw PSTraceSource.NewArgumentNullException(nameof(pattern)); } if (charsNotToEscape == null) { - throw PSTraceSource.NewArgumentNullException("charsNotToEscape"); + throw PSTraceSource.NewArgumentNullException(nameof(charsNotToEscape)); + } + + if (pattern == string.Empty) + { + return pattern; } - char[] temp = new char[pattern.Length * 2 + 1]; + Span temp = pattern.Length < StackAllocThreshold ? stackalloc char[pattern.Length * 2 + 1] : new char[pattern.Length * 2 + 1]; int tempIndex = 0; for (int i = 0; i < pattern.Length; i++) @@ -231,13 +240,13 @@ internal static string Escape(string pattern, char[] charsNotToEscape) string s = null; - if (tempIndex > 0) + if (tempIndex == pattern.Length) { - s = new string(temp, 0, tempIndex); + s = pattern; } else { - s = string.Empty; + s = new string(temp.Slice(0, tempIndex)); } return s; @@ -312,10 +321,16 @@ public static string Unescape(string pattern) { if (pattern == null) { - throw PSTraceSource.NewArgumentNullException("pattern"); + throw PSTraceSource.NewArgumentNullException(nameof(pattern)); } - char[] temp = new char[pattern.Length]; + if (pattern == string.Empty) + { + return pattern; + } + + Span temp = pattern.Length < StackAllocThreshold ? stackalloc char[pattern.Length] : new char[pattern.Length]; + int tempIndex = 0; bool prevCharWasEscapeChar = false; @@ -361,13 +376,13 @@ public static string Unescape(string pattern) string s = null; - if (tempIndex > 0) + if (tempIndex == pattern.Length) { - s = new string(temp, 0, tempIndex); + s = pattern; } else { - s = string.Empty; + s = new string(temp.Slice(0, tempIndex)); } return s;