summaryrefslogtreecommitdiff
path: root/core/readbuf.c
blob: ee10362f8a495443dbc3e1ddc25d6418622829e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
 * Copyright (c) 2026, Chloe M.
 * Provided under the BSD-3 clause
 */

#include <stdint.h>
#include <stddef.h>
#include <errno.h>
#include <unistd.h>
#include "cescal/readbuf.h"

int
readbuf_init(struct readbuf *rb)
{
    if (rb == NULL) {
        errno = EINVAL;
        return -1;
    }

    rb->size = 0;
    rb->tail = 0;
    return 0;
}

char
readbuf_read(struct readbuf *rb, int fd)
{
    ssize_t nread = -1;

    if (rb == NULL || fd < 0) {
        errno = EINVAL;
        return '\0';
    }

#define N_RESIDUAL(rb) ((rb)->size - (rb)->tail)
    if (N_RESIDUAL(rb) == 0 || rb->size == 0) {
        if ((nread = read(fd, rb->buf, READBUF_CAP)) <= 0)
            return nread;

        rb->size = nread;
        rb->tail = 0;
    }
#undef N_RESIDUAL

    return rb->buf[rb->tail++];
}