tylertreat / chan

Pure C implementation of Go channels.
Apache License 2.0
1.41k stars 119 forks source link

primitive values #7

Open mattn opened 10 years ago

mattn commented 10 years ago

Currently, chan provides chan_send to send data by void* argument. But someone may want to send int/long/double/char etc. How do you think? And I worry about someone may mistake to use chan and argument pointer. For example.

char buf[256];
while (!chan_is_closed(c)) {
  if (condition) {
    strcpy(buf, "doA");
  } else {
    strcpy(buf, "doB");
  }
  chan_send(c, p);
}

If the chan is possible to do buffering, the buf will be overwritten. It need to allocation new memory for each sending. My suggestion is adding new function like below.

chan_send_string(c, buf);
chan_recv_string(c);
chan_send_int(c, 3);
chan_recv_int(c);
chan_send_double(c, 4.5);
chan_recv_double(c);

This functions allocate new memory for the types. chan_recv_int, chan_recv_double is possible to free the memory automatically. chan_recv_string will be required to free memory by developers.

tylertreat commented 10 years ago

:+1: Yes, this would be a good addition to the API. I think send would look something like this:

int chan_send_int(chan_t* chan, int data)
{
    int* wrapped = malloc(sizeof(int));
    *wrapped = data;

    int success = chan_send(chan, wrapped);
    if (success != 0)
    {
        free(wrapped);
    }

    return success;
}

What I'm not sure about is how recv should work. chan_recv currently takes a pointer that it sets so it can return an int to indicate success. I'm thinking the other recv functions should work similarly.

Thoughts?

mattn commented 10 years ago

Right. Or how about this? This is way to hide freeing code.

int n;
char buf[256];
chan_recv_int(c, &n);
chan_recv_string(c, buf, sizeof(buf));
tylertreat commented 10 years ago

I think this looks good. On Sep 3, 2014 11:22 PM, "mattn" notifications@github.com wrote:

Right. Or how about this? This is way to hide freeing code.

int n;char buf[256];chan_recv_int(c, &n);chan_recv_string(c, buf, sizeof(buf));

— Reply to this email directly or view it on GitHub https://github.com/tylertreat/chan/issues/7#issuecomment-54405401.

tylertreat commented 10 years ago

Based on discussion in this PR, I think we will look at making channels "typed."

tylertreat commented 10 years ago

So, thinking more about typed channels, I'm wondering how useful it would actually be to store the type on chan_t? If typed channels is the way we want to go, it seems like we would need to define a chan_t for each type: int, double, char, etc.

mattn commented 10 years ago

Agreed. We will have to add new types for each users want.