-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
- Loading branch information
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
<!-- omit in toc --> | ||
# Half-ULID for C# / .NET | ||
|
||
Half-ULID (HUlid) is a 64-bit shrinked version of [ULID](https://github.com/ulid/spec). | ||
Max 2,097,152 of IDs can be created for every milliseconds. | ||
|
||
|
||
|
||
## Structure | ||
|
||
`YearOffset(7) Month(4) Day(5) Hour(5) Minute(6) Second(6) Millisec(10)` 43-bit total | ||
+ | ||
`21-bit value` from 0 to 2,097,151 | ||
|
||
*NOTE*: `YearOffset` supports for 128 years from origin. (A.D. 2,150 December 31 by default) | ||
|
||
|
||
|
||
## Usage | ||
|
||
```csharp | ||
using SatorImaging.HUlid; | ||
|
||
// Half-Ulid stores year as an offset from specified origin. | ||
HalfUlid.Init(originYear: 2023); | ||
|
||
// generator method uses same creation time until next Init() call. | ||
var id = HalfUlid.Next(); // generate sequential id. | ||
id = HalfUlid.Next(offset: 10); // custom offset; | ||
id = HalfUlid.Next(10); | ||
id = HalfUlid.Next(10); | ||
var randomId = HaldUlid.Random(); // generate random id. | ||
// retrieve creation time in UTC format. | ||
var createdAt = id.ToHUlidDateTime(); | ||
createdAt = id.ToHUlidDateTime(originYear: 2023); // retrieve with custom year origin. | ||
// retrieve value part of Half-Ulid. | ||
var value = id.ToHUlidValue(); | ||
|
||
// DateTime.MinValue will be returned when failed to convert. | ||
if (0L.ToHUlidDateTime() == DateTime.MinValue) | ||
thow new Exception(); | ||
|
||
// set custom creation time. | ||
HalfUlid.SetCreationTime(DateTime.Now); // local time automatically converted to UTC time. | ||
// actual methods called from extension methods. | ||
value = HalfUlid.GetValue(value); | ||
createdAt = HalfUlid.GetDateTime(value, originYear: 2023); | ||
``` | ||
|
||
|
||
|
||
|
||
|
||
# Copyright | ||
|
||
Copyright © 2023 Sator Imaging, all rights reserved. | ||
|
||
|
||
|
||
# License | ||
|
||
|
||
<p> | ||
<details> | ||
<summary>The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software.</summary> | ||
|
||
```text | ||
MIT License | ||
Copyright (c) 2023 Sator Imaging | ||
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. | ||
``` | ||
|
||
</details> | ||
</p> |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Threading; | ||
|
||
namespace SatorImaging.HUlid | ||
{ | ||
public static class HalfUlid | ||
{ | ||
const int ID_MAX = 2097151; // 2 ^ 21 - 1; | ||
const int DEFAULT_YEAR_ORIGIN = 2023; | ||
const int DEFAULT_START_VALUE = -1; | ||
|
||
static int _currentOriginYear = DEFAULT_YEAR_ORIGIN; | ||
static long _currentValue = DEFAULT_START_VALUE; | ||
static long _timeBits = GetTimeBits(DateTime.MinValue); //long.MinValue; | ||
readonly static Random _rng = new Random(); | ||
|
||
|
||
//public static void InitTimeBits() | ||
//{ | ||
// Interlocked.CompareExchange(ref _timeBits, GetTimeBits(DateTime.MinValue), long.MinValue); | ||
//} | ||
|
||
public static void Init(int startValue = DEFAULT_START_VALUE, int originYear = DEFAULT_YEAR_ORIGIN) | ||
{ | ||
_currentValue = Math.Max(DEFAULT_START_VALUE, startValue); | ||
_currentOriginYear = originYear; | ||
SetCreationTime(DateTime.MinValue); | ||
} | ||
|
||
|
||
public static long GetTimeBits(DateTime utcTime) | ||
{ | ||
if (utcTime == DateTime.MinValue) | ||
utcTime = DateTime.UtcNow; | ||
if (utcTime.Kind != DateTimeKind.Utc) | ||
utcTime = utcTime.ToUniversalTime(); | ||
|
||
// datetime in UPPER bits. | ||
long ret = (long)(utcTime.Year - _currentOriginYear) << 57; | ||
ret |= (long)utcTime.Month << 53; | ||
ret |= (long)utcTime.Day << 48; | ||
ret |= (long)utcTime.Hour << 43; | ||
ret |= (long)utcTime.Minute << 37; | ||
ret |= (long)utcTime.Second << 31; | ||
ret |= (long)utcTime.Millisecond << 21; | ||
return ret; | ||
} | ||
|
||
///<param name="utcTime">Non-UTC time is automatically converted to UTC time.</param> | ||
public static void SetCreationTime(DateTime utcTime) | ||
{ | ||
_timeBits = GetTimeBits(utcTime); | ||
} | ||
|
||
|
||
///<summary>Generate sequential Half-ULID value.</summary> | ||
public static long Next(int offset = 1) | ||
{ | ||
//InitTimeBits(); | ||
_currentValue += Math.Max(1, offset); | ||
return _timeBits | _currentValue; | ||
} | ||
|
||
///<summary>Generate Half-ULID value with random number.</summary> | ||
///<remarks>NOTE: identical value could be returned for same creation time.</remarks> | ||
public static long Random() | ||
{ | ||
//InitTimeBits(); | ||
return _timeBits | (long)_rng.Next(0, ID_MAX); | ||
} | ||
|
||
|
||
public static int ToHUlidValue(this long val) => GetValue(val); | ||
public static int GetValue(long val) | ||
{ | ||
return unchecked((int)(val & 0b_1111_1111_1111_1111_1111_1L)); | ||
} | ||
|
||
///<summary>NOTE: return DateTime.MinValue when error.</summary> | ||
public static DateTime ToHUlidDateTime(this long val, int originYear = -1) => GetDateTime(val, originYear); | ||
///<summary>NOTE: return DateTime.MinValue when error.</summary> | ||
public static DateTime GetDateTime(long val, int originYear = -1) | ||
{ | ||
if (originYear < 0) | ||
originYear = _currentOriginYear; | ||
|
||
try | ||
{ | ||
unchecked | ||
{ | ||
return new DateTime( | ||
(int) /**/ (val >> 57) + originYear /**/, | ||
(int)( /**/ (val & (0b_1111L << 53)) >> 53 /**/ ), | ||
(int)( /**/ (val & (0b_1111_1L << 48)) >> 48 /**/ ), | ||
(int)( /**/ (val & (0b_1111_1L << 43)) >> 43 /**/ ), | ||
(int)( /**/ (val & (0b_1111_11L << 37)) >> 37 /**/ ), | ||
(int)( /**/ (val & (0b_1111_11L << 31)) >> 31 /**/ ), | ||
(int)( /**/ (val & (0b_1111_1111_11L << 21)) >> 21 /**/ ), | ||
DateTimeKind.Utc | ||
); | ||
} | ||
} | ||
catch | ||
{ | ||
return DateTime.MinValue; | ||
} | ||
} | ||
|
||
|
||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"name": "SatorImaging.HUlid", | ||
"rootNamespace": "SatorImaging.HUlid", | ||
"references": [], | ||
"includePlatforms": [], | ||
"excludePlatforms": [], | ||
"allowUnsafeCode": false, | ||
"overrideReferences": false, | ||
"precompiledReferences": [], | ||
"autoReferenced": true, | ||
"defineConstraints": [], | ||
"versionDefines": [], | ||
"noEngineReferences": false | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
{ | ||
"name": "SatorImaging.Tests.HUlid", | ||
"rootNamespace": "SatorImaging.Tests.HUlid", | ||
"references": [ | ||
"UnityEngine.TestRunner", | ||
"UnityEditor.TestRunner", | ||
"SatorImaging.HUlid" | ||
], | ||
"includePlatforms": [ | ||
"Editor" | ||
], | ||
"excludePlatforms": [], | ||
"allowUnsafeCode": false, | ||
"overrideReferences": true, | ||
"precompiledReferences": [ | ||
"nunit.framework.dll" | ||
], | ||
"autoReferenced": false, | ||
"defineConstraints": [], | ||
"versionDefines": [], | ||
"noEngineReferences": false | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.