chan icon indicating copy to clipboard operation
chan copied to clipboard

primitive values

Open mattn opened this issue 11 years ago • 6 comments

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.

mattn avatar Sep 04 '14 02:09 mattn

:+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?

tylertreat avatar Sep 04 '14 03:09 tylertreat

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));

mattn avatar Sep 04 '14 04:09 mattn

I think this looks good. On Sep 3, 2014 11:22 PM, "mattn" [email protected] 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 avatar Sep 04 '14 04:09 tylertreat

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

tylertreat avatar Sep 05 '14 13:09 tylertreat

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.

tylertreat avatar Sep 09 '14 03:09 tylertreat

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

mattn avatar Sep 09 '14 13:09 mattn