Skip to content

Instantly share code, notes, and snippets.

@khellang
Created March 19, 2019 21:44
Show Gist options
  • Save khellang/c6f6f34c40cde22e992e2a4de9805af1 to your computer and use it in GitHub Desktop.
Save khellang/c6f6f34c40cde22e992e2a4de9805af1 to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace Hellang.CompactGuid
{
public static class Program
{
public static void Main()
{
var newGuid = Guid.NewGuid();
Console.WriteLine(newGuid.ToString());
Console.WriteLine(newGuid.ToCompactString());
}
}
public static class CompactGuid
{
private static readonly string EmptyString = new string('0', Length);
private const int Length = 26;
public static string ToCompactString(this Guid value)
{
if (value == Guid.Empty)
{
return EmptyString;
}
if (BitConverter.IsLittleEndian)
{
value = value.ToUuid();
}
return value.ToString();
}
private static Guid ToUuid(this Guid value)
{
if (Ssse3.IsSupported)
{
var vector = Unsafe.As<Guid, Vector128<byte>>(ref value);
var mask = Vector128.Create(434320308585955843L, 1084818905618843912L).AsByte();
var result = Ssse3.Shuffle(vector, mask);
return Unsafe.As<Vector128<byte>, Guid>(ref result);
}
throw new NotSupportedException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment