tgeneric_async.nim 854 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. discard """
  2. output: "1\nmessa"
  3. """
  4. import async
  5. # bug #2377
  6. proc test[T](v: T) {.async.} =
  7. echo $v
  8. asyncCheck test[int](1)
  9. # More complex case involving typedesc and static params
  10. type
  11. SomeMsg = object
  12. data: string
  13. template msgId(M: type SomeMsg): int = 1
  14. proc recvMsg(): Future[tuple[msgId: int, msgData: string]] {.async.} =
  15. return (1, "message")
  16. proc read(data: string, T: type SomeMsg, maxBytes: int): T =
  17. result.data = data[0 ..< min(data.len, maxBytes)]
  18. proc nextMsg*(MsgType: typedesc,
  19. maxBytes: static[int]): Future[MsgType] {.async.} =
  20. const wantedId = MsgType.msgId
  21. while true:
  22. var (nextMsgId, nextMsgData) = await recvMsg()
  23. if nextMsgId == wantedId:
  24. return nextMsgData.read(MsgType, maxBytes)
  25. proc main {.async.} =
  26. let msg = await nextMsg(SomeMsg, 5)
  27. echo msg.data
  28. asyncCheck main()