Skip to main content

Generates a Guid using the Comb algorithm - designed to make the use of Guids as Primary Keys, Foreign Keys, and Indexes nearly as efficient as init.

namespace NServiceBus
{
    using System;

    /// <summary>
    /// Generates a Guid using http://www.informit.com/articles/article.asp?p=25862
    /// The Comb algorithm is designed to make the use of <see cref="Guid"/>s as Primary Keys, Foreign Keys, and Indexes nearly as efficient
    /// as <see cref="int"/>.
    /// </summary>
    /// <remarks>Source: https://github.com/nhibernate/nhibernate-core/blob/4.0.4.GA/src/NHibernate/Id/GuidCombGenerator.cs</remarks>
    static class CombGuid
    {
        /// <summary>
        /// Generate a new <see cref="Guid" /> using the comb algorithm.
        /// </summary>
        public static Guid Generate()
        {
            var guidArray = Guid.NewGuid().ToByteArray();

            var now = DateTime.UtcNow;

            // Get the days and milliseconds which will be used to build the byte string
            var days = new TimeSpan(now.Ticks - BaseDateTicks);
            var timeOfDay = 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
            var daysArray = BitConverter.GetBytes(days.Days);
            var millisecondArray = BitConverter.GetBytes((long) (timeOfDay.TotalMilliseconds/3.333333));

            // Reverse the bytes to match SQL Servers ordering
            Array.Reverse(daysArray);
            Array.Reverse(millisecondArray);

            // Copy the bytes into the guid
            Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
            Array.Copy(millisecondArray, millisecondArray.Length - 4, guidArray, guidArray.Length - 4, 4);

            return new Guid(guidArray);
        }

        static readonly long BaseDateTicks = new DateTime(1900, 1, 1).Ticks;
    }
}

// ====================================================================================================================
// From: JasperFx/jasper (https://github.com/JasperFx/jasper/blob/master/src/Jasper/Util/CombGuidIdGeneration.cs)
// jasper/src/Jasper/Util/CombGuidIdGeneration.cs
// // ====================================================================================================================

using System;

namespace Jasper.Util
{
    /// <summary>
    ///     Comb Guid Id Generation. More info http://www.informit.com/articles/article.aspx?p=25862
    /// </summary>
    public static class CombGuidIdGeneration
    {
        private const int NumDateBytes = 6;

        /*
            FROM: https://github.com/richardtallent/RT.Comb

            Copyright 2015 Richard S. Tallent, II
            Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
            (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
            publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to
            do so, subject to the following conditions:
            The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
            THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
            MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
            LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
            CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        */

        /// <summary>
        ///     Returns a new Guid COMB, consisting of a random Guid combined with the provided timestamp.
        /// </summary>
        public static Guid NewGuid(DateTimeOffset timestamp)
        {
            return Create(Guid.NewGuid(), timestamp);
        }

        public static Guid NewGuid()
        {
            return Create(Guid.NewGuid(), DateTimeOffset.UtcNow);
        }

        private static byte[] DateTimeToBytes(DateTimeOffset timestamp)
        {
            var unixTime = timestamp.ToUnixTimeMilliseconds();
            var unixTimeBytes = BitConverter.GetBytes(unixTime);

            var result = new byte[NumDateBytes];

            if (BitConverter.IsLittleEndian)
            {
                Array.Copy(unixTimeBytes, 2, result, 0, 4);
                Array.Copy(unixTimeBytes, 0, result, 4, 2);
            }
            else
            {
                Array.Copy(unixTimeBytes, 2, result, 0, 6);
            }

            return result;
        }

        private static DateTimeOffset BytesToDateTime(byte[] value)
        {
            var unixTimeBytes = new byte[8];

            if (BitConverter.IsLittleEndian)
            {
                Array.Copy(value, 4, unixTimeBytes, 0, 2);
                Array.Copy(value, 0, unixTimeBytes, 2, 4);
            }
            else
            {
                Array.Copy(value, 0, unixTimeBytes, 2, 6);
            }

            var unixTime = BitConverter.ToInt64(unixTimeBytes, 0);
            var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(0).AddMilliseconds(unixTime);
            return timestamp;
        }

        public static Guid Create(Guid value, DateTimeOffset timestamp)
        {
            var bytes = value.ToByteArray();
            var dtbytes = DateTimeToBytes(timestamp);

            // Overwrite the first six bytes with unix time
            Array.Copy(dtbytes, 0, bytes, 0, NumDateBytes);
            return new Guid(bytes);
        }

        public static DateTimeOffset GetTimestamp(Guid comb)
        {
            var bytes = comb.ToByteArray();
            return BytesToDateTime(bytes);
        }
    }
}