Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/Ulid.Tests/Ulid.Guid.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,45 @@ public void FromAndToGuid_ShouldPreserveValue()
Assert.Equal(ulid, ulidFromGuid); // Ensure the ULID matches after conversion
}

[Fact]
public void ToGuid_ShouldKeepTheByteOrderOfTheStringRepresentation()
{
// Arrange
// The canonical text of a GUID lists its bytes in the same order as the bytes of a ULID,
// whereas the in-memory layout of a Guid stores its first three fields in little-endian order.
byte[] ulidBytes = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff];
var expected = new Guid("00112233-4455-6677-8899-aabbccddeeff");
var ulid = Ulid.New(ulidBytes);

// Act & Assert
Assert.Equal(expected, ulid.ToGuid());
Assert.Equal(expected, (Guid)ulid);
Assert.Equal(ulid, Ulid.New(expected));
Assert.Equal(ulidBytes, Ulid.New(expected).ToByteArray());
}

[Fact]
public void FromAndToGuid_RandomValues_ShouldMatchTheGuidByteOrder()
{
// Arrange
var random = new Random(4711);
var bytes = new byte[16];

for (var i = 0; i < 10_000; i++)
{
random.NextBytes(bytes);

// Act
var ulid = Ulid.New(bytes);
var guid = ulid.ToGuid();

// Assert
Assert.Equal(ulid.ToString(), Ulid.New(guid).ToString());
Assert.Equal(guid.ToString("N"), Convert.ToHexString(bytes).ToLowerInvariant());
Assert.Equal(ulid, Ulid.New(guid));
}
}

[Fact]
public void FromAndToGuid_ImplicitConversion_ShouldPreserveValue()
{
Expand Down
20 changes: 16 additions & 4 deletions src/Ulid/Ulid.Guid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using System.Runtime.CompilerServices;
#if NETCOREAPP
using System.Runtime.Intrinsics;
#if !NET7_0_OR_GREATER
#if !NET10_0_OR_GREATER
using System.Runtime.Intrinsics.X86;
#endif
#endif
Expand Down Expand Up @@ -63,14 +63,15 @@ private static Vector128<byte> _shuffleMask
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static TOut Shuffle<TIn, TOut>(ref TIn bytes)
{
#if NET7_0_OR_GREATER
#if NET10_0_OR_GREATER
if (Vector128.IsHardwareAccelerated)
{
var vector = Unsafe.As<TIn, Vector128<byte>>(ref bytes);
vector = Vector128.Shuffle(vector, _shuffleMask);
return Unsafe.As<Vector128<byte>, TOut>(ref vector);
}
#elif NETCOREAPP3_0_OR_GREATER
// Vector128.Shuffle is not expanded to a single instruction before .NET 10
if (Ssse3.IsSupported)
{
var vector = Unsafe.As<TIn, Vector128<byte>>(ref bytes);
Expand All @@ -93,8 +94,19 @@ private static TOut Shuffle<TIn, TOut>(ref TIn bytes)
Unsafe.SkipInit(out TOut result);
ref var dst = ref Unsafe.As<TOut, byte>(ref result);

Unsafe.WriteUnaligned(ref dst, lower);
Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, 4), upper);
if (typeof(TOut) == typeof(Ulid))
{
// A Ulid is read back as a whole. When its first 8 bytes are written in smaller pieces, the CPU cannot
// forward the stores to that wider load and stalls. The shuffle only runs on little-endian systems.
Unsafe.WriteUnaligned(ref dst, lower | ((ulong)upper << 32));
}
else
{
// A Guid is made of separate fields, which are written and read back one by one
Unsafe.WriteUnaligned(ref dst, lower);
Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, 4), upper);
}

Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, 8), Unsafe.ReadUnaligned<ulong>(ref Unsafe.Add(ref src, 8)));

return result;
Expand Down
12 changes: 6 additions & 6 deletions src/Ulid/Ulid.New.GenerationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,9 @@ protected GenerationOptions(GenerationOptions original)
CurrentState = new();
}

// Separates Lock and LastUlid into different cache lines to prevent "false sharing"
// x64 has 64-byte cache lines; ARM64 (e.g., Apple Silicon) has 128-byte cache lines
// The leading and trailing padding keep neighboring heap objects off those cache lines.
// Keeps the lock and the last ULID on one cache line, as they are always used together, while the leading
// and trailing padding keep neighboring heap objects off that cache line to prevent "false sharing".
// x64 has 64-byte cache lines; ARM64 (e.g., Apple Silicon) has 128-byte cache lines.
[StructLayout(LayoutKind.Explicit)]
internal class State
{
Expand All @@ -198,11 +198,11 @@ internal class State

// The last generated ULID as two numeric (not byte order) halves, so that increments need no byte swaps
#pragma warning disable CS0649 // Field is never assigned to, and will always have its default value
[FieldOffset(_cacheLineSize * 2)] public ulong LastUlidPart0;
[FieldOffset(_cacheLineSize * 2 + 8)] public ulong LastUlidPart1;
[FieldOffset(_cacheLineSize + 8)] public ulong LastUlidPart0;
[FieldOffset(_cacheLineSize + 16)] public ulong LastUlidPart1;

#pragma warning disable CS0169 // Padding field is never used
[FieldOffset(_cacheLineSize * 3 + 8)] private readonly ulong _trailingPadding;
[FieldOffset(_cacheLineSize * 2 + 16)] private readonly ulong _trailingPadding;
#pragma warning restore CS0169
#pragma warning restore CS0649 // Field is never assigned to, and will always have its default value

Expand Down
Loading