Welcome to little lamb

Code » limb » release » tree

[release] / src / liblimb / djbunix.h / sa_readmax.c

/* This file is part of limb                           https://lila.oss/limb
 * Copyright (C) 2023 Olivier Brunel                          jjk@jjacky.com */
/* SPDX-License-Identifier: GPL-2.0-only */
#include <errno.h>
#include <limb/allreadwrite.h>
#include <limb/djbunix.h>

int
sa_readmax(stralloc *sa, int fd, size_t max)
{
    size_t salen = sa->len;
    for (;;)
    {
        size_t n = max && sa->len - salen + 4096 > max ? max - (sa->len - salen) : 4096;
        if (!n) {
            errno = ENOBUFS;
            break;
        }
        if (!stralloc_readyplus(sa, n)) break;

        ssize_t r = fd_read(fd, sa->s + sa->len, n) ;
        if (!r) return 1;
        else if (r == -1) break;
        sa->len += r;
    }

    sa->len = salen;
    return 0;
}