# beacon_chain # Copyright (c) 2023 Status Research & Development GmbH # Licensed and distributed under either of # * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT). # * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0). # at your option. This file may not be copied, modified, or distributed except according to those terms. # TODO: These should be added to the Chronos's asyncfutures2 module # See https://github.com/status-im/nim-chronos/pull/339 import chronos proc firstCompletedFuture*(futs: varargs[FutureBase]): Future[FutureBase] = ## Returns a future which will complete and return completed FutureBase, ## when one of the futures in ``futs`` is completed. ## ## If the argument is empty, the returned future FAILS immediately. ## ## On success, the returned Future will hold the completed FutureBase. ## ## If all futures fail naturally or due to cancellation, the returned ## future will be failed as well. ## ## On cancellation, futures in ``futs`` WILL NOT BE cancelled. var retFuture = newFuture[FutureBase]("chronos.firstCompletedFuture()") # Because we can't capture varargs[T] in closures we need to create copy. var nfuts = @futs # If one of the Future[T] already finished we return it as result for fut in nfuts: if fut.completed(): retFuture.complete(fut) return retFuture if len(nfuts) == 0: retFuture.fail(newException(ValueError, "Empty Future[T] list")) return var failedFutures = 0 var cb: proc(udata: pointer) {.gcsafe, raises: [].} cb = proc(udata: pointer) {.gcsafe, raises: [].} = if not(retFuture.finished()): var res: FutureBase var rfut = cast[FutureBase](udata) if rfut.completed: for i in 0..