/* =============================================================================
 * 02_short_counts.c -- read() gives you what it has, not what you asked for
 * =============================================================================
 *
 * [Idea]
 *   You ask read() for 1000 bytes. It returns 100. Nothing is wrong: a "short
 *   count" means the data has not all arrived YET. On a disk file you rarely
 *   notice (only the last block is short); on a PIPE, SOCKET or terminal it is
 *   the normal case, because the other end is still sending.
 *
 *   This is the single most common source of "works on my file, breaks on the
 *   network" bugs. The demo creates a pipe, has a child write in slow chunks,
 *   and compares:
 *     (a) one raw read() asking for everything   -> gets a SHORT count
 *     (b) rio_readn() asking for everything      -> loops, gets it ALL
 *
 * [What it answers]
 *   - Why does read() return fewer bytes than requested?
 *   - What exactly does rio_readn do differently?
 *   - When is a short count NOT a short count? (return 0 = EOF; -1 = error)
 *
 * [Systems link]
 *   A pipe (Lecture 16's fork + this lecture's descriptors) is the simplest
 *   thing with a "writer who is still writing", so it reproduces on one machine
 *   what a slow network does between two.
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include "rio.h"

#define CHUNK  100      /* bytes the child writes per burst */
#define BURSTS 10       /* number of bursts -> CHUNK*BURSTS bytes in total */
#define TOTAL  (CHUNK * BURSTS)

int main(void)
{
    /* ---- experiment (a): a single raw read() on a trickling pipe ---------- */
    int p[2];
    if (pipe(p) < 0) { perror("pipe"); return 1; }
    /* p[0] is the read end, p[1] the write end. fork() gives the child copies
       of both descriptors; each side closes the end it does not use. */

    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {
        close(p[0]);
        char chunk[CHUNK];
        memset(chunk, 'x', sizeof(chunk));
        for (int i = 0; i < BURSTS; i++) {
            rio_writen(p[1], chunk, sizeof(chunk));
            usleep(20 * 1000);      /* 20 ms pause: the data trickles in */
        }
        close(p[1]);
        _exit(0);
    }
    close(p[1]);                    /* parent reads only */

    char buf[TOTAL + 1];
    /* Ask for ALL of it in one call, immediately -- long before the child has
       written it all. The kernel hands over whatever has arrived so far. */
    ssize_t one = read(p[0], buf, TOTAL);
    printf("[a] asked read() for %d bytes, got %zd  <-- a SHORT count\n",
           TOTAL, one);

    /* Collect the rest the naive way, to show how much was still coming. */
    ssize_t rest = 0, n;
    while ((n = read(p[0], buf, TOTAL)) > 0)
        rest += n;
    printf("[a] the remaining %zd bytes arrived in later read() calls\n", rest);
    printf("[a] total %zd; a program that trusted the first read would have\n",
           one + rest);
    printf("    silently lost %zd bytes\n", rest);
    close(p[0]);
    waitpid(pid, NULL, 0);

    /* ---- experiment (b): rio_readn on the same trickling pipe ------------ */
    if (pipe(p) < 0) { perror("pipe"); return 1; }
    pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {
        close(p[0]);
        char chunk[CHUNK];
        memset(chunk, 'y', sizeof(chunk));
        for (int i = 0; i < BURSTS; i++) {
            rio_writen(p[1], chunk, sizeof(chunk));
            usleep(20 * 1000);
        }
        close(p[1]);
        _exit(0);
    }
    close(p[1]);

    ssize_t got = rio_readn(p[0], buf, TOTAL);
    printf("[b] asked rio_readn() for %d bytes, got %zd  <-- COMPLETE\n",
           TOTAL, got);
    close(p[0]);
    waitpid(pid, NULL, 0);

    /* ---- what the two other return values mean --------------------------- */
    /* EOF: read a pipe whose write end is closed and empty -> 0, not an error. */
    if (pipe(p) == 0) {
        close(p[1]);                        /* no writer at all */
        ssize_t eof = read(p[0], buf, 10);
        printf("[c] read() on a pipe with no writer returned %zd  (0 = EOF)\n",
               eof);
        close(p[0]);
    }

    printf("\nObservations\n------------\n");
    printf("- the raw read() asked for %d and got %zd: it returns what is\n",
           TOTAL, one);
    printf("  AVAILABLE, not what you asked for. The exact number depends on\n");
    printf("  timing and changes between runs.\n");
    printf("- rio_readn() asked for %d and got %zd, because it loops over the\n",
           TOTAL, got);
    printf("  short counts until the request is satisfied or the stream ends.\n");
    printf("- three different return values, three different meanings:\n");
    printf("    > 0  this many bytes moved (maybe fewer than asked)\n");
    printf("    = 0  EOF -- the stream is over, no more data ever\n");
    printf("    < 0  a real error (check errno; EINTR just means 'retry')\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS) -- see README for the
 * exact numbers from a real run; the first read is always SHORT (far less than
 * 1000) and rio_readn always returns the full 1000.
 */
