|
| 1 | +//go:build go1.21 |
| 2 | + |
| 3 | +/* |
| 4 | + * |
| 5 | + * Copyright 2024 gRPC authors. |
| 6 | + * |
| 7 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | + * you may not use this file except in compliance with the License. |
| 9 | + * You may obtain a copy of the License at |
| 10 | + * |
| 11 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | + * |
| 13 | + * Unless required by applicable law or agreed to in writing, software |
| 14 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | + * See the License for the specific language governing permissions and |
| 17 | + * limitations under the License. |
| 18 | + * |
| 19 | + */ |
| 20 | + |
| 21 | +// Package grpcrand implements math/rand functions in a concurrent-safe way |
| 22 | +// with a global random source, independent of math/rand's global source. |
| 23 | +package grpcrand |
| 24 | + |
| 25 | +import "math/rand" |
| 26 | + |
| 27 | +// This implementation will be used for Go version 1.21 or newer. |
| 28 | +// For older versions, the original implementation with mutex will be used. |
| 29 | + |
| 30 | +// Int implements rand.Int on the grpcrand global source. |
| 31 | +func Int() int { |
| 32 | + return rand.Int() |
| 33 | +} |
| 34 | + |
| 35 | +// Int63n implements rand.Int63n on the grpcrand global source. |
| 36 | +func Int63n(n int64) int64 { |
| 37 | + return rand.Int63n(n) |
| 38 | +} |
| 39 | + |
| 40 | +// Intn implements rand.Intn on the grpcrand global source. |
| 41 | +func Intn(n int) int { |
| 42 | + return rand.Intn(n) |
| 43 | +} |
| 44 | + |
| 45 | +// Int31n implements rand.Int31n on the grpcrand global source. |
| 46 | +func Int31n(n int32) int32 { |
| 47 | + return rand.Int31n(n) |
| 48 | +} |
| 49 | + |
| 50 | +// Float64 implements rand.Float64 on the grpcrand global source. |
| 51 | +func Float64() float64 { |
| 52 | + return rand.Float64() |
| 53 | +} |
| 54 | + |
| 55 | +// Uint64 implements rand.Uint64 on the grpcrand global source. |
| 56 | +func Uint64() uint64 { |
| 57 | + return rand.Uint64() |
| 58 | +} |
| 59 | + |
| 60 | +// Uint32 implements rand.Uint32 on the grpcrand global source. |
| 61 | +func Uint32() uint32 { |
| 62 | + return rand.Uint32() |
| 63 | +} |
| 64 | + |
| 65 | +// ExpFloat64 implements rand.ExpFloat64 on the grpcrand global source. |
| 66 | +func ExpFloat64() float64 { |
| 67 | + return rand.ExpFloat64() |
| 68 | +} |
| 69 | + |
| 70 | +// Shuffle implements rand.Shuffle on the grpcrand global source. |
| 71 | +var Shuffle = func(n int, f func(int, int)) { |
| 72 | + rand.Shuffle(n, f) |
| 73 | +} |
0 commit comments