]> mj.ucw.cz Git - libucw.git/blob - ucw/fb-buffer.c
Fastbuf: fbbuf_seek bugfix
[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     .pos = size,
69     .spout = fbbuf_spout,
70   };
71 }
72
73 #ifdef TEST
74
75 int main(int argc, char *argv[])
76 {
77   if (argc < 2)
78     {
79       fprintf(stderr, "You must specify a test (r, w, o)\n");
80       return 1;
81     }
82   switch (*argv[1])
83     {
84       case 'r':
85         {
86           struct fastbuf fb;
87           char *data = "Two\nlines\n";
88           fbbuf_init_read(&fb, data, strlen(data), 0);
89           char buffer[10];
90           while (bgets(&fb, buffer, 10))
91             puts(buffer);
92           bclose(&fb);
93           break;
94         }
95       case 'w':
96         {
97           struct fastbuf fb;
98           char buff[20];
99           fbbuf_init_write(&fb, buff, 20);
100           bputs(&fb, "Hello world\n");
101           bputc(&fb, 0);
102           fputs(buff, stdout);
103           break;
104         }
105       case 'o':
106         {
107           struct fastbuf fb;
108           char buff[4];
109           fbbuf_init_write(&fb, buff, 4);
110           bputs(&fb, "Hello");
111           bputc(&fb, 0);
112           fputs(buff, stdout);
113           break;
114         }
115     }
116   return 0;
117 }
118
119 #endif