From fc98e4eb655d7ed7f05297b79e03a53615d5a4f9 Mon Sep 17 00:00:00 2001 From: jojo aquino Date: Thu, 2 Jan 2025 20:53:26 +0000 Subject: [PATCH] class extensions --- .../Common/Extensions/GuidExtensions.cs | 23 -------------- .../Common/Extensions/StringExtensions.cs | 30 +++++++++++++++++++ 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/GuidExtensions.cs b/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/GuidExtensions.cs index 7e1832d..3ec3daa 100644 --- a/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/GuidExtensions.cs +++ b/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/GuidExtensions.cs @@ -6,11 +6,8 @@ namespace EnotaryoPH.Web.Common.Extensions public static class GuidExtensions { private const char Dash = '-'; - private const char EqualsChar = '='; private const byte ForwardSlashByte = (byte)'/'; - private const char Plus = '+'; private const byte PlusByte = (byte)'+'; - private const char Slash = '/'; private const char Underscore = '_'; public static string ToBase64String(this Guid guid) @@ -39,25 +36,5 @@ namespace EnotaryoPH.Web.Common.Extensions return final; } - - public static Guid ToGuidFromString(ReadOnlySpan id) - { - Span 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 idBytes = stackalloc byte[16]; - Convert.TryFromBase64Chars(base64Chars, idBytes, out _); - return new Guid(idBytes); - } } } \ No newline at end of file diff --git a/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/StringExtensions.cs b/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/StringExtensions.cs index f9879e8..344c0fd 100644 --- a/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/StringExtensions.cs +++ b/EnotaryoPH/EnotaryoPH.Web/Common/Extensions/StringExtensions.cs @@ -2,8 +2,38 @@ { 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 string NullIfWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s) ? null : s; + + public static Guid ToGuidFromString(this string s) + { + if (s.Length != 22) + { + return Guid.Empty; + } + + var id = s.AsSpan(); + Span 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 idBytes = stackalloc byte[16]; + Convert.TryFromBase64Chars(base64Chars, idBytes, out _); + return new Guid(idBytes); + } } } \ No newline at end of file