Skip to content

Instantly share code, notes, and snippets.

@stevejgordon
Last active June 3, 2022 15:16
Show Gist options
  • Save stevejgordon/485d08d8efc5a8f34a3f071a315a5815 to your computer and use it in GitHub Desktop.
Save stevejgordon/485d08d8efc5a8f34a3f071a315a5815 to your computer and use it in GitHub Desktop.
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;
}
}
}
@DoomerDGR8
Copy link

Is the DecodeBase64String function planned?

@stevejgordon
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment