| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package gae | |
| 6 | |
| 7 import ( | |
| 8 "math/rand" | |
| 9 | |
| 10 "github.com/luci/luci-go/common/clock" | |
| 11 "golang.org/x/net/context" | |
| 12 ) | |
| 13 | |
| 14 // TODO(riannucci): Extract this into its own package. It's used by taskqueue, | |
| 15 // but otherwise isn't related to gae services at all. | |
| 16 | |
| 17 // MathRandFactory is the function signature for factory methods compatible with | |
| 18 // SetMathRandFactory. | |
| 19 type MathRandFactory func(context.Context) *rand.Rand | |
| 20 | |
| 21 // GetMathRand gets a *"math/rand".Rand from the context. If one hasn't been | |
| 22 // set, this creates a new Rand object with a Source initialized from the | |
| 23 // current time clock.Now(c).UnixNano(). | |
| 24 func GetMathRand(c context.Context) *rand.Rand { | |
| 25 if f, ok := c.Value(mathRandKey).(MathRandFactory); ok && f != nil { | |
| 26 return f(c) | |
| 27 } | |
| 28 return rand.New(rand.NewSource(clock.Now(c).UnixNano())) | |
| 29 } | |
| 30 | |
| 31 // SetMathRandFactory sets the function to produce *"math/rand".Rand instances, | |
| 32 // as returned by the GetMathRand method. | |
| 33 func SetMathRandFactory(c context.Context, mrf MathRandFactory) context.Context
{ | |
| 34 return context.WithValue(c, mathRandKey, mrf) | |
| 35 } | |
| 36 | |
| 37 // SetMathRand sets the current *"math/rand".Rand object in the context. Useful | |
| 38 // for testing with a quick mock. This is just a shorthand SetMathRandFactory | |
| 39 // invocation to set a factory which always returns the same object. | |
| 40 func SetMathRand(c context.Context, r *rand.Rand) context.Context { | |
| 41 if r == nil { | |
| 42 return SetMathRandFactory(c, nil) | |
| 43 } | |
| 44 return SetMathRandFactory(c, func(context.Context) *rand.Rand { return r
}) | |
| 45 } | |
| OLD | NEW |