/* =============================================================================
 * rio.c -- implementation of the RIO package (see rio.h for the why)
 * =============================================================================
 *
 * Read rio.h first. The whole package is three ideas:
 *   1. loop until you have all n bytes (short counts are normal, not errors);
 *   2. retry on EINTR (a signal interrupted us; nothing failed);
 *   3. keep a buffer so reading a line does not cost one syscall per byte.
 * -----------------------------------------------------------------------------
 */
#include "rio.h"

#include <errno.h>
#include <string.h>
#include <unistd.h>

/* ---------------------------------------------------------------------------
 * rio_readn -- read exactly n bytes (unbuffered)
 * ---------------------------------------------------------------------------
 * [Idea] Keep calling read() until we have n bytes, EOF, or a real error.
 *        Each call may transfer fewer than we asked, so we advance the pointer
 *        by however much we actually got and ask for the rest.
 */
ssize_t rio_readn(int fd, void *buf, size_t n)
{
    size_t nleft = n;           /* bytes still wanted */
    char  *bufp  = buf;         /* where the next byte goes */

    while (nleft > 0) {
        ssize_t nread = read(fd, bufp, nleft);
        if (nread < 0) {
            if (errno == EINTR)
                continue;       /* [Systems link] a signal (L17) interrupted us
                                   before any data moved -- just call again. */
            return -1;          /* a genuine error */
        }
        if (nread == 0)
            break;              /* EOF: the stream ended early -> short count */
        nleft -= (size_t)nread; /* this is the short-count handling: believe the
                                   kernel about how much it actually gave us */
        bufp  += nread;
    }
    return (ssize_t)(n - nleft);    /* n normally; < n if we hit EOF */
}

/* ---------------------------------------------------------------------------
 * rio_writen -- write exactly n bytes (unbuffered)
 * ---------------------------------------------------------------------------
 * [Idea] Same loop. A write to a pipe or socket can accept only part of the
 *        data (the kernel buffer filled up), so we must re-offer the rest.
 * [Returns] n, or -1. There is no "EOF" when writing, so no short success.
 */
ssize_t rio_writen(int fd, const void *buf, size_t n)
{
    size_t      nleft = n;
    const char *bufp  = buf;

    while (nleft > 0) {
        ssize_t nwritten = write(fd, bufp, nleft);
        if (nwritten <= 0) {
            if (nwritten < 0 && errno == EINTR)
                continue;       /* interrupted by a signal: retry */
            return -1;
        }
        nleft -= (size_t)nwritten;
        bufp  += nwritten;
    }
    return (ssize_t)n;
}

/* ---------------------------------------------------------------------------
 * rio_read -- the internal buffered read (not public)
 * ---------------------------------------------------------------------------
 * [Idea] Hand out bytes from rio_buf. When the buffer is empty, refill it with
 *        ONE big read(). This is what turns "one syscall per character" into
 *        "one syscall per 8 KB" for line-oriented input.
 * [Returns] how many bytes were copied out (<= n), 0 at EOF, -1 on error.
 */
static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n)
{
    while (rp->rio_cnt <= 0) {              /* buffer empty -> refill */
        rp->rio_cnt = (int)read(rp->rio_fd, rp->rio_buf, sizeof(rp->rio_buf));
        if (rp->rio_cnt < 0) {
            if (errno != EINTR)
                return -1;
            /* interrupted by a signal: loop around and read again */
        } else if (rp->rio_cnt == 0) {
            return 0;                       /* EOF */
        } else {
            rp->rio_bufptr = rp->rio_buf;   /* reset pointer to the fresh data */
        }
    }

    /* Copy out the smaller of "what was asked" and "what we have buffered". */
    size_t cnt = n;
    if ((size_t)rp->rio_cnt < n)
        cnt = (size_t)rp->rio_cnt;
    memcpy(usrbuf, rp->rio_bufptr, cnt);
    rp->rio_bufptr += cnt;
    rp->rio_cnt    -= (int)cnt;
    return (ssize_t)cnt;
}

/* ---------------------------------------------------------------------------
 * rio_readinitb -- attach a buffered reader to a descriptor
 * --------------------------------------------------------------------------- */
void rio_readinitb(rio_t *rp, int fd)
{
    rp->rio_fd     = fd;
    rp->rio_cnt    = 0;                 /* buffer starts empty */
    rp->rio_bufptr = rp->rio_buf;
}

/* ---------------------------------------------------------------------------
 * rio_readlineb -- read one text line, up to and including '\n'
 * ---------------------------------------------------------------------------
 * [Idea] Pull bytes one at a time FROM THE BUFFER (cheap -- no syscall) until
 *        we see a newline, run out of room, or hit EOF. Always NUL-terminate so
 *        the caller can treat it as a C string.
 */
ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen)
{
    char *bufp = usrbuf;
    size_t n;
    char c;

    for (n = 1; n < maxlen; n++) {          /* leave room for the NUL */
        ssize_t rc = rio_read(rp, &c, 1);
        if (rc == 1) {
            *bufp++ = c;
            if (c == '\n') {                /* end of line: keep the '\n' */
                n++;
                break;
            }
        } else if (rc == 0) {
            if (n == 1)
                return 0;                   /* EOF, no data read at all */
            break;                          /* EOF after some data: a last line
                                               with no trailing newline */
        } else {
            return -1;                      /* error */
        }
    }
    *bufp = '\0';                           /* [C tip] always NUL-terminate */
    return (ssize_t)(n - 1);                /* bytes of text, excluding the NUL */
}

/* ---------------------------------------------------------------------------
 * rio_readnb -- read exactly n bytes through the buffered reader
 * ---------------------------------------------------------------------------
 * [Idea] Like rio_readn, but takes its bytes from the rio_t buffer, so it can
 *        be mixed with rio_readlineb on the same stream (e.g. read HTTP headers
 *        line by line, then read the body as a block).
 */
ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n)
{
    size_t nleft = n;
    char  *bufp  = usrbuf;

    while (nleft > 0) {
        ssize_t nread = rio_read(rp, bufp, nleft);
        if (nread < 0)
            return -1;
        if (nread == 0)
            break;                          /* EOF -> short count */
        nleft -= (size_t)nread;
        bufp  += nread;
    }
    return (ssize_t)(n - nleft);
}
