
This allows us to drop the cuid.net dependency and is ~6x faster while improving security (cuid2 is dubious at best in this regard). We may switch to ULID or UUIDv7 in the future for even higher performance, but this change allows for improving performance and security without any side effects.
23 lines
No EOL
825 B
C#
23 lines
No EOL
825 B
C#
using Iceshrimp.Backend.Core.Extensions;
|
|
|
|
namespace Iceshrimp.Backend.Core.Helpers;
|
|
|
|
public static class IdHelpers
|
|
{
|
|
private const long Time2000 = 946684800000;
|
|
|
|
public static string GenerateSlowflakeId(DateTime? createdAt = null)
|
|
{
|
|
if (createdAt?.Kind is not null and not DateTimeKind.Utc)
|
|
createdAt = createdAt.Value.ToUniversalTime();
|
|
|
|
createdAt ??= DateTime.UtcNow;
|
|
|
|
// We want to use a charset with a power-of-two amount of possible characters for optimal CSPRNG performance.
|
|
var random = CryptographyHelpers.GenerateRandomString(8, CryptographyHelpers.Charset.CrockfordBase32Lower);
|
|
var now = (long)createdAt.Value.Subtract(DateTime.UnixEpoch).TotalMilliseconds;
|
|
var time = Math.Max(now - Time2000, 0);
|
|
var timestamp = time.ToBase36().PadLeft(8, '0');
|
|
return timestamp + random;
|
|
}
|
|
} |