summary refs log tree commit diff stats
path: root/lib/pure
diff options
context:
space:
mode:
authorDominik Picheta <dominikpicheta@googlemail.com>2016-06-19 22:58:14 +0100
committerGitHub <noreply@github.com>2016-06-19 22:58:14 +0100
commitf76112fb01beed159f0697c6e7d27dcab7323d8d (patch)
treeda23c142a2264c88e09b5f6e75f5232f5fe30178 /lib/pure
parentf54e2bae6be49283df412137437170631588801c (diff)
parentc93292e2f7a8d3bf7c6fbadccafe1516d77b4ece (diff)
downloadNim-f76112fb01beed159f0697c6e7d27dcab7323d8d.tar.gz
Merge pull request #4370 from edubart/future-withtimeout
Add withTimeout proc for futures
Diffstat (limited to 'lib/pure')
-rw-r--r--lib/pure/asyncdispatch.nim18
1 files changed, 18 insertions, 0 deletions
diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim
index bb19f87ef..082fe40ff 100644
--- a/lib/pure/asyncdispatch.nim
+++ b/lib/pure/asyncdispatch.nim
@@ -1542,6 +1542,24 @@ proc sleepAsync*(ms: int): Future[void] =
   p.timers.push((epochTime() + (ms / 1000), retFuture))
   return retFuture
 
+proc withTimeout*[T](fut: Future[T], timeout: int): Future[bool] =
+  ## Returns a future which will complete once ``fut`` completes or after
+  ## ``timeout`` milliseconds has elapsed.
+  ##
+  ## If ``fut`` completes first the returned future will hold true,
+  ## otherwise, if ``timeout`` milliseconds has elapsed first, the returned
+  ## future will hold false.
+
+  var retFuture = newFuture[bool]("asyncdispatch.`withTimeout`")
+  var timeoutFuture = sleepAsync(timeout)
+  fut.callback =
+    proc () =
+      if not retFuture.finished: retFuture.complete(true)
+  timeoutFuture.callback =
+    proc () =
+      if not retFuture.finished: retFuture.complete(false)
+  return retFuture
+
 proc accept*(socket: AsyncFD,
     flags = {SocketFlag.SafeDisconn}): Future[AsyncFD] =
   ## Accepts a new connection. Returns a future containing the client socket