From 61b4312bad7d0df616b1488f7e7783adfc1e88d8 Mon Sep 17 00:00:00 2001 From: Yu Vitaqua fer Chronos Date: Sat, 7 Oct 2023 23:54:13 +0100 Subject: [PATCH] Add some documentation for NULID as well as minor tweaks. --- config.nims | 0 nulid.nimble | 2 +- src/nulid.nim | 106 +++++++++++++++++++++++++++++++++++++++++------- tests/test1.nim | 2 +- 4 files changed, 93 insertions(+), 17 deletions(-) create mode 100644 config.nims diff --git a/config.nims b/config.nims new file mode 100644 index 0000000..e69de29 diff --git a/nulid.nimble b/nulid.nimble index e4aac71..a325d39 100644 --- a/nulid.nimble +++ b/nulid.nimble @@ -1,6 +1,6 @@ # Package -version = "0.2.1" +version = "0.2.2" author = "Yu Vitaqua fer Chronos" description = "An implementation of ULID!" license = "CC0" diff --git a/src/nulid.nim b/src/nulid.nim index feae6ca..4b3e99c 100644 --- a/src/nulid.nim +++ b/src/nulid.nim @@ -1,6 +1,5 @@ import std/[ asyncdispatch, - sysrand, times ] @@ -9,30 +8,72 @@ import pkg/[ nint128 ] +const insecureRandom = defined(nulidInsecureRandom) or defined(js) # No sysrand on the JS backend + +when insecureRandom: + import std/random + +else: + import std/sysrand + +# Relying on internal implementation details isn't great, but it's unlikely to change so... import pkg/nint128/vendor/stew/endians2 const HighUint80 = u128("1208925819614629174706176") type NULID* = object + ## An object representing a ULID. timestamp*: int64 = 0 randomness*: UInt128 = 0.u128 NULIDGenerator* = ref object - lastTime: int64 = 0 - random: UInt128 = u128(0) + ## A NULID generator object, contains details needed to follow the spec. + ## A generator was made to be compliant with the NULID spec and also to be + ## threadsafe not use globals that could change. + lastTime: int64 ## Timestamp of last ULID + random: UInt128 ## A random number + + when insecureRandom: + rand: Rand ## Random generator when using insecure random + +proc initNulidGenerator*(): NULIDGenerator = + ## Initialises a `NULIDGenerator` for use. + result = NULIDGenerator(lastTime: 0, random: 0.u128) + + when insecureRandom: + result.rand = initRand() + +let globalGen = initNulidGenerator() func swapBytes(x: Int128): Int128 = result.lo = swapBytes(cast[uint64](x.hi)) result.hi = cast[int64](swapBytes(x.lo)) -proc toArray*[T](oa: openArray[T], size: static Slice[int]): array[size.len, T] = +func toArray[T](oa: openArray[T], size: static Slice[int]): array[size.len, T] = result[0..