1 // Copyright 2018 Google LLC All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package random 16 17 import "math/rand" 18 19 // Option is an optional parameter to the random functions 20 type Option func(opts *options) 21 22 type options struct { 23 source rand.Source 24 25 // TODO opens the door to add this in the future 26 // algorithm digest.Algorithm 27 } 28 29 func getOptions(opts []Option) *options { 30 // get a random seed 31 32 // TODO in go 1.20 this is fine (it will be random) 33 seed := rand.Int63() //nolint:gosec 34 /* 35 // in prior go versions this needs to come from crypto/rand 36 var b [8]byte 37 _, err := crypto_rand.Read(b[:]) 38 if err != nil { 39 panic("cryptographically secure random number generator is not working") 40 } 41 seed := int64(binary.LittleEndian.Int64(b[:])) 42 */ 43 44 // defaults 45 o := &options{ 46 source: rand.NewSource(seed), 47 } 48 49 for _, opt := range opts { 50 opt(o) 51 } 52 return o 53 } 54 55 // WithSource sets the random number generator source 56 func WithSource(source rand.Source) Option { 57 return func(opts *options) { 58 opts.source = source 59 } 60 } 61