Skip to content

Instantly share code, notes, and snippets.

@formix
Last active April 2, 2020 23:43
Show Gist options
  • Save formix/792b0fd2d822c289402685a06b820105 to your computer and use it in GitHub Desktop.
Save formix/792b0fd2d822c289402685a06b820105 to your computer and use it in GitHub Desktop.
64 bits Sufficiently Unique Id Generator
/****************************************************************************
* Copyright 2009-2020 Jean-Philippe Gravel, P. Eng. PSEM
* Conversion to C# from https://gist.github.com/formix/d9521fd49cbeee305e2a
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
using System;
using System.Security.Cryptography;
namespace Utils
{
/// <summary>
/// Sufficiently unique identifier.
/// </summary>
public static class SUID
{
private static ushort _counter = 0;
private static readonly object _mutex = new object();
static SUID()
{
var word = new byte[2];
RandomNumberGenerator.Create().GetBytes(word);
_counter = BitConverter.ToUInt16(word, 0);
}
/// <summary>
/// Creates a unique 64 bits ID by aggregating the current time in
/// milliseconds since epoch(Jan. 1, 1) and using a 16 bits counter.The
/// counter is initialized at a random number.This generator can create up
/// to 65536 different id per millisecond, which translate to 1 id every
/// 16 microseconds.
/// </summary>
/// <returns>A new 64 bit value.</returns>
public static ulong Next()
{
lock (_mutex)
{
ulong now = (ulong)(DateTime.Now.Ticks / 10000);
ulong id = (now << 16) | _counter;
_counter++;
return id;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment