cscvs to tla changeset 27
[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
9 #include <sys/types.h>
10 #include <sys/uio.h>
11 #include <unistd.h>
12
13 #include "charfuncs.h"
14
15 /**
16  *      buffer_fetchchar - Fetches a char from a buffer.
17  *      @ctx: Our buffer context structure.
18  *      @count: The number of characters to get from the buffer.
19  *      @c: Where to put the characters retrieved.
20  */
21 int buffer_fetchchar(void *ctx, size_t count, unsigned char *c)
22 {
23         struct buffer_ctx *buf = NULL;
24         int i;
25         
26         buf = (struct buffer_ctx *) ctx;
27         for (i = 0; i < count; i++) {
28                 c[i] = buf->buffer[buf->offset++];
29         }
30
31         return (((buf->offset) == (buf->size)) ? 1 : 0);
32 }
33
34 /**
35  *      buffer_putchar - Puts a char to a buffer.
36  *      @ctx: Our buffer context structure.
37  *      @count: The number of characters to put into the buffer.
38  *      @c: The characters to add to the buffer.
39  *
40  *      Adds characters to the buffer references by the buffer context. If we
41  *      fill it then we double the size of the current buffer and then add the
42  *      rest.
43  */
44 int buffer_putchar(void *ctx, size_t count, unsigned char *c)
45 {
46         struct buffer_ctx *buf = NULL;
47         size_t newsize = 0;
48         int i;
49         
50         buf = (struct buffer_ctx *) ctx;
51
52         for (newsize = buf->size; newsize < (buf->offset + count);
53                         newsize *= 2) ;
54
55         if (newsize != buf->size) {
56                 buf->buffer = realloc(buf->buffer, newsize);
57                 buf->size = newsize;
58         }
59         
60         for (i = 0; i < count; i++) {
61                 buf->buffer[buf->offset++] = c[i];
62         }
63
64         return 1;
65 }
66
67 /**
68  *      file_fetchchar - Fetches a char from a file.
69  */
70 int file_fetchchar(void *fd, size_t count, unsigned char *c)
71 {
72         return !(read( *(int *) fd, c, count));
73 }
74
75 /**
76  *      file_putchar - Puts a char to a file.
77  */
78 int file_putchar(void *fd, size_t count, unsigned char *c)
79 {
80         return !(write( *(int *) fd, c, count));
81 }