Skip to content

Commit

Permalink
Merge pull request #25 from shogo82148/use-global-rand
Browse files Browse the repository at this point in the history
use global rand functions
  • Loading branch information
shogo82148 authored Dec 29, 2023
2 parents 294a261 + 9199a4c commit 0a0ccb6
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 31 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ jobs:
strategy:
matrix:
go:
- "1"
- "stable"
- "1.22.0-rc.1"
- "1.21"
- "1.20"
- "1.19"
Expand Down
21 changes: 21 additions & 0 deletions rand.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//go:build !go1.22
// +build !go1.22

package retry

import (
"math/rand"
"time"
)

func (p *Policy) randomJitter() time.Duration {
jitter := int64(p.Jitter)
if jitter == 0 {
return 0
}

if jitter < 0 {
return -time.Duration(rand.Int63n(-jitter))
}
return time.Duration(rand.Int63n(jitter))
}
21 changes: 21 additions & 0 deletions rand_v2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//go:build go1.22
// +build go1.22

package retry

import (
"math/rand/v2"
"time"
)

func (p *Policy) randomJitter() time.Duration {
jitter := p.Jitter
if jitter == 0 {
return 0
}

if jitter < 0 {
return -rand.N(-jitter)
}
return rand.N(jitter)
}
30 changes: 0 additions & 30 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ package retry

import (
"context"
crand "crypto/rand"
"encoding/binary"
"errors"
"math/rand"
"sync"
"time"
)

Expand All @@ -28,9 +24,6 @@ type Policy struct {
// Zero means no jitter.
// Negative value shorten the delay.
Jitter time.Duration

mu sync.Mutex
rand *rand.Rand
}

// Retrier handles retrying.
Expand Down Expand Up @@ -122,29 +115,6 @@ func MarkPermanent(err error) error {
return &permanentError{err}
}

func (p *Policy) randomJitter() time.Duration {
jitter := int64(p.Jitter)
if jitter == 0 {
return 0
}

p.mu.Lock()
defer p.mu.Unlock()

if p.rand == nil {
// initialize rand using crypto/rand
var seed int64
if err := binary.Read(crand.Reader, binary.LittleEndian, &seed); err != nil {
seed = time.Now().UnixNano() // fall back to timestamp
}
p.rand = rand.New(rand.NewSource(seed))
}
if jitter < 0 {
return -time.Duration(p.rand.Int63n(-jitter))
}
return time.Duration(p.rand.Int63n(jitter))
}

// Continue returns whether retrying should be continued.
func (r *Retrier) Continue() bool {
r.count++
Expand Down

0 comments on commit 0a0ccb6

Please sign in to comment.