-
Notifications
You must be signed in to change notification settings - Fork 930
/
GuidCombGenerator.cs
72 lines (62 loc) · 2.38 KB
/
GuidCombGenerator.cs
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
using System;
using NHibernate.Engine;
namespace NHibernate.Id
{
/// <summary>
/// An <see cref="IIdentifierGenerator" /> that generates <see cref="System.Guid"/> values
/// using a strategy suggested Jimmy Nilsson's
/// <a href="http://www.informit.com/articles/article.asp?p=25862">article</a>
/// on <a href="http://www.informit.com">informit.com</a>.
/// </summary>
/// <remarks>
/// <p>
/// This id generation strategy is specified in the mapping file as
/// <code><generator class="guid.comb" /></code>
/// </p>
/// <p>
/// The <c>comb</c> algorithm is designed to make the use of GUIDs as Primary Keys, Foreign Keys,
/// and Indexes nearly as efficient as ints.
/// </p>
/// <p>
/// This code was contributed by Donald Mull.
/// </p>
/// </remarks>
public class GuidCombGenerator : IIdentifierGenerator
{
#region IIdentifierGenerator Members
/// <summary>
/// Generate a new <see cref="Guid"/> using the comb algorithm.
/// </summary>
/// <param name="session">The <see cref="ISessionImplementor"/> this id is being generated in.</param>
/// <param name="obj">The entity for which the id is being generated.</param>
/// <returns>The new identifier as a <see cref="Guid"/>.</returns>
public object Generate(ISessionImplementor session, object obj)
{
return GenerateComb();
}
/// <summary>
/// Generate a new <see cref="Guid"/> using the comb algorithm.
/// </summary>
private Guid GenerateComb()
{
byte[] guidArray = Guid.NewGuid().ToByteArray();
DateTime baseDate = new DateTime(1900, 1, 1);
DateTime now = DateTime.Now;
// Get the days and milliseconds which will be used to build the byte string
TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
TimeSpan msecs = now.TimeOfDay;
// Convert to a byte array
// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
byte[] daysArray = BitConverter.GetBytes(days.Days);
byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds / 3.333333));
// Reverse the bytes to match SQL Servers ordering
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Copy the bytes into the guid
Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
return new Guid(guidArray);
}
#endregion
}
}