Skip to content

Commit

Permalink
EncodeCore and AppendSpanFormattable
Browse files Browse the repository at this point in the history
  • Loading branch information
TrayanZapryanov committed Jun 4, 2024
1 parent eed1378 commit 583bab4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
Link="Common\System\HexConverter.cs" />
<Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs"
Link="Common\System\Text\ValueStringBuilder.cs" />
<Compile Include="$(CommonPath)System\Text\ValueStringBuilder.AppendSpanFormattable.cs"
Link="Common\System\Text\ValueStringBuilder.AppendSpanFormattable.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,56 +141,63 @@ internal static string JavaScriptStringEncode(string? value, bool addDoubleQuote
return addDoubleQuotes ? $"\"{value}\"" : value;
}

var vsb = new ValueStringBuilder(stackalloc char[512]);
if (addDoubleQuotes)
{
vsb.Append('"');
}
ReadOnlySpan<char> chars = value;
do
return EncodeCore(value, i, addDoubleQuotes);

static string EncodeCore(ReadOnlySpan<char> value, int i, bool addDoubleQuotes)
{
vsb.Append(chars.Slice(0, i));
char c = chars[i];
chars = chars.Slice(i + 1);
switch (c)
var vsb = new ValueStringBuilder(stackalloc char[512]);
if (addDoubleQuotes)
{
case '\r':
vsb.Append("\\r");
break;
case '\t':
vsb.Append("\\t");
break;
case '\"':
vsb.Append("\\\"");
break;
case '\\':
vsb.Append("\\\\");
break;
case '\n':
vsb.Append("\\n");
break;
case '\b':
vsb.Append("\\b");
break;
case '\f':
vsb.Append("\\f");
break;
default:
vsb.Append($"\\u{(int)c:x4}");
break;
vsb.Append('"');
}

i = chars.IndexOfAny(s_invalidJavaScriptChars);
} while (i >= 0);
ReadOnlySpan<char> chars = value;
do
{
vsb.Append(chars.Slice(0, i));
char c = chars[i];
chars = chars.Slice(i + 1);
switch (c)
{
case '\r':
vsb.Append("\\r");
break;
case '\t':
vsb.Append("\\t");
break;
case '\"':
vsb.Append("\\\"");
break;
case '\\':
vsb.Append("\\\\");
break;
case '\n':
vsb.Append("\\n");
break;
case '\b':
vsb.Append("\\b");
break;
case '\f':
vsb.Append("\\f");
break;
default:
vsb.Append("\\u");
vsb.AppendSpanFormattable((int)c, "x4");
break;
}

vsb.Append(chars);
i = chars.IndexOfAny(s_invalidJavaScriptChars);
} while (i >= 0);

if (addDoubleQuotes)
{
vsb.Append('"');
}
vsb.Append(chars);

return vsb.ToString();
if (addDoubleQuotes)
{
vsb.Append('"');
}

return vsb.ToString();
}
}

[return: NotNullIfNotNull(nameof(bytes))]
Expand Down

0 comments on commit 583bab4

Please sign in to comment.