D. J. Bernstein

The buffer_put library interface

Buffered output

     #include <buffer.h>


     buffer b;
     char *x;
     unsigned int len;
buffer_put appends x[0], x[1], ..., x[len-1] to a string stored in preallocated space. buffer_flush feeds the string to a write operation and then empties the string. buffer_put calls buffer_flush automatically if it runs out of space.

The preallocated space and the write operation are specified by b. You must initialize b as described below before calling buffer_put or buffer_flush.

On success, buffer_put and buffer_flush return 0. On error, buffer_put and buffer_flush return -1, setting errno appropriately.

buffer_putalign is similar to buffer_put. The difference is that, when there isn't enough space for new data, buffer_put calls buffer_flush before copying any data, while buffer_putalign fills all available space with data before calling buffer_flush.

buffer_putflush is similar to buffer_put followed by buffer_flush.

buffer_puts, buffer_putsalign, and buffer_putsflush are just like buffer_put, buffer_putalign, and buffer_putflush with len determined as the number of bytes before the first \0 in x.


     #include <buffer.h>


     buffer b;
     int (*op)(int,char *,int);
     int fd;
     char *y;
     unsigned int ylen;
buffer_init prepares b to store a string in y[0], y[1], ..., y[ylen-1]. Initially the string is empty.

buffer_init also prepares b to use the write operation specified by op and fd. buffer_flush feeds a string d[0], d[1], ..., d[dlen-1] to the write operation by calling

If op successfully handles one or more bytes at the beginning of the string, it must return the number of bytes handled; if this number is smaller than dlen, buffer_flush will call op again with the rest of the string. If op does not handle any bytes, and does not encounter an error, it must return 0, or return -1 with errno set to error_intr; in either case, buffer_flush will immediately call op again. If op encounters an error, it must return -1 with errno set to something other than error_intr; buffer_flush will pass the error to the caller.

You can use

     buffer b = BUFFER_INIT(op,fd,y,ylen);
to initialize b statically if op, fd, y, and ylen are compile-time constants.

You can call buffer_init again at any time. Note that this discards the currently buffered string.