2 * charfuncs.c - Routines for dealing with character streams.
4 * Copyright 2002 Jonathan McDowell <noodles@earth.li>
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation; version 2 of the License.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program. If not, see <https://www.gnu.org/licenses/>.
23 #include "build-config.h"
24 #include "charfuncs.h"
27 * Fetches a char from a buffer.
28 * @ctx: Our buffer context structure.
29 * @count: The number of characters to get from the buffer.
30 * @c: Where to put the characters retrieved.
32 size_t buffer_fetchchar(void *ctx, size_t count, void *c)
34 struct buffer_ctx *buf = NULL;
36 buf = (struct buffer_ctx *) ctx;
38 if (buf->offset + count > buf->size) {
39 count = buf->size - buf->offset;
42 memcpy(c, &buf->buffer[buf->offset], count);
49 * buffer_putchar - Puts a char to a buffer.
50 * @ctx: Our buffer context structure.
51 * @count: The number of characters to put into the buffer.
52 * @c: The characters to add to the buffer.
54 * Adds characters to the buffer references by the buffer context. If we
55 * fill it then we double the size of the current buffer and then add the
58 size_t buffer_putchar(void *ctx, size_t count, void *c)
60 struct buffer_ctx *buf = NULL;
63 buf = (struct buffer_ctx *) ctx;
65 for (newsize = buf->size; newsize < (buf->offset + count);
68 if (newsize != buf->size) {
69 buf->buffer = realloc(buf->buffer, newsize);
73 memcpy(&buf->buffer[buf->offset], c, count);
80 * Fetches a char from a file.
82 size_t file_fetchchar(void *fd, size_t count, void *c)
84 ssize_t ret = read( *(int *) fd, c, count);
86 return (ret > 0) ? ret : 0;
90 * Puts a char to a file.
92 size_t file_putchar(void *fd, size_t count, void *c)
94 size_t ret = write( *(int *) fd, c, count);
96 return (ret > 0) ? ret : 0;
100 * Gets a char from stdin.
102 size_t stdin_getchar(__unused void *ctx, size_t count, void *c)
104 return fread(c, 1, count, stdin);
108 * Puts a char to stdout.
110 size_t stdout_putchar(__unused void *ctx, size_t count, void *c)
112 return fwrite(c, 1, count, stdout);