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