Skip to content

Commit 9d307b2

Browse files
committed
update
1 parent 1e46a3d commit 9d307b2

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

slice.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,7 @@ func SliceRandList(min, max int) []int {
225225
min, max = max, min
226226
}
227227
length := max - min + 1
228-
t0 := time.Now()
229-
rand.Seed(int64(t0.Nanosecond()))
228+
rand := NewRand()
230229
list := rand.Perm(length)
231230
for index := range list {
232231
list[index] += min

string.go

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package com
1616

1717
import (
18+
"bufio"
1819
"bytes"
1920
"crypto/hmac"
2021
"crypto/md5"
@@ -70,6 +71,24 @@ func Md5file(file string) string {
7071
return ByteMd5(barray)
7172
}
7273

74+
func Md5Reader(r io.Reader) (string, error) {
75+
h := md5.New()
76+
reader := bufio.NewReader(r)
77+
buf := make([]byte, 4096) // 4KB的缓冲区
78+
for {
79+
n, err := reader.Read(buf)
80+
if err != nil && err != io.EOF {
81+
return ``, err
82+
}
83+
if n == 0 {
84+
break
85+
}
86+
h.Write(buf[:n])
87+
}
88+
md5sum := h.Sum(nil)
89+
return hex.EncodeToString(md5sum), nil
90+
}
91+
7392
func Token(key string, val []byte, args ...string) string {
7493
hm := hmac.New(sha1.New, []byte(key))
7594
hm.Write(val)
@@ -230,25 +249,30 @@ func Reverse(s string) string {
230249
return string(runes[n:])
231250
}
232251

252+
func NewRand() *r.Rand {
253+
return r.New(r.NewSource(time.Now().UnixNano()))
254+
}
255+
233256
// RandomCreateBytes generate random []byte by specify chars.
234257
func RandomCreateBytes(n int, alphabets ...byte) []byte {
235258
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
236259
var bytes = make([]byte, n)
237260
var randby bool
261+
var rd *r.Rand
238262
if num, err := rand.Read(bytes); num != n || err != nil {
239-
r.Seed(time.Now().UnixNano())
263+
rd = NewRand()
240264
randby = true
241265
}
242266
for i, b := range bytes {
243267
if len(alphabets) == 0 {
244268
if randby {
245-
bytes[i] = alphanum[r.Intn(len(alphanum))]
269+
bytes[i] = alphanum[rd.Intn(len(alphanum))]
246270
} else {
247271
bytes[i] = alphanum[b%byte(len(alphanum))]
248272
}
249273
} else {
250274
if randby {
251-
bytes[i] = alphabets[r.Intn(len(alphabets))]
275+
bytes[i] = alphabets[rd.Intn(len(alphabets))]
252276
} else {
253277
bytes[i] = alphabets[b%byte(len(alphabets))]
254278
}

0 commit comments

Comments
 (0)