|
1 | | -import std/asyncdispatch |
| 1 | +import std/[asyncdispatch] |
2 | 2 | import ./connections |
3 | 3 | import ./bindings |
| 4 | +import ./poller |
| 5 | + |
| 6 | +type |
| 7 | + AsyncZPollCB* = proc(x: ZSocket) {.gcsafe.} |
| 8 | + AsyncZPoller* = object |
| 9 | + ## Experimental type to use zmq.poll() with Nim's async dispatch loop |
| 10 | + cb* : seq[AsyncZPollCB] |
| 11 | + zpoll*: ZPoller |
| 12 | + |
| 13 | +iterator items*(poller: AsyncZPoller): tuple[item: ZPollItem, cb: AsyncZPollCB] = |
| 14 | + var |
| 15 | + i = 0 |
| 16 | + n = poller.zpoll.len() |
| 17 | + while i < n: |
| 18 | + yield(poller.zpoll[i], poller.cb[i]) |
| 19 | + inc(i) |
| 20 | + |
| 21 | +proc `=destroy`*(obj: var AsyncZPoller) = |
| 22 | + if hasPendingOperations(): |
| 23 | + raise newException(ZmqError, "AsyncZPoller closed with pending operation") |
| 24 | + |
| 25 | +proc register*(poller: var AsyncZPoller, sock: ZSocket, event: int, cb: AsyncZPollCB) = |
| 26 | + ## Register ZSocket function |
| 27 | + poller.zpoll.register(sock, event) |
| 28 | + poller.cb.add(cb) |
| 29 | + |
| 30 | +proc register*(poller: var AsyncZPoller, conn: ZConnection, event: int, cb: AsyncZPollCB) = |
| 31 | + ## Register ZConnection |
| 32 | + poller.register(conn.socket, event, cb) |
| 33 | + |
| 34 | +proc register*(poller: var AsyncZPoller, item: ZPollItem, cb: AsyncZPollCB) = |
| 35 | + ## Register ZConnection |
| 36 | + poller.zpoll.items.add(item) |
| 37 | + poller.cb.add(cb) |
| 38 | + |
| 39 | +proc initZPoller*(poller: sink ZPoller, cb: AsyncZPollCB) : AsyncZPoller = |
| 40 | + for p in poller.items: |
| 41 | + result.register(p, cb) |
| 42 | + |
| 43 | +proc initZPoller*(args: openArray[tuple[item: ZConnection, cb: AsyncZPollCB]], event: cshort): AsyncZPoller = |
| 44 | + ## Init a ZPoller with all items on the same event |
| 45 | + for arg in args: |
| 46 | + result.register(arg.item, event, arg.cb) |
| 47 | + |
| 48 | +proc pollAsync*(poller: AsyncZPoller, timeout: int = 1) : Future[int] = |
| 49 | + ## Experimental API. Poll all the ZConnection and execute an async CB when ``event`` occurs. |
| 50 | + result = newFuture[int]("pollAsync") |
| 51 | + var r = poller.zpoll.poll(timeout) |
| 52 | + # ZMQ can't have a timeout smaller than one |
| 53 | + if r > 0: |
| 54 | + for zpoll, cb in poller.items(): |
| 55 | + if events(zpoll): |
| 56 | + proc localcb = cb(zpoll.socket) |
| 57 | + callSoon localcb |
| 58 | + if hasPendingOperations(): |
| 59 | + # poll vs drain ? |
| 60 | + poll(timeout) |
| 61 | + |
| 62 | + result.complete(r) |
4 | 63 |
|
5 | 64 | proc receiveAsync*(conn: ZConnection): Future[string] = |
6 | 65 | ## Similar to `receive()`, but `receiveAsync()` allows other async tasks to run. |
|
0 commit comments