Add ulid package

This commit is contained in:
Ask Bjørn Hansen 2023-07-08 12:49:14 -07:00
parent ebd0695862
commit 3ba8ba4a22
2 changed files with 76 additions and 0 deletions

51
ulid/ulid.go Normal file
View File

@ -0,0 +1,51 @@
package ulid
import (
cryptorand "crypto/rand"
"encoding/binary"
"io"
mathrand "math/rand"
"os"
"sync"
"time"
oklid "github.com/oklog/ulid/v2"
"go.ntppool.org/common/logger"
)
var monotonicPool = sync.Pool{
New: func() interface{} {
log := logger.Setup()
var seed int64
err := binary.Read(cryptorand.Reader, binary.BigEndian, &seed)
if err != nil {
log.Error("crypto/rand error", "err", err)
os.Exit(10)
}
rand := mathrand.New(mathrand.NewSource(seed))
inc := uint64(mathrand.Int63())
// log.Printf("seed: %d", seed)
// log.Printf("inc: %d", inc)
// inc = inc & ^uint64(1<<63) // only want 63 bits
mono := oklid.Monotonic(rand, inc)
return mono
},
}
func MakeULID(t time.Time) (*oklid.ULID, error) {
mono := monotonicPool.Get().(io.Reader)
id, err := oklid.New(oklid.Timestamp(t), mono)
if err != nil {
return nil, err
}
return &id, nil
}

25
ulid/ulid_test.go Normal file
View File

@ -0,0 +1,25 @@
package ulid
import (
"testing"
"time"
)
func TestULID(t *testing.T) {
tm := time.Now()
ul1, err := MakeULID(tm)
if err != nil {
t.Logf("makeULID failed: %s", err)
t.Fail()
}
ul2, err := MakeULID(tm)
if err != nil {
t.Logf("MakeULID failed: %s", err)
t.Fail()
}
if ul1.String() == ul2.String() {
t.Logf("ul1 and ul2 got the same string: %s", ul1.String())
t.Fail()
}
t.Logf("ulid string 1 and 2: %s | %s", ul1.String(), ul2.String())
}