/packedArgs

a convention mainly created for `createThread` proc

Primary LanguageNim

packedArgs!

The Problem

Note: Channels are designed for the Thread type. They are unstable when used with spawn :: Nim doc for channles

the problem is that spawn can block and programms that use channels usually assume that it cannot block :: Araq on discord channel

So this brings us to createThread. But the bad thing about createThread is that you can't pass multiply arguments for your proc. you have to pack them (arguments) inside a tuple/object, ... and then pass it.

The Solution

this library aims to eliminite this limitation via packedArgs macro. this macro creates a duplicated proc that has packed parameters [as a tuple].

Assume you have a proc named myProc like this and you apply packedArgs to it:

proc myProc(a, b = 1; c: bool): string {.packedArgs.} =
  ...

the generated code will be:

proc myProc(a, b = 1; c: bool): string =
  ...

type MyProcArgs = tuple[a, b: typeof 1, c: bool]

proc toMyProcArgs(a, b = 1; c: bool): MyProcArgs =
  (a, b, c)

proc myProcPacked(args: MyProcArgs): string =
  myProc(args.a, args.b, args.c)

usage:

myProcPacked(toMyProcArgs(1, 2, true)) # same as myProc(1, 2, true)

or there is macro genPackedArgsFor to use after routine declaration.

macro genPackedArgsFor(routineIdent: typed, exported: static[bool]): untyped

usage:

proc work(something: bool): float = discard
genPackedArgsFor(work, true)

Becuase this is a little trickier, use unpackArgs when it's possible.

Features

  • export: if the proc exported itself, the generated type/procs are exported too
  • generics: nothing new, see tests/test.nim to make sure