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 wrapper | |
6 | |
7 import ( | |
8 "math/rand" | |
9 | |
10 "golang.org/x/net/context" | |
11 ) | |
12 | |
13 // MathRandFactory is the function signature for factory methods compatible with | |
M-A Ruel
2015/05/25 17:14:52
Why? I mean, I can see why a pseudo-random is usef
iannucci
2015/05/26 18:25:06
Exposed to who? This is just an interface. There c
| |
14 // SetMathRandFactory. | |
15 type MathRandFactory func(context.Context) *rand.Rand | |
16 | |
17 // GetMathRand gets a *"math/rand".Rand from the context. If one hasn't been | |
18 // set, this creates a new Rand object with a Source initialized from the | |
19 // current time accordint to GetTimeNow(c).UnixNano(). | |
20 func GetMathRand(c context.Context) *rand.Rand { | |
21 obj := c.Value(mathRandKey) | |
22 if obj == nil || obj.(MathRandFactory) == nil { | |
23 return rand.New(rand.NewSource(GetTimeNow(c).UnixNano())) | |
24 } | |
25 return obj.(MathRandFactory)(c) | |
26 } | |
27 | |
28 // SetMathRandFactory sets the function to produce *"math/rand".Rand instances, | |
29 // as returned by the GetMathRand method. | |
30 func SetMathRandFactory(c context.Context, mrf MathRandFactory) context.Context { | |
31 return context.WithValue(c, mathRandKey, mrf) | |
32 } | |
33 | |
34 // SetMathRand sets the current *"math/rand".Rand object in the context. Useful | |
35 // for testing with a quick mock. This is just a shorthand SetMathRandFactory | |
36 // invocation to set a factory which always returns the same object. | |
37 func SetMathRand(c context.Context, r *rand.Rand) context.Context { | |
38 f := func(context.Context) *rand.Rand { return r } | |
39 if r == nil { | |
40 f = nil | |
41 } | |
42 return SetMathRandFactory(c, f) | |
43 } | |
OLD | NEW |