Add -1 to Debian package version
[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 <stdio.h>
10 #include <string.h>
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         
27         buf = (struct buffer_ctx *) ctx;
28         
29         memcpy(c, &buf->buffer[buf->offset], count);
30         buf->offset += count;
31
32         return (((buf->offset) == (buf->size)) ? 1 : 0);
33 }
34
35 /**
36  *      buffer_putchar - Puts a char to a buffer.
37  *      @ctx: Our buffer context structure.
38  *      @count: The number of characters to put into the buffer.
39  *      @c: The characters to add to the buffer.
40  *
41  *      Adds characters to the buffer references by the buffer context. If we
42  *      fill it then we double the size of the current buffer and then add the
43  *      rest.
44  */
45 int buffer_putchar(void *ctx, size_t count, unsigned char *c)
46 {
47         struct buffer_ctx *buf = NULL;
48         size_t newsize = 0;
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         memcpy(&buf->buffer[buf->offset], c, count);
61         buf->offset += count;
62         
63         return 1;
64 }
65
66 /**
67  *      file_fetchchar - Fetches a char from a file.
68  */
69 int file_fetchchar(void *fd, size_t count, unsigned char *c)
70 {
71         return !(read( *(int *) fd, c, count));
72 }
73
74 /**
75  *      file_putchar - Puts a char to a file.
76  */
77 int file_putchar(void *fd, size_t count, unsigned char *c)
78 {
79         return !(write( *(int *) fd, c, count));
80 }
81
82 /**
83  *      stdin_getchar - Gets a char from stdin.
84  */
85 int stdin_getchar(void *ctx, size_t count, unsigned char *c)
86 {
87         return (fread(c, 1, count, stdin) != count);
88 }
89
90 /**
91  *      stdout_putchar - Puts a char to stdout.
92  */
93 int stdout_putchar(void *ctx, size_t count, unsigned char *c)
94 {
95         return (fwrite(c, 1, count, stdout) != count);
96 }