Recursive coroutines in C (C99)

When implementing the communication protocol, we have an encoder that recursively traverses some structures and encodes them into a binary message.

So far so good, but now the buffer should split into several pieces of a fixed size, for example. The top size of the receive buffer. Since the allocation of memory for a complete message and its reduction, therefore, seems too wasteful (the size of the message - in theory - is not limited), now the idea is to implement a coroutine using setjmp / longjmp.

At the moment, I have a prototype with two transition buffers - one buffer to resume the encoding function, and the second one to simulate the return behavior of the function in order to return to the caller.

Well, it seems to have worked, but the code looks like it is right from hell. Are there any β€œconventions” for implementing intermittent recursive functions, maybe a set of macros or something else? I would like to use only standard features, without built-in asm, to stay portable.

Addition: The prototype is here: https://github.com/open62541/open62541/compare/master...chunking_longjmp "Usage" is shown inside the unit test. Currently, the coprocessor behavior is implemented for the non-recursive function Array_encodeBinary . However, the 'coroutine' behavior should be extended to the general recursive function UA_encodeBinary , located here: https://github.com/open62541/open62541/blob/master/src/ua_types_encoding_binary.c#L1029

+5
source share
1 answer

As Olaf noted, the easiest way would be to use an iterative algorithm. However, if for some reason this is complicated, you can always model a recursive algorithm using the stack container and while . This at least facilitates interruption of the function. A pretty good article on how to implement it can be found here . The article is written for C ++, but it is not difficult to convert it to c.

+1
source

Source: https://habr.com/ru/post/1239453/


All Articles