Created
July 5, 2024 07:49
-
-
Save jrgcubano/6984cc81cf4ca4dc36cc3517bbbd8e81 to your computer and use it in GitHub Desktop.
Combine two guids in one using Xor with SIMD operations
This file contains hidden or 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
void Main() | |
{ | |
var providerId = Guid.Parse("6dac0000-17be-e460-ad92-08dc8fb0aee8").Dump("ProviderId"); // NewId.Next().ToGuid().Dump(); | |
var parkingSessionId = Guid.Parse("ec000000-5d59-0015-eafd-08dc9b3476c8").Dump("ParkingSession Id"); // NewId.Next().ToGuid().Dump(); | |
// var secondId = Guid.Parse("ec000000-5d59-0015-c615-08dc9b3578ff").Dump("Second Id"); // NewId.NextGuid().Dump(); | |
//var result = new List<(int index, Guid id, Guid combined)>(); | |
// | |
//for (var i = 0; i <= 10; i++) | |
//{ | |
// var id = NewId.NextGuid(); | |
// | |
// result.Add((index: i, id: id, combined: providerId.Xor(id).Dump($"ProviderId Xor Id '{id}'"))); | |
//} | |
providerId.Xor(parkingSessionId).Dump("ProviderId Xor ParkingSessionId"); | |
// result.Add(providerId.Xor(secondId).Dump("ProviderId Xor SecondId")); | |
// var ordered = result.OrderBy(x => x.combined).Dump(); | |
/// result = firstId.CombineGuids(secondId).Dump(); | |
} | |
public static class Extensions | |
{ | |
// https://stackoverflow.com/questions/1383030/how-to-combine-two-guid-values | |
public static Guid Xor(this Guid a, Guid b) | |
{ | |
if (Sse2.IsSupported) | |
{ | |
var result = Sse2.Xor(Unsafe.As<Guid, Vector128<long>>(ref a), Unsafe.As<Guid, Vector128<long>>(ref b)); | |
return Unsafe.As<Vector128<long>, Guid>(ref result); | |
} | |
var spanA = MemoryMarshal.CreateSpan(ref Unsafe.As<Guid, long>(ref a), 2); | |
var spanB = MemoryMarshal.CreateSpan(ref Unsafe.As<Guid, long>(ref b), 2); | |
spanB[0] ^= spanA[0]; | |
spanB[1] ^= spanA[1]; | |
return b; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment