cscvs to tla changeset 107
[onak.git] / charfuncs.c
1 /*
2  * charfuncs.c - Routines for dealing with character streams.
3  *
4  * Jonathan McDowell <noodles@earth.li>
5  *
6  * Copyright 2002 Project Purple
7  *
8  * $Id: charfuncs.c,v 1.4 2003/10/04 10:21:40 noodles Exp $
9  */
10
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/uio.h>
14 #include <unistd.h>
15
16 #include "charfuncs.h"
17
18 /**
19  *      buffer_fetchchar - Fetches a char from a buffer.
20  *      @ctx: Our buffer context structure.
21  *      @count: The number of characters to get from the buffer.
22  *      @c: Where to put the characters retrieved.
23  */
24 int buffer_fetchchar(void *ctx, size_t count, unsigned char *c)
25 {
26         struct buffer_ctx *buf = NULL;
27         size_t i;
28         
29         buf = (struct buffer_ctx *) ctx;
30         for (i = 0; i < count; i++) {
31                 c[i] = buf->buffer[buf->offset++];
32         }
33
34         return (((buf->offset) == (buf->size)) ? 1 : 0);
35 }
36
37 /**
38  *      buffer_putchar - Puts a char to a buffer.
39  *      @ctx: Our buffer context structure.
40  *      @count: The number of characters to put into the buffer.
41  *      @c: The characters to add to the buffer.
42  *
43  *      Adds characters to the buffer references by the buffer context. If we
44  *      fill it then we double the size of the current buffer and then add the
45  *      rest.
46  */
47 int buffer_putchar(void *ctx, size_t count, unsigned char *c)
48 {
49         struct buffer_ctx *buf = NULL;
50         size_t newsize = 0;
51         size_t i;
52         
53         buf = (struct buffer_ctx *) ctx;
54
55         for (newsize = buf->size; newsize < (buf->offset + count);
56                         newsize *= 2) ;
57
58         if (newsize != buf->size) {
59                 buf->buffer = realloc(buf->buffer, newsize);
60                 buf->size = newsize;
61         }
62         
63         for (i = 0; i < count; i++) {
64                 buf->buffer[buf->offset++] = c[i];
65         }
66
67         return 1;
68 }
69
70 /**
71  *      file_fetchchar - Fetches a char from a file.
72  */
73 int file_fetchchar(void *fd, size_t count, unsigned char *c)
74 {
75         return !(read( *(int *) fd, c, count));
76 }
77
78 /**
79  *      file_putchar - Puts a char to a file.
80  */
81 int file_putchar(void *fd, size_t count, unsigned char *c)
82 {
83         return !(write( *(int *) fd, c, count));
84 }
85
86 /**
87  *      stdin_getchar - Gets a char from stdin.
88  */
89 int stdin_getchar(void *ctx, size_t count, unsigned char *c)
90 {
91         return (fread(c, 1, count, stdin) != count);
92 }
93
94 /**
95  *      stdout_putchar - Puts a char to stdout.
96  */
97 int stdout_putchar(void *ctx, size_t count, unsigned char *c)
98 {
99         return (fwrite(c, 1, count, stdout) != count);
100 }