-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFastGuid.Database.cs
More file actions
179 lines (149 loc) · 8.59 KB
/
FastGuid.Database.cs
File metadata and controls
179 lines (149 loc) · 8.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
using System;
using System.Buffers.Binary;
using System.Numerics;
using System.Runtime.CompilerServices;
namespace SecurityDriven
{
public static partial class FastGuid
{
// Copyright (c) 2025 Stan Drapkin
// LICENSE: https://github.com/sdrapkin/SecurityDriven.FastGuid
/// <summary>
/// Returns a new Guid optimized for use as a SQL Server clustered key.
/// Guid structure is [8 random bytes][8 bytes of SQL Server ordered DateTime.UtcNow].
/// Each Guid should be sequential within 100-nanosecond UtcNow precision limits.
/// 64-bit cryptographic randomness adds uniqueness for timestamp collisions and provides reasonable unguessability and protection against online brute-force attacks.
/// </summary>
/// <returns>Guid for SQL-Server clustered key.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Guid NewSqlServerGuid() => NewSqlServerGuid(DateTime.UtcNow);
/// <summary>
/// Returns a new Guid optimized for use as a SQL Server clustered key.
/// Guid structure is [8 random bytes][8 bytes of SQL Server ordered timestampUtc].
/// 64-bit cryptographic randomness adds uniqueness for timestamp collisions and provides reasonable unguessability and protection against online brute-force attacks.
/// </summary>
/// <param name="timestampUtc">UTC timestamp.</param>
/// <returns>Guid for SQL-Server clustered key.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Guid NewSqlServerGuid(DateTime timestampUtc)
{
Guid guid = FastGuid.NewGuid();
// based on Microsoft SqlGuid.cs
// https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/System.Data/System/Data/SQLTypes/SQLGuid.cs
ref var guidStruct = ref Unsafe.As<Guid, (long, ulong)>(ref guid);
ref var ticksStruct = ref Unsafe.As<DateTime, ulong>(ref timestampUtc);
guidStruct.Item2 = BinaryPrimitives.ReverseEndianness(BitOperations.RotateRight(ticksStruct, 16));
return guid;
}//NewSqlServerGuid(DateTime)
/// <summary>
/// Returns a new Guid optimized for use as a PostgreSQL index key.
/// Guid structure is [8 bytes of PostgreSQL-ordered timestampUtc][8 random bytes].
/// Each Guid should be sequential within 100-nanosecond UtcNow precision limits.
/// 64-bit cryptographic randomness adds uniqueness for timestamp collisions and provides reasonable unguessability and protection against online brute-force attacks.
/// Designed for <see href="https://www.npgsql.org">Npgsql</see>, which auto-converts to big-endian wire format, resulting in correct PG::uuid value.
/// Explicit <see href="https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-7">UUID-v7-like</see> big-endian byte conversion of returned Guid should use
/// .ToByteArray(bigEndian:true) or .TryWriteBytes(destinationSpan, bigEndian:true).
/// </summary>
/// <returns>Guid for PostgreSQL index key.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Guid NewPostgreSqlGuid() => NewPostgreSqlGuid(DateTime.UtcNow);
/// <summary>
/// Returns a new Guid optimized for use as a PostgreSQL index key.
/// Guid structure is [8 bytes of PostgreSQL-ordered timestampUtc][8 random bytes].
/// 64-bit cryptographic randomness adds uniqueness for timestamp collisions and provides reasonable unguessability and protection against online brute-force attacks.
/// Designed for <see href="https://www.npgsql.org">Npgsql</see>, which auto-converts to big-endian wire format, resulting in correct PG::uuid value.
/// Explicit <see href="https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-7">UUID-v7-like</see> big-endian byte conversion of returned Guid should use
/// .ToByteArray(bigEndian:true) or .TryWriteBytes(destinationSpan, bigEndian:true).
/// </summary>
/// <param name="timestampUtc">UTC timestamp.</param>
/// <returns>Guid for PostgreSQL index key.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Guid NewPostgreSqlGuid(DateTime timestampUtc)
{
Guid guid = FastGuid.NewGuid();
// PostgreSQL compares UUIDs as byte arrays, using memcmp
// https://doxygen.postgresql.org/uuid_8c.html#aae2aef5e86c79c563f02a5cee13d1708
ref var guidStruct = ref Unsafe.As<Guid, (int, short, short)>(ref guid);
ref var ticksStruct = ref Unsafe.As<DateTime, (int, int)>(ref timestampUtc);
ref var shortStruct = ref Unsafe.As<int, (short, short)>(ref ticksStruct.Item1);
guidStruct.Item1 = ticksStruct.Item2;
guidStruct.Item2 = shortStruct.Item2;
guidStruct.Item3 = shortStruct.Item1;
return guid;
}//NewPostgreSqlGuid()
static readonly Guid AllBitsSet = new Guid(uint.MaxValue, ushort.MaxValue, ushort.MaxValue,
byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
#region SqlServer
/// <summary>Helper methods for Guids generated by <see cref="NewSqlServerGuid()"/>.</summary>
public static class SqlServer
{
/// <summary>Extracts SqlServer Guid creation timestamp (UTC). Full <see cref="DateTime.UtcNow"/> precision.</summary>
/// <param name="guid">Guid generated by <see cref="NewSqlServerGuid()"/>.</param>
/// <returns>SqlServer Guid creation timestamp.</returns>
public static DateTime GetTimestamp(Guid guid)
{
ref var guidStruct = ref Unsafe.As<Guid, (long, ulong)>(ref guid);
var ulongStruct = BinaryPrimitives.ReverseEndianness(BitOperations.RotateRight(guidStruct.Item2, 16));
return Unsafe.As<ulong, DateTime>(ref ulongStruct);
}// GetTimestamp()
/// <summary>Returns the *smallest* Guid for a given timestamp (useful for time-based database range searches).</summary>
public static Guid MinGuidForTimestamp(DateTime timestampUtc)
{
Guid guid = default;
ref var guidStruct = ref Unsafe.As<Guid, (long, ulong)>(ref guid);
ref var ticksStruct = ref Unsafe.As<DateTime, ulong>(ref timestampUtc);
guidStruct.Item2 = BinaryPrimitives.ReverseEndianness(BitOperations.RotateRight(ticksStruct, 16));
return guid;
}// MinGuidForTimestamp()
/// <summary>Returns the *largest* Guid for a given timestamp (useful for time-based database range searches).</summary>
public static Guid MaxGuidForTimestamp(DateTime timestampUtc)
{
Guid guid = AllBitsSet;
ref var guidStruct = ref Unsafe.As<Guid, (long, ulong)>(ref guid);
ref var ticksStruct = ref Unsafe.As<DateTime, ulong>(ref timestampUtc);
guidStruct.Item2 = BinaryPrimitives.ReverseEndianness(BitOperations.RotateRight(ticksStruct, 16));
return guid;
}// MaxGuidForTimestamp()
}// static class SqlServer
#endregion
#region PostgreSql
/// <summary>Helper methods for Guids generated by <see cref="NewPostgreSqlGuid()"/>.</summary>
public static class PostgreSql
{
/// <summary>Extracts PostgreSql Guid creation timestamp (UTC). Full <see cref="DateTime.UtcNow"/> precision.</summary>
/// <param name="guid">Guid generated by <see cref="NewPostgreSqlGuid()"/>.</param>
/// <returns>PostgreSql Guid creation timestamp.</returns>
public static DateTime GetTimestamp(Guid guid)
{
ref var guidTimestamp = ref Unsafe.As<Guid, (uint, ushort, ushort)>(ref guid);
ulong ticksStruct = ((ulong)guidTimestamp.Item1 << 32) | ((uint)guidTimestamp.Item2 << 16) | guidTimestamp.Item3;
return Unsafe.As<ulong, DateTime>(ref ticksStruct);
}// GetTimestamp()
/// <summary>Returns the *smallest* Guid for a given timestamp (useful for time-based database range searches).</summary>
public static Guid MinGuidForTimestamp(DateTime timestampUtc)
{
Guid guid = default;
ref var guidStruct = ref Unsafe.As<Guid, (int, short, short)>(ref guid);
ref var ticksStruct = ref Unsafe.As<DateTime, (int, int)>(ref timestampUtc);
ref var shortStruct = ref Unsafe.As<int, (short, short)>(ref ticksStruct.Item1);
guidStruct.Item1 = ticksStruct.Item2;
guidStruct.Item2 = shortStruct.Item2;
guidStruct.Item3 = shortStruct.Item1;
return guid;
}// MinGuidForTimestamp()
/// <summary>Returns the *largest* Guid for a given timestamp (useful for time-based database range searches).</summary>
public static Guid MaxGuidForTimestamp(DateTime timestampUtc)
{
Guid guid = AllBitsSet;
ref var guidStruct = ref Unsafe.As<Guid, (int, short, short)>(ref guid);
ref var ticksStruct = ref Unsafe.As<DateTime, (int, int)>(ref timestampUtc);
ref var shortStruct = ref Unsafe.As<int, (short, short)>(ref ticksStruct.Item1);
guidStruct.Item1 = ticksStruct.Item2;
guidStruct.Item2 = shortStruct.Item2;
guidStruct.Item3 = shortStruct.Item1;
return guid;
}// MaxGuidForTimestamp()
}// static class PostgreSql
#endregion
}//class FastGuid
}//ns