Add ulid package
This commit is contained in:
parent
ebd0695862
commit
3ba8ba4a22
51
ulid/ulid.go
Normal file
51
ulid/ulid.go
Normal 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
25
ulid/ulid_test.go
Normal 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())
|
||||
}
|
Loading…
Reference in New Issue
Block a user