comparison src/core/rbuf.c @ 120:b3429b26d60d

core: add rbuf utility, closes #2488 @2h
author David Demelier <markand@malikania.fr>
date Mon, 05 Oct 2020 13:05:09 +0200
parents
children
comparison
equal deleted inserted replaced
119:43e04bf2c350 120:b3429b26d60d
1 /*
2 * rbuf.c -- basic utility for reading input buffers
3 *
4 * Copyright (c) 2020 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <assert.h>
20
21 #include "rbuf.h"
22
23 void
24 rbuf_open(struct rbuf *rb, const void *data, size_t datasz)
25 {
26 assert(rb);
27 assert(data);
28
29 rb->s = data;
30 rb->e = rb->s + datasz;
31 }
32
33 bool
34 rbuf_readline(struct rbuf *rb, char *output, size_t outputsz)
35 {
36 assert(rb);
37 assert(output);
38 assert(outputsz > 0);
39
40 if (rb->s == rb->e)
41 return false;
42
43 for (--outputsz; rb->s != rb->e && *rb->s != '\n' && outputsz; outputsz--)
44 *output++ = *rb->s++;
45
46 /* Not enough space? */
47 if (!outputsz && rb->s != rb->e && *rb->s != '\n')
48 return false;
49
50 /* Remove this '\n' if still present. */
51 if (rb->s != rb->e && *rb->s == '\n')
52 rb->s++;
53
54 *output = '\0';
55
56 return true;
57 }