NAME

inbuf -- buffered reading


SYNOPSIS

   #include <afblib/inbuf.h>
   typedef struct inbuf {
      int fd;
      stralloc buf;
      size_t pos;
   } inbuf;
   bool inbuf_alloc(inbuf* ibuf, size_t size);
   ssize_t inbuf_read(inbuf* ibuf, void* buf, size_t size);
   int inbuf_getchar(inbuf* ibuf);
   bool inbuf_back(inbuf* ibuf);
   void inbuf_free(inbuf* ibuf);


DESCRIPTION

These function provides a simple and efficient input buffering for reading from file descriptors. They are mainly useful for pipelines and network connections. In case of bidirectional communication channels, it might be useful to use the outbuf interface as well. An input and an output buffer can be used in parallel for the same file descriptor.

There is no such method called open or init. Instead, the structure needs to be initialized, either using an initializer, e.g.

   int fd;
   // fd = open(...);
   inbuf ibuf = {fd}; // the file descriptor is the first component

or by using a compound-literal (C99), e.g.

   int fd;
   inbuf ibuf;
   // fd = open(...);
   ibuf = (inbuf) {fd};

The function inbuf_alloc may be invoked to select a non-standard buffer size. Otherwise, a buffer of 512 bytes is allocated on the next invocation of inbuf_read or inbuf_getchar.

Reading is possible through the functions inbuf_read and inbuf_back. The former is close to the system call read(2) while inbuf_getchar is a convenient shortform for reading individual characters. Whenever a read operation was successful, at least one byte might be reread after the invocation of inbuf_back. inbuf_free frees the input buffer.

inbuf_read, if the input buffer needs to be filled, invokes read repeatedly whenever the system call got interrupted (errno = EINTR).


DIAGNOSTICS

inbuf_alloc returns 1 in case of success, 0 otherwise. inbuf_read return positive amounts indicating the number of bytes read in case of success, 0 in case of end of file, and -1 in case of errors. inbuf_getchar returns -1 in case of errors or end of file. Non-negative values represent the character read. inbuf_back returns 1 on success and 0 otherwise.


EXAMPLE

The following sample reads character-wise from standard input (file descriptor 0):

   inbuf ibuf = {0};
   int ch;
   while ((ch = inbuf_getchar(&ibuf)) >= 0) {
      // process ch
   }


AUTHOR

Andreas F. Borchert