45 lines
1.7 KiB
C#
45 lines
1.7 KiB
C#
namespace EnotaryoPH.Web.Common.Extensions
|
|
{
|
|
public static class StringExtensions
|
|
{
|
|
private const char EqualsChar = '=';
|
|
private const char Plus = '+';
|
|
private const char Slash = '/';
|
|
|
|
public static string DefaultIfEmpty(this string s, string defaultValue) => !string.IsNullOrWhiteSpace(s) ? s : defaultValue ?? string.Empty;
|
|
|
|
public static bool IsInList(this string s, params string[] list) => list.Contains(s, StringComparer.OrdinalIgnoreCase);
|
|
|
|
public static bool IsInList<T>(this string stringValue, IEnumerable<T> listOfEnums) where T : struct, Enum => Enum.TryParse(stringValue, out T enumValue) && listOfEnums.Contains(enumValue);
|
|
|
|
public static bool IsInList<T>(this string stringValue, params T[] listOfEnums) where T : struct, Enum => Enum.TryParse(stringValue, out T enumValue) && listOfEnums.Contains(enumValue);
|
|
|
|
public static string NullIfWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s) ? null : s;
|
|
|
|
public static Guid ToGuidFromBase64(this string s)
|
|
{
|
|
if (s.Length != 22)
|
|
{
|
|
return Guid.Empty;
|
|
}
|
|
|
|
var id = s.AsSpan();
|
|
Span<char> base64Chars = stackalloc char[24];
|
|
for (var i = 0; i < 22; i++)
|
|
{
|
|
base64Chars[i] = id[i] switch
|
|
{
|
|
'-' => Slash,
|
|
'_' => Plus,
|
|
_ => id[i]
|
|
};
|
|
}
|
|
base64Chars[22] = EqualsChar;
|
|
base64Chars[23] = EqualsChar;
|
|
|
|
Span<byte> idBytes = stackalloc byte[16];
|
|
Convert.TryFromBase64Chars(base64Chars, idBytes, out _);
|
|
return new Guid(idBytes);
|
|
}
|
|
}
|
|
} |