Skip to content

Commit

Permalink
perf: improve the performance of randomBytes (#20)
Browse files Browse the repository at this point in the history
Co-authored-by: Joe Chen <[email protected]>
  • Loading branch information
songzhibin97 and unknwon authored Apr 9, 2022
1 parent 94a436d commit 0e0bbe4
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
package csrf

import (
"crypto/rand"
"fmt"
r "math/rand"
"math/rand"
"net/http"
"reflect"
"time"
Expand Down Expand Up @@ -104,23 +103,30 @@ type Options struct {
ErrorFunc func(w http.ResponseWriter)
}

var src = rand.NewSource(time.Now().UnixNano())

// randomBytes generates n random []byte.
func randomBytes(n int) []byte {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
var randby bool
if num, err := rand.Read(bytes); num != n || err != nil {
r.Seed(time.Now().UnixNano())
randby = true
}
for i, b := range bytes {
if randby {
bytes[i] = alphanum[r.Intn(len(alphanum))]
} else {
bytes[i] = alphanum[b%byte(len(alphanum))]
const (
letterBytes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)

b := make([]byte, n)
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return bytes
return b
}

var _ inject.FastInvoker = (*csrfInvoker)(nil)
Expand Down

0 comments on commit 0e0bbe4

Please sign in to comment.