]> mj.ucw.cz Git - libucw.git/blob - ucw/fb-buffer.c
Opt: Updated symbol renames
[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)
18 {
19   f->bstop = f->bufend;
20   f->pos = f->bstop - f->buffer;
21   return f->bptr < f->bstop;
22 }
23
24 static int
25 fbbuf_seek(struct fastbuf *f, ucw_off_t pos, int whence)
26 {
27   /* Somebody might want to seek to the end of buffer, try to be nice to him. */
28   ucw_off_t len = f->bufend - f->buffer;
29   if (whence == SEEK_END)
30     pos += len;
31   if (pos < 0 || pos > len)
32     bthrow(f, "seek", "Seek out of range");
33   f->bstop = f->bptr = f->buffer + pos;
34   f->pos = pos;
35   return 1;
36 }
37
38 void
39 fbbuf_init_read(struct fastbuf *f, byte *buf, uns size, uns can_overwrite)
40 {
41   *f = (struct fastbuf) {
42     .buffer = buf,
43     .bptr = buf,
44     .bstop = buf + size,
45     .bufend = buf + size,
46     .name = "fbbuf-read",
47     .pos = size,
48     .refill = fbbuf_refill,
49     .seek = fbbuf_seek,
50     .can_overwrite_buffer = can_overwrite };
51 }
52
53 static void
54 fbbuf_spout(struct fastbuf *f)
55 {
56   bthrow(f, "write", "fbbuf: buffer overflow on write");
57 }
58
59 void
60 fbbuf_init_write(struct fastbuf *f, byte *buf, uns size)
61 {
62   *f = (struct fastbuf) {
63     .buffer = buf,
64     .bstop = buf,
65     .bptr = buf,
66     .bufend = buf + size,
67     .name = "fbbuf-write",
68     .spout = fbbuf_spout,
69   };
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