Skip to content

Commit

Permalink
AnsiParser improvement (dotnet#39729)
Browse files Browse the repository at this point in the history
  • Loading branch information
maryamariyan authored and Jacksondr5 committed Aug 10, 2020
1 parent 402e551 commit 211b72d
Showing 1 changed file with 11 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.IO;
using System.Runtime.CompilerServices;

namespace Microsoft.Extensions.Logging.Console
{
Expand Down Expand Up @@ -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();
Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 211b72d

Please sign in to comment.