Skip to content

Commit 8a96550

Browse files
committed
Extract reordering logic
1 parent 9dc9e47 commit 8a96550

1 file changed

Lines changed: 13 additions & 40 deletions

File tree

DuckDB.NET.Data/Extensions/GuidConverter.cs

Lines changed: 13 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ internal static class GuidConverter
77
{
88
private const int GuidSize = 16;
99

10+
// First 4 bytes (little-endian), Next 4 bytes (little-endian), Last 8 bytes (big-endian)
11+
private static readonly int[] GuidByteOrder = [6, 7, 4, 5, 0, 1, 2, 3, 15, 14, 13, 12, 11, 10, 9, 8];
12+
1013
public static unsafe Guid ConvertToGuid(this DuckDBHugeInt input)
1114
{
1215
Span<byte> bytes = stackalloc byte[32];
@@ -29,28 +32,10 @@ public static unsafe Guid ConvertToGuid(this DuckDBHugeInt input)
2932
#endif
3033

3134
// Reconstruct the Guid bytes (reverse the original byte reordering)
32-
33-
// First 4 bytes (little-endian)
34-
bytes[6] = bytes[GuidSize + 0];
35-
bytes[7] = bytes[GuidSize + 1];
36-
bytes[4] = bytes[GuidSize + 2];
37-
bytes[5] = bytes[GuidSize + 3];
38-
39-
// Next 4 bytes (little-endian)
40-
bytes[0] = bytes[GuidSize + 4];
41-
bytes[1] = bytes[GuidSize + 5];
42-
bytes[2] = bytes[GuidSize + 6];
43-
bytes[3] = bytes[GuidSize + 7];
44-
45-
// Last 8 bytes (big-endian)
46-
bytes[15] = bytes[GuidSize + 8];
47-
bytes[14] = bytes[GuidSize + 9];
48-
bytes[13] = bytes[GuidSize + 10];
49-
bytes[12] = bytes[GuidSize + 11];
50-
bytes[11] = bytes[GuidSize + 12];
51-
bytes[10] = bytes[GuidSize + 13];
52-
bytes[9] = bytes[GuidSize + 14];
53-
bytes[8] = bytes[GuidSize + 15];
35+
for (int i = 0; i < GuidSize; i++)
36+
{
37+
bytes[GuidByteOrder[i]] = bytes[i + GuidSize];
38+
}
5439

5540
// Create Guid from the first 16 bytes
5641
#if NET6_0_OR_GREATER
@@ -72,24 +57,12 @@ public static DuckDBHugeInt ToHugeInt(this Guid guid)
7257
var byteArray = guid.ToByteArray();
7358
byteArray.AsSpan().CopyTo(bytes);
7459
#endif
75-
bytes[GuidSize + 0] = bytes[6]; // First 4 bytes (little-endian)
76-
bytes[GuidSize + 1] = bytes[7];
77-
bytes[GuidSize + 2] = bytes[4];
78-
bytes[GuidSize + 3] = bytes[5];
79-
80-
bytes[GuidSize + 4] = bytes[0]; // Next 4 bytes (little-endian)
81-
bytes[GuidSize + 5] = bytes[1];
82-
bytes[GuidSize + 6] = bytes[2];
83-
bytes[GuidSize + 7] = bytes[3];
84-
85-
bytes[GuidSize + 8] = bytes[15]; // Big endian
86-
bytes[GuidSize + 9] = bytes[14];
87-
bytes[GuidSize + 10] = bytes[13];
88-
bytes[GuidSize + 11] = bytes[12];
89-
bytes[GuidSize + 12] = bytes[11];
90-
bytes[GuidSize + 13] = bytes[10];
91-
bytes[GuidSize + 14] = bytes[9];
92-
bytes[GuidSize + 15] = bytes[8];
60+
61+
// Reconstruct the Guid bytes (reverse the original byte reordering)
62+
for (int i = 0; i < GuidSize; i++)
63+
{
64+
bytes[i + GuidSize] = bytes[GuidByteOrder[i]];
65+
}
9366

9467
#if NET6_0_OR_GREATER
9568
// Upper 64 bits (bytes 0-7)

0 commit comments

Comments
 (0)