trpc.group/trpc-go/trpc-go@v1.0.3/internal/rand/rand.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  // Package rand provides public goroutine-safe random function.
    15  // The implementation is similar to grpc random functions. Additionally,
    16  // the seed function is provided to be called from the outside, and
    17  // the random functions are provided as a struct's methods.
    18  package rand
    19  
    20  import (
    21  	"math/rand"
    22  	"sync"
    23  )
    24  
    25  // SafeRand is the safe random functions struct.
    26  type SafeRand struct {
    27  	r  *rand.Rand
    28  	mu sync.Mutex
    29  }
    30  
    31  // NewSafeRand creates a SafeRand using the given seed.
    32  func NewSafeRand(seed int64) *SafeRand {
    33  	c := &SafeRand{
    34  		r: rand.New(rand.NewSource(seed)),
    35  	}
    36  	return c
    37  }
    38  
    39  // Int63n provides a random int64.
    40  func (c *SafeRand) Int63n(n int64) int64 {
    41  	c.mu.Lock()
    42  	defer c.mu.Unlock()
    43  	res := c.r.Int63n(n)
    44  	return res
    45  }
    46  
    47  // Intn provides a random int.
    48  func (c *SafeRand) Intn(n int) int {
    49  	c.mu.Lock()
    50  	defer c.mu.Unlock()
    51  	res := c.r.Intn(n)
    52  	return res
    53  }
    54  
    55  // Float64 provides a random float64.
    56  func (c *SafeRand) Float64() float64 {
    57  	c.mu.Lock()
    58  	defer c.mu.Unlock()
    59  	res := c.r.Float64()
    60  	return res
    61  }