#include #include #include #include #include #include "system.h" #include "cmpbuf.h" /* Read |nbytes| bytes from descriptor |fd| into |buf|. |nbytes| must not be |SIZE_MAX|. Return the number of characters successfully read. On error, return |SIZE_MAX|, setting |errno|. The number returned is always |nbytes| unless end-of-file or error. */ size_t block_read(int fd, char *buf, size_t nbytes) { char *bp = buf; char const *buflim = buf + nbytes; size_t readlim = MIN (SSIZE_MAX, SIZE_MAX); do { size_t bytes_remaining = buflim - bp; size_t bytes_to_read = MIN (bytes_remaining, readlim); ssize_t nread = read(fd, bp, bytes_to_read); if (nread <= 0) { if (nread == 0) break; return SIZE_MAX; } bp += nread; } while (bp < buflim); return bp - buf; } /* Least common multiple of two buffer sizes |a| and |b|. However, if either |a| or |b| is zero, or if the multiple is greater than |lcm_max|, return a reasonable buffer size. */ size_t buffer_lcm(size_t a, size_t b, size_t lcm_max) { size_t lcm, m, n, q, r; /* Yield reasonable values if buffer sizes are zero. */ if (!a) return b ? b : 8 * 1024; if (!b) return a; /* |n = gcd (a, b)| */ for (m = a, n = b; (r = m % n) != 0; m = n, n = r) continue; /* Yield a if there is an overflow. */ q = a / n; lcm = q * b; return lcm <= lcm_max && lcm / b == q ? lcm : a; }