Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1176)

Unified Diff: go/src/infra/gae/libs/wrapper/mathrand.go

Issue 1151473003: Better attempt at an appengine wrapper. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: pointer! Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: go/src/infra/gae/libs/wrapper/mathrand.go
diff --git a/go/src/infra/gae/libs/wrapper/mathrand.go b/go/src/infra/gae/libs/wrapper/mathrand.go
new file mode 100644
index 0000000000000000000000000000000000000000..2ecd2cae65865653c0c59e6092bfd7df08527877
--- /dev/null
+++ b/go/src/infra/gae/libs/wrapper/mathrand.go
@@ -0,0 +1,43 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package wrapper
+
+import (
+ "math/rand"
+
+ "golang.org/x/net/context"
+)
+
+// 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
+// SetMathRandFactory.
+type MathRandFactory func(context.Context) *rand.Rand
+
+// GetMathRand gets a *"math/rand".Rand from the context. If one hasn't been
+// set, this creates a new Rand object with a Source initialized from the
+// current time accordint to GetTimeNow(c).UnixNano().
+func GetMathRand(c context.Context) *rand.Rand {
+ obj := c.Value(mathRandKey)
+ if obj == nil || obj.(MathRandFactory) == nil {
+ return rand.New(rand.NewSource(GetTimeNow(c).UnixNano()))
+ }
+ return obj.(MathRandFactory)(c)
+}
+
+// SetMathRandFactory sets the function to produce *"math/rand".Rand instances,
+// as returned by the GetMathRand method.
+func SetMathRandFactory(c context.Context, mrf MathRandFactory) context.Context {
+ return context.WithValue(c, mathRandKey, mrf)
+}
+
+// SetMathRand sets the current *"math/rand".Rand object in the context. Useful
+// for testing with a quick mock. This is just a shorthand SetMathRandFactory
+// invocation to set a factory which always returns the same object.
+func SetMathRand(c context.Context, r *rand.Rand) context.Context {
+ f := func(context.Context) *rand.Rand { return r }
+ if r == nil {
+ f = nil
+ }
+ return SetMathRandFactory(c, f)
+}

Powered by Google App Engine
This is Rietveld 408576698