From 211b72d17ef7a0a97421baec269cc46447cb7a17 Mon Sep 17 00:00:00 2001 From: Maryam Ariyan Date: Fri, 24 Jul 2020 16:11:53 -0700 Subject: [PATCH] AnsiParser improvement (#39729) --- .../src/AnsiParser.cs | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs index 665093b408667..bf2ee5f99c901 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.Runtime.CompilerServices; namespace Microsoft.Extensions.Logging.Console { @@ -47,6 +48,7 @@ public void Parse(string message) { int startIndex = -1; int length = 0; + int escapeCode; ConsoleColor? foreground = null; ConsoleColor? background = null; var span = message.AsSpan(); @@ -59,12 +61,10 @@ public void Parse(string message) { if (span[i + 3] == 'm') { -#if NETCOREAPP - if (ushort.TryParse(span.Slice(i + 2, length: 1), out ushort escapeCode)) -#else - if (ushort.TryParse(span.Slice(i + 2, length: 1).ToString(), out ushort escapeCode)) -#endif + // Example: \x1B[1m + if (IsDigit(span[i + 2])) { + escapeCode = (int)(span[i + 2] - '0'); if (startIndex != -1) { _onParseWrite(message, startIndex, length, background, foreground); @@ -79,12 +79,10 @@ public void Parse(string message) } else if (span.Length >= i + 5 && span[i + 4] == 'm') { -#if NETCOREAPP - if (ushort.TryParse(span.Slice(i + 2, length: 2), out ushort escapeCode)) -#else - if (ushort.TryParse(span.Slice(i + 2, length: 2).ToString(), out ushort escapeCode)) -#endif + // Example: \x1B[40m + if (IsDigit(span[i + 2]) && IsDigit(span[i + 3])) { + escapeCode = (int)(span[i + 2] - '0') * 10 + (int)(span[i + 3] - '0'); if (startIndex != -1) { _onParseWrite(message, startIndex, length, background, foreground); @@ -128,6 +126,9 @@ public void Parse(string message) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsDigit(char c) => (uint)(c - '0') <= ('9' - '0'); + internal const string DefaultForegroundColor = "\x1B[39m\x1B[22m"; // reset to default foreground color internal const string DefaultBackgroundColor = "\x1B[49m"; // reset to the background color