Favourite Pattern for Processing Zero, Once, Multiple

S

Shao Miller

What you're doing seems much the same as what a compiler does, so you
could read up on how they do it. I think this stage is called lexical.

I'd be inclined to drop the whole idea of sending characters to your
function. Make the function return the next output character, or EOF
if it is actually the end of the input file, and leave the function to
read in as many characters as it needs to get an output character.
(This may be what you are getting at by talking about callbacks, but
there's no need to use a callback as such if there is only one other
function producing the input characters.) In short, write a function
that you can pull characters from, and which will in turn pull in the
characters it needs, instead of trying to push characters into the
function.

Thank you for the feed-back.

Yes indeed, the idea was that the 'bar' function knows how to translate,
and so is fed input characters, but their source is opaque to 'bar'.
The caller might provide input characters from a buffer, or might read
them from a stream, or who-knows-how-else.

And what to do with the output characters should also be opaque to
'bar'; it just translates.

The idea of passing one or more callbacks could certainly work, instead.
For example:

enum e_callback_result {
cv_yield,
cv_break,
cv_more
};

typedef enum e_callback_result f_callback(void *);

void translate(
void * context,
f_callback * next_input,
f_callback * next_output
) {
enum e_callback_result rv;

rv = cv_more;
while (rv != cv_break) {
while ((rv = next_input(context)) == cv_more)
continue;

if (rv == cv_break)
break;

while ((rv = next_output(context)) == cv_more)
continue;
}
}

Where the input fetching could yield after each input character, but the
output function might deliberately spin for a while. This is more
symmetrical than the "caller versus 'bar'" style. Is that worth
something, do you think? Or was it not quite the "pull in the character
it needs" that you had in mind?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top