Skip to content

Commit e6731a9

Browse files
committed
simplifies safeasynciter (magic of auto)
1 parent f5ea783 commit e6731a9

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

codex/utils/safeasynciter.nim

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -52,17 +52,15 @@ type
5252
next*: SafeGenNext[?!T]
5353

5454
proc flatMap[T, U](
55-
fut: Future[?!T], fn: SafeFunction[?!T, ?!U]
55+
fut: auto, fn: SafeFunction[?!T, ?!U]
5656
): Future[?!U] {.async: (raises: [CancelledError]).} =
57-
let raisingFut = cast[Future[?!T].Raising([CancelledError])](fut)
58-
let t = await raisingFut
57+
let t = await fut
5958
await fn(t)
6059

6160
proc flatMap[T, U](
62-
fut: Future[?!T], fn: SafeFunction[?!T, Option[?!U]]
61+
fut: auto, fn: SafeFunction[?!T, Option[?!U]]
6362
): Future[Option[?!U]] {.async: (raises: [CancelledError]).} =
64-
let raisingFut = cast[Future[?!T].Raising([CancelledError])](fut)
65-
let t = await raisingFut
63+
let t = await fut
6664
await fn(t)
6765

6866
########################################################################
@@ -141,13 +139,11 @@ proc finish*[T](self: SafeAsyncIter[T]): void =
141139
proc finished*[T](self: SafeAsyncIter[T]): bool =
142140
self.finished
143141

144-
iterator items*[T](self: SafeAsyncIter[T]): Future[?!T] =
142+
iterator items*[T](self: SafeAsyncIter[T]): auto {.inline.} =
145143
while not self.finished:
146144
yield self.next()
147145

148-
iterator pairs*[T](
149-
self: SafeAsyncIter[T]
150-
): tuple[key: int, val: Future[?!T]] {.inline.} =
146+
iterator pairs*[T](self: SafeAsyncIter[T]): auto {.inline.} =
151147
var i = 0
152148
while not self.finished:
153149
yield (i, self.next())
@@ -176,25 +172,23 @@ proc mapFilter*[T, U](
176172
mapPredicate: SafeFunction[?!T, Option[?!U]],
177173
finishOnErr: bool = true,
178174
): Future[SafeAsyncIter[U]] {.async: (raises: [CancelledError]).} =
179-
var nextFutU: Option[Future[?!U]]
175+
var nextU: Option[?!U]
180176

181177
proc filter(): Future[void] {.async: (raises: [CancelledError]).} =
182-
nextFutU = Future[?!U].none
178+
nextU = none(?!U)
183179
while not iter.finished:
184-
let futT: Future[?!T] = iter.next()
180+
let futT = iter.next()
185181
if mappedValue =? await futT.flatMap(mapPredicate):
186-
let fut: Future[?!U] = newFuture[?!U]("mapFilter.filter")
187-
fut.complete(mappedValue)
188-
nextFutU = fut.some
182+
nextU = some(mappedValue)
189183
break
190184

191185
proc genNext(): Future[?!U] {.async: (raises: [CancelledError]).} =
192-
let futU = cast[Future[?!U].Raising([CancelledError])](nextFutU.unsafeGet)
186+
let u = nextU.unsafeGet
193187
await filter()
194-
await futU
188+
u
195189

196190
proc isFinished(): bool =
197-
nextFutU.isNone
191+
nextU.isNone
198192

199193
await filter()
200194
SafeAsyncIter[U].new(genNext, isFinished, finishOnErr = finishOnErr)

0 commit comments

Comments
 (0)