Improved Guid.ToUppercaseAsciiLetters() extension

This commit is contained in:
Sergio Pedri 2021-05-05 00:29:46 +02:00
Родитель 6961808ca7
Коммит 0c1fb1b179
1 изменённых файлов: 12 добавлений и 6 удалений

Просмотреть файл

@ -4,7 +4,6 @@
using System;
using System.Diagnostics.Contracts;
using System.Linq;
namespace Microsoft.Toolkit.Uwp.UI.Media
{
@ -19,12 +18,19 @@ namespace Microsoft.Toolkit.Uwp.UI.Media
/// <param name="guid">The input <see cref="Guid"/> to process</param>
/// <returns>A <see cref="string"/> representation of <paramref name="guid"/> only made up of letters in the [A-Z] range</returns>
[Pure]
public static string ToUppercaseAsciiLetters(this Guid guid)
public static string ToUppercaseAsciiLetters(in this Guid guid)
{
return new string((
from c in guid.ToString("N")
let l = char.IsDigit(c) ? (char)('G' + c - '0') : c
select l).ToArray());
// Composition IDs must only be composed of characters in the [A-Z0-9_] set,
// and also have the restriction that the initial character cannot be a digit.
// Because of this, we need to prepend an underscore to a serialized guid to
// avoid cases where the first character is a digit. Additionally, we're forced
// to use ToUpper() here because ToString("N") currently returns a lowercase
// hexadecimal string. Note: this extension might be improved once we move to
// .NET 5 in the WinUI 3 release, by using string.Create<TState>(...) to only
// have a single string allocation, and then using Guid.TryFormat(...) to
// serialize the guid in place over the Span<char> starting from the second
// character. For now, this implementation is fine on UWP and still fast enough.
return $"_{guid.ToString("N").ToUpper()}";
}
}
}