Skip to content

Commit

Permalink
Merge pull request #11990 from Youssef1313/perf-android-regex
Browse files Browse the repository at this point in the history
perf: Avoid using Regex in AndroidResourceNameEncoder
  • Loading branch information
jeromelaban authored Apr 25, 2023
2 parents 06b3ffc + b15c12f commit 155cb5c
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/Uno.UWP/Helpers/AndroidResourceNameEncoder.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Uno
{
internal static class AndroidResourceNameEncoder
{
private const string NumberPrefix = "__";

// These characters are not supported on Android, but they're used by the attached property localization syntax.
// Example: "MyUid.[using:Windows.UI.Xaml.Automation]AutomationProperties.Name"
private static readonly Regex sanitizeName = new Regex(@"[^a-zA-Z0-9_.]", RegexOptions.Compiled);

/// <summary>
/// Encode a resource name to remove characters that are not supported on Android.
/// </summary>
/// <param name="key">The original resource name from the UWP Resources.resw file.</param>
/// <returns>The encoded resource name for the Android Strings.xml file.</returns>
public static string Encode(string key)
{
// Checks whether the key contains unsupported characters
key = sanitizeName.Replace(key, "_");
var charArray = key.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
// Checks whether the key contains unsupported characters
// These characters are not supported on Android, but they're used by the attached property localization syntax.
// Example: "MyUid.[using:Windows.UI.Xaml.Automation]AutomationProperties.Name"
if (charArray[i] is not ((>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or (>= '0' and <= '9') or '_' or '.'))
{
charArray[i] = '_';
}
}

key = new string(charArray);

//Checks if the keys are starting by a number because they are invalid in C#
if (int.TryParse(key.Substring(0, 1), out var number))
if (int.TryParse(key.Substring(0, 1), out _))
{
key = $"{NumberPrefix}{key}";
}
Expand Down

0 comments on commit 155cb5c

Please sign in to comment.