Skip to content

Instantly share code, notes, and snippets.

@aprell
Created October 23, 2012 10:43
Show Gist options
  • Save aprell/3938121 to your computer and use it in GitHub Desktop.
Save aprell/3938121 to your computer and use it in GitHub Desktop.
Range: Iterate through all values received on a channel
#include "channel.h"
// Example use:
// channel_range(chan, &val) {
// do sth with val
// }
#define unique_name_paste(id, n) id ##_## n
#define unique_name(id, n) unique_name_paste(id, n)
#define channel_range(c, p) \
bool unique_name(__got_val_from_chan, __LINE__); \
unique_name(L, __LINE__): \
unique_name(__got_val_from_chan, __LINE__) = false; \
/* As long as the channel is not closed and nonempty */ \
while (!channel_closed(c) || channel_peek(c)) { \
if (!channel_receive(c, p, sizeof(*(p)))) { \
continue; \
} else { \
unique_name(__got_val_from_chan, __LINE__) = true; \
break; \
} \
} \
/* Use of goto in for requires a statement expression */ \
for (; unique_name(__got_val_from_chan, __LINE__); ({ goto unique_name(L, __LINE__); }))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment