]> mj.ucw.cz Git - libucw.git/blob - ucw/fb-buffer.c
Renamed cf_write_item() to cf_modify_item().
[libucw.git] / ucw / fb-buffer.c
1 /*
2  *      UCW Library -- Fast Buffered I/O on Static Buffers
3  *
4  *      (c) 2003--2006 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "ucw/lib.h"
11 #include "ucw/fastbuf.h"
12
13 #include <stdio.h>
14 #include <stdlib.h>
15
16 static int
17 fbbuf_refill(struct fastbuf *f UNUSED)
18 {
19   return 0;
20 }
21
22 static int
23 fbbuf_seek(struct fastbuf *f, ucw_off_t pos, int whence)
24 {
25   /* Somebody might want to seek to the end of buffer, try to be nice to him. */
26   ucw_off_t len = f->bufend - f->buffer;
27   if (whence == SEEK_END)
28     pos += len;
29   ASSERT(pos >= 0 && pos <= len);
30   f->bptr = f->buffer + pos;
31   f->bstop = f->bufend;
32   f->pos = len;
33   return 1;
34 }
35
36 void
37 fbbuf_init_read(struct fastbuf *f, byte *buf, uns size, uns can_overwrite)
38 {
39   f->buffer = f->bptr = buf;
40   f->bstop = f->bufend = buf + size;
41   f->name = "fbbuf-read";
42   f->pos = size;
43   f->refill = fbbuf_refill;
44   f->spout = NULL;
45   f->seek = fbbuf_seek;
46   f->close = NULL;
47   f->config = NULL;
48   f->can_overwrite_buffer = can_overwrite;
49 }
50
51 static void
52 fbbuf_spout(struct fastbuf *f UNUSED)
53 {
54   die("fbbuf: buffer overflow on write");
55 }
56
57 void
58 fbbuf_init_write(struct fastbuf *f, byte *buf, uns size)
59 {
60   f->buffer = f->bstop = f->bptr = buf;
61   f->bufend = buf + size;
62   f->name = "fbbuf-write";
63   f->pos = size;
64   f->refill = NULL;
65   f->spout = fbbuf_spout;
66   f->seek = NULL;
67   f->close = NULL;
68   f->config = NULL;
69   f->can_overwrite_buffer = 0;
70 }
71
72 #ifdef TEST
73
74 int main(int argc, char *argv[])
75 {
76   if (argc < 2)
77     {
78       fprintf(stderr, "You must specify a test (r, w, o)\n");
79       return 1;
80     }
81   switch (*argv[1])
82     {
83       case 'r':
84         {
85           struct fastbuf fb;
86           char *data = "Two\nlines\n";
87           fbbuf_init_read(&fb, data, strlen(data), 0);
88           char buffer[10];
89           while (bgets(&fb, buffer, 10))
90             puts(buffer);
91           bclose(&fb);
92           break;
93         }
94       case 'w':
95         {
96           struct fastbuf fb;
97           char buff[20];
98           fbbuf_init_write(&fb, buff, 20);
99           bputs(&fb, "Hello world\n");
100           bputc(&fb, 0);
101           fputs(buff, stdout);
102           break;
103         }
104       case 'o':
105         {
106           struct fastbuf fb;
107           char buff[4];
108           fbbuf_init_write(&fb, buff, 4);
109           bputs(&fb, "Hello");
110           bputc(&fb, 0);
111           fputs(buff, stdout);
112           break;
113         }
114     }
115   return 0;
116 }
117
118 #endif