Skip to content

Commit

Permalink
perf: 根据可用字符的长度重复利用每一个随机数
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Mar 21, 2024
1 parent c35ee92 commit 33f1c3f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
27 changes: 23 additions & 4 deletions rands.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,30 @@ func bytes(r *rand.Rand, min, max int, bs []byte) []byte {
l = min + r.Intn(max-min)
}

ret := make([]byte, l)
ll := uint64(len(bs))

// 将一个 uint64 的随机数据,按 bs 的长度拆分为多个数组下标。
// 比如 bs 的长度为 10,那么一个 uint64 的随机数,
// 理论上可以表示 64 / 10 = 6 个数组下标从 bs 中拿值。

for i := 0; i < l; i++ {
index := r.Intn(len(bs))
ret[i] = bs[index]
var bit int // 表示 len(bs) 下标的最大数值需要的位数
var mask uint64 // bit 的掩码
for bit = 0; bit < 64; bit++ {
if mask = 1<<bit - 1; mask >= ll {
break
}
}

ret := make([]byte, l)
for i := 0; i < l; {
// 在 index 不够大时,index>>bit 可能会让 index 变为 0,为 0 的 index 应该抛弃。
for index := r.Uint64(); index > 0 && i < l; {
if idx := index & mask; idx < ll {
ret[i] = bs[idx]
i++
}
index >>= bit
}
}

return ret
Expand Down
10 changes: 7 additions & 3 deletions rands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,14 @@ func TestCheckArgs(t *testing.T) {
// bytes
func TestBytes1(t *testing.T) {
a := assert.New(t, false)
r1 := random
r2 := random

a.NotEqual(bytes(random, 10, 11, []byte("1234123lks;df")), bytes(random, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(random, 10, 11, []byte("1234123lks;df")), bytes(random, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(random, 10, 11, []byte("1234123lks;df")), bytes(random, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, 10, 11, []byte("1234123lks;df")), bytes(r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, 10, 11, []byte("1234123lks;df")), bytes(r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, 10, 11, []byte("1234123lks;df")), bytes(r2, 10, 11, []byte("1234123lks;df")))

println("String:", String(10, 11, AlphaNumberPunct()))
}

// Bytes
Expand Down

0 comments on commit 33f1c3f

Please sign in to comment.