mirror of
https://github.com/XTLS/Xray-core.git
synced 2025-04-29 16:58:34 +00:00
v1.0.0
This commit is contained in:
parent
47d23e9972
commit
c7f7c08ead
711 changed files with 82154 additions and 2 deletions
52
common/dice/dice.go
Normal file
52
common/dice/dice.go
Normal file
|
@ -0,0 +1,52 @@
|
|||
// Package dice contains common functions to generate random number.
|
||||
// It also initialize math/rand with the time in seconds at launch time.
|
||||
package dice // import "github.com/xtls/xray-core/v1/common/dice"
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
|
||||
func Roll(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
return rand.Intn(n)
|
||||
}
|
||||
|
||||
// Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
|
||||
func RollDeterministic(n int, seed int64) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
return rand.New(rand.NewSource(seed)).Intn(n)
|
||||
}
|
||||
|
||||
// RollUint16 returns a random uint16 value.
|
||||
func RollUint16() uint16 {
|
||||
return uint16(rand.Int63() >> 47)
|
||||
}
|
||||
|
||||
func RollUint64() uint64 {
|
||||
return rand.Uint64()
|
||||
}
|
||||
|
||||
func NewDeterministicDice(seed int64) *DeterministicDice {
|
||||
return &DeterministicDice{rand.New(rand.NewSource(seed))}
|
||||
}
|
||||
|
||||
type DeterministicDice struct {
|
||||
*rand.Rand
|
||||
}
|
||||
|
||||
func (dd *DeterministicDice) Roll(n int) int {
|
||||
if n == 1 {
|
||||
return 0
|
||||
}
|
||||
return dd.Intn(n)
|
||||
}
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().Unix())
|
||||
}
|
50
common/dice/dice_test.go
Normal file
50
common/dice/dice_test.go
Normal file
|
@ -0,0 +1,50 @@
|
|||
package dice_test
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"testing"
|
||||
|
||||
. "github.com/xtls/xray-core/v1/common/dice"
|
||||
)
|
||||
|
||||
func BenchmarkRoll1(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Roll(1)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRoll20(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Roll(20)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkIntn1(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
rand.Intn(1)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkIntn20(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
rand.Intn(20)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInt63(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = uint16(rand.Int63() >> 47)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInt31(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = uint16(rand.Int31() >> 15)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkIntn(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = uint16(rand.Intn(65536))
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue