Skip to content

Commit

Permalink
PoParser PERF (#15943)
Browse files Browse the repository at this point in the history
  • Loading branch information
hishamco authored Aug 7, 2024
1 parent ecfd665 commit 62922e4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="ZString" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\OrchardCore.Localization.Abstractions\OrchardCore.Localization.Abstractions.csproj" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Cysharp.Text;

namespace OrchardCore.Localization.PortableObject
{
Expand All @@ -11,12 +13,17 @@ namespace OrchardCore.Localization.PortableObject
/// </summary>
public class PoParser
{
private static readonly Dictionary<char, char> _escapeTranslations = new()
private static readonly FrozenDictionary<char, char> _escapeTranslations;

static PoParser()
{
{ 'n', '\n' },
{ 'r', '\r' },
{ 't', '\t' },
};
_escapeTranslations = new Dictionary<char, char>()
{
{ 'n', '\n' },
{ 'r', '\r' },
{ 't', '\t' }
}.ToFrozenDictionary();
}

/// <summary>
/// Parses a .po file.
Expand Down Expand Up @@ -55,32 +62,30 @@ public IEnumerable<CultureDictionaryRecord> Parse(TextReader reader)

private static string Unescape(string str)
{
StringBuilder sb = null;
if (!str.Contains('\\'))
{
return str;
}

var escaped = false;
using var builder = ZString.CreateStringBuilder();

for (var i = 0; i < str.Length; i++)
{
var c = str[i];
if (escaped)
{
if (sb == null)
{
sb = new StringBuilder(str.Length);
if (i > 1)
{
sb.Append(str[..(i - 1)]);
}
}

char unescaped;
if (_escapeTranslations.TryGetValue(c, out unescaped))
{
sb.Append(unescaped);
builder.Append(unescaped);
}
else
{
// General rule: \x ==> x
sb.Append(c);
builder.Append(c);
}

escaped = false;
}
else
Expand All @@ -91,12 +96,12 @@ private static string Unescape(string str)
}
else
{
sb?.Append(c);
builder.Append(c);
}
}
}

return sb?.ToString() ?? str;
return builder.ToString();
}

private static string TrimQuote(string str)
Expand Down

0 comments on commit 62922e4

Please sign in to comment.