Index: common/clock/cancelSleep.go |
diff --git a/common/clock/cancelSleep.go b/common/clock/cancelSleep.go |
new file mode 100644 |
index 0000000000000000000000000000000000000000..984b426edec05bb36e5279256d7d6d6c9b7340b8 |
--- /dev/null |
+++ b/common/clock/cancelSleep.go |
@@ -0,0 +1,33 @@ |
+// Copyright 2016 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 clock |
+ |
+import ( |
+ "time" |
+ |
+ "golang.org/x/net/context" |
+) |
+ |
+// CancelSleep sleeps the current goroutine (see time.Sleep). |
+// |
+// If the supplied Context is canceled prior to the specified duration, |
+// CancelSleep will return the Context's error. If the sleep completes |
+// naturally, it will return nil. |
+func CancelSleep(c context.Context, d time.Duration) error { |
iannucci
2016/02/09 20:41:10
(discussed offline) let's just make normal Sleep (
Vadim Sh.
2016/02/09 21:11:37
I'd prefer to keep CancelSleep. clock package is m
|
+ select { |
+ case <-c.Done(): |
+ return c.Err() |
+ |
+ case <-After(c, d): |
+ // For determinism, prefer context cancellation over full sleep. |
+ select { |
+ case <-c.Done(): |
+ return c.Err() |
+ default: |
+ break |
+ } |
+ return nil |
+ } |
+} |