Welcome to little lamb

Code » limb » release » tree

[release] / src / liblimb / buffer.h / buffer_getuptoc.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/buffer.h>
#include <limb/bytestr.h>

int
buffer_getuptoc(buffer *b, char *dst, size_t len, char c, size_t *got)
{
    if (*got > len) return (errno = EINVAL, 0);
    dst += *got;
    len -= *got;

    for (;;) {
        size_t n = buffer_getnofill(b, dst, len);
        if (n) {
            size_t e = byte_chr(dst, n, c);
            if (e++ < n) {
                *got += e;
                buffer_unget(b, n - e);
                return 1;
            }
            *got += n;
            if (*got >= len)
                return (errno = ENOBUFS, 0);
            dst += n;
            len -= n;
        }
        ssize_t r = buffer_fill(b);
        if (r <= 0) {
            if (!r) errno = EPIPE;
            return 0;
        }
    }
}