Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use math/rand/v2 #88

Merged
merged 5 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions server/cmd/wsnet2-bot/cmd/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"os/signal"
"sync"
Expand Down Expand Up @@ -126,7 +126,7 @@ func runLoadWorker(ctx context.Context, p, w int, minLifeTime, maxLifeTime time.
lifetimeRange := int(maxLifeTime - minLifeTime)
n := 0
for {
time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
time.Sleep(time.Millisecond * time.Duration(rand.IntN(100)))

select {
case <-ctx.Done():
Expand All @@ -136,7 +136,7 @@ func runLoadWorker(ctx context.Context, p, w int, minLifeTime, maxLifeTime time.

lifetime := minLifeTime
if lifetimeRange > 0 {
lifetime += time.Duration(rand.Intn(lifetimeRange))
lifetime += time.Duration(rand.IntN(lifetimeRange))
}
widsuffix := fmt.Sprintf("%v-%v", wid, n)
logprefix := fmt.Sprintf("room[%v]", widsuffix)
Expand Down
12 changes: 6 additions & 6 deletions server/cmd/wsnet2-bot/cmd/soak.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cmd
import (
"context"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"os/signal"
"sync"
Expand Down Expand Up @@ -101,7 +101,7 @@ func runSoak(ctx context.Context, roomCount int, minLifeTime, maxLifeTime time.D
go func(n int) {
lifetime := minLifeTime
if lifetimeRange != 0 {
lifetime += time.Duration(rand.Intn(lifetimeRange))
lifetime += time.Duration(rand.IntN(lifetimeRange))
}
err := runSoakRoom(ctx, n, lifetime)
if err != nil {
Expand Down Expand Up @@ -248,7 +248,7 @@ func runMaster(ctx context.Context, conn *client.Connection, lifetime time.Durat
defer t.Stop()

for {
conn.Send(binary.MsgTypeBroadcast, msgBody[:rand.Intn(30)+30])
conn.Send(binary.MsgTypeBroadcast, msgBody[:rand.IntN(30)+30])

select {
case <-sendctx.Done():
Expand All @@ -265,7 +265,7 @@ func runMaster(ctx context.Context, conn *client.Connection, lifetime time.Durat
for {
conn.Send(binary.MsgTypeRoomProp, binary.MarshalRoomPropPayload(
true, true, true, group, 10, 0,
binary.Dict{"score": binary.MarshalInt(rand.Int63n(1024))}, binary.Dict{}))
binary.Dict{"score": binary.MarshalInt(rand.Int64N(1024))}, binary.Dict{}))

select {
case <-sendctx.Done():
Expand Down Expand Up @@ -344,7 +344,7 @@ func runPlayer(ctx context.Context, conn *client.Connection, masterId, logprefix
defer t.Stop()

for {
conn.Send(binary.MsgTypeToMaster, msgBody[:rand.Intn(30)+30])
conn.Send(binary.MsgTypeToMaster, msgBody[:rand.IntN(30)+30])

select {
case <-sendctx.Done():
Expand Down Expand Up @@ -394,7 +394,7 @@ func runWatcher(ctx context.Context, conn *client.Connection, logprefix string)
defer t.Stop()

for {
conn.Send(binary.MsgTypeToMaster, msgBody[:rand.Intn(30)+30])
conn.Send(binary.MsgTypeToMaster, msgBody[:rand.IntN(30)+30])

select {
case <-sendctx.Done():
Expand Down
4 changes: 2 additions & 2 deletions server/cmd/wsnet2-bot/cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cmd
import (
"context"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"os/signal"
"sync"
Expand Down Expand Up @@ -70,7 +70,7 @@ func runLoadWatcher(ctx context.Context, watcherCount int) error {
for i := 0; i < watcherCount; i++ {
go func(i int) {
defer wg.Done()
time.Sleep(time.Duration(rand.Intn(900)+100) * time.Millisecond)
time.Sleep(time.Duration(rand.IntN(900)+100) * time.Millisecond)

watcherId := fmt.Sprintf("watcher-%v-%v", pid, i)
logprefix := fmt.Sprintf("watcher[%v]", i)
Expand Down
29 changes: 19 additions & 10 deletions server/game/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ import (
"context"
crand "crypto/rand"
"database/sql"
"encoding/hex"
"encoding/binary"
"fmt"
"math"
"math/big"
"math/rand"
"math/rand/v2"
"reflect"
"regexp"
"strings"
Expand All @@ -31,14 +29,19 @@ var (
roomHistoryInsertQuery string

randsrc *rand.Rand
murand sync.Mutex

rerid *regexp.Regexp
)

func init() {
initQueries()
seed, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
randsrc = rand.New(rand.NewSource(seed.Int64()))

var seed [16]byte
_, _ = crand.Read(seed[:])
s1 := binary.NativeEndian.Uint64(seed[:8])
s2 := binary.NativeEndian.Uint64(seed[8:])
randsrc = rand.New(rand.NewPCG(s1, s2))

rerid = regexp.MustCompile(common.RoomIdPattern)
}
Expand Down Expand Up @@ -78,9 +81,13 @@ func initQueries() {
}

func RandomHex(n int) string {
b := make([]byte, (n+1)/2)
_, _ = randsrc.Read(b) // (*rand.Rand).Read always success.
return hex.EncodeToString(b)[:n]
b := make([]byte, 0, n+15)
murand.Lock()
defer murand.Unlock()
for len(b) < n {
b = fmt.Appendf(b, "%016x", randsrc.Uint64())
}
return string(b[:n])
}

func IsValidRoomId(id string) bool {
Expand Down Expand Up @@ -305,7 +312,9 @@ func (repo *Repository) newRoomInfo(ctx context.Context, tx *sqlx.Tx, op *pb.Roo

ri.Id = RandomHex(common.RoomIdLen)
if op.WithNumber {
ri.Number.Number = randsrc.Int31n(maxNumber) + 1 // [1..maxNumber]
murand.Lock()
ri.Number.Number = randsrc.Int32N(maxNumber) + 1 // [1..maxNumber]
murand.Unlock()
}

_, err = tx.NamedExecContext(ctx, roomInsertQuery, ri)
Expand Down
18 changes: 12 additions & 6 deletions server/game/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package game

import (
"context"
crand "crypto/rand"
"encoding/binary"
"errors"
"math/rand/v2"
"regexp"
"testing"
"time"

"github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
Expand Down Expand Up @@ -92,19 +94,23 @@ func TestNewRoomInfo(t *testing.T) {
}

// 生成されるはずの値
seed := time.Now().Unix()
randsrc.Seed(seed)
var seed [16]byte
_, _ = crand.Read(seed[:])
s1 := binary.NativeEndian.Uint64(seed[:8])
s2 := binary.NativeEndian.Uint64(seed[8:])
randsrc = rand.New(rand.NewPCG(s1, s2))

id1 := RandomHex(lenId)
num1 := randsrc.Int31n(int32(maxNumber)) + 1
num1 := randsrc.Int32N(int32(maxNumber)) + 1
id2 := RandomHex(lenId)
num2 := randsrc.Int31n(int32(maxNumber)) + 1
num2 := randsrc.Int32N(int32(maxNumber)) + 1

insQuery := "INSERT INTO room "
mock.ExpectBegin()
mock.ExpectExec(insQuery).WillReturnError(dupErr)
mock.ExpectExec(insQuery).WillReturnResult(sqlmock.NewResult(1, 1))

randsrc.Seed(seed)
randsrc = rand.New(rand.NewPCG(s1, s2))
tx, _ := db.Beginx()
ri, err := repo.newRoomInfo(ctx, tx, op)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions server/lobby/game_cache.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package lobby

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

Expand Down Expand Up @@ -108,7 +108,7 @@ func (c *gameCache) Rand() (*gameServer, error) {
if len(c.order) == 0 {
return nil, xerrors.New("no available game server")
}
id := c.order[rand.Intn(len(c.order))]
id := c.order[rand.IntN(len(c.order))]
return c.servers[id], nil
}

Expand Down
4 changes: 2 additions & 2 deletions server/lobby/hub_cache.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package lobby

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

Expand Down Expand Up @@ -89,6 +89,6 @@ func (c *hubCache) Rand() (*hubServer, error) {
if len(c.order) == 0 {
return nil, xerrors.New("no available hub server")
}
id := c.order[rand.Intn(len(c.order))]
id := c.order[rand.IntN(len(c.order))]
return c.servers[id], nil
}
4 changes: 2 additions & 2 deletions server/lobby/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package lobby
import (
"context"
"fmt"
"math/rand"
"math/rand/v2"
"sort"
"sync"
"time"
Expand Down Expand Up @@ -392,7 +392,7 @@ func (rs *RoomService) watch(ctx context.Context, room *pb.RoomInfo, clientInfo

var hub *hubServer
if len(hubIDs) > 0 {
n := rand.Intn(len(hubIDs))
n := rand.IntN(len(hubIDs))
hub, err = rs.hubCache.Get(hubIDs[n])
} else {
hub, err = rs.hubCache.Rand()
Expand Down
Loading