Last active
June 3, 2022 15:16
-
-
Save stevejgordon/485d08d8efc5a8f34a3f071a315a5815 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Buffers.Text; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
namespace EfficientGuids | |
{ | |
public static class GuidExtensions | |
{ | |
private const byte ForwardSlashByte = (byte)'/'; | |
private const byte DashByte = (byte)'-'; | |
private const byte PlusByte = (byte)'+'; | |
private const byte UnderscoreByte = (byte)'_'; | |
public static string EncodeBase64String(this Guid guid) | |
{ | |
Span<byte> guidBytes = stackalloc byte[16]; | |
Span<byte> encodedBytes = stackalloc byte[24]; | |
MemoryMarshal.TryWrite(guidBytes, ref guid); // write bytes from the Guid | |
Base64.EncodeToUtf8(guidBytes, encodedBytes, out _, out _); | |
// replace any characters which are not URL safe | |
for (var i = 0; i < 22; i++) | |
{ | |
if (encodedBytes[i] == ForwardSlashByte) | |
encodedBytes[i] = DashByte; | |
if (encodedBytes[i] == PlusByte) | |
encodedBytes[i] = UnderscoreByte; | |
} | |
// skip the last two bytes as these will be '==' padding | |
var final = Encoding.UTF8.GetString(encodedBytes.Slice(0, 22)); | |
return final; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @DoomerDGR8. This was purely a sample for a blog post so no further code is planned. It's not thoroughly tested or production ready.