31 lines
894 B
C#
31 lines
894 B
C#
using System.Numerics;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace KronaStaffTerminal.Models;
|
|
|
|
internal static class UlidGenerator
|
|
{
|
|
private const string Alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
|
|
public static string New()
|
|
{
|
|
Span<byte> value = stackalloc byte[16];
|
|
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
for (var index = 5; index >= 0; index--)
|
|
{
|
|
value[index] = (byte)(timestamp & 0xff);
|
|
timestamp >>= 8;
|
|
}
|
|
|
|
RandomNumberGenerator.Fill(value[6..]);
|
|
var number = new BigInteger(value, isUnsigned: true, isBigEndian: true);
|
|
Span<char> result = stackalloc char[26];
|
|
for (var index = 25; index >= 0; index--)
|
|
{
|
|
result[index] = Alphabet[(int)(number & 31)];
|
|
number >>= 5;
|
|
}
|
|
|
|
return new string(result);
|
|
}
|
|
}
|