Skip to content

Commit 9fab791

Browse files
author
Sri Krishna Paritala
committed
Fixed Uniqueness
1 parent d65fcf8 commit 9fab791

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

id.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package idgen
33
import (
44
"errors"
55
"io"
6+
"math"
67
"math/rand"
78
"strings"
89
"sync"
@@ -35,7 +36,8 @@ func New(prefix string) string {
3536

3637
var entropyPool = sync.Pool{
3738
New: func() interface{} {
38-
return ulid.Monotonic(rand.New(rand.NewSource(time.Now().UnixNano())), 0)
39+
ns := time.Now().UnixNano()
40+
return ulid.Monotonic(rand.New(rand.NewSource(ns)), uint64(ns)%math.MaxUint32)
3941
},
4042
}
4143

id_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"net/url"
66
"sort"
77
"strings"
8+
"sync"
89
"testing"
910
"time"
1011

@@ -52,6 +53,36 @@ func TestUniqueness(t *testing.T) {
5253
}
5354
}
5455

56+
func TestUniquenessParallel(t *testing.T) {
57+
var wg sync.WaitGroup
58+
59+
ids := make(chan string, 1000)
60+
for i := 0; i < 100; i++ {
61+
go func(ids chan<- string) {
62+
wg.Add(1)
63+
defer wg.Done()
64+
65+
for i := 0; i < 100; i++ {
66+
ids <- idgen.New("usr")
67+
}
68+
}(ids)
69+
}
70+
71+
go func() {
72+
wg.Wait()
73+
close(ids)
74+
}()
75+
76+
set := map[string]bool{}
77+
for id := range ids {
78+
if set[id] {
79+
t.Errorf("generating repeated strings")
80+
}
81+
82+
set[id] = true
83+
}
84+
}
85+
5586
func TestLexicalOrder(t *testing.T) {
5687
var ii [1000]string
5788
for k := range ii {

0 commit comments

Comments
 (0)