]> mj.ucw.cz Git - libucw.git/blob - ucw/fb-buffer.c
7fff1a1cfd94574bf4c1ce7f554c2cc0e827f471
[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 = (struct fastbuf) {
40     .buffer = buf,
41     .bptr = buf,
42     .bstop = buf + size,
43     .bufend = buf + size,
44     .name = "fbbuf-read",
45     .pos = size,
46     .refill = fbbuf_refill,
47     .seek = fbbuf_seek,
48     .can_overwrite_buffer = can_overwrite };
49 }
50
51 static void
52 fbbuf_spout(struct fastbuf *f)
53 {
54   bthrow(f, "fb.write", "fbbuf: buffer overflow on write");
55 }
56
57 void
58 fbbuf_init_write(struct fastbuf *f, byte *buf, uns size)
59 {
60   *f = (struct fastbuf) {
61     .buffer = buf,
62     .bstop = buf,
63     .bptr = buf,
64     .bufend = buf + size,
65     .name = "fbbuf-write",
66     .pos = size,
67     .spout = fbbuf_spout,
68   };
69 }
70
71 #ifdef TEST
72
73 int main(int argc, char *argv[])
74 {
75   if (argc < 2)
76     {
77       fprintf(stderr, "You must specify a test (r, w, o)\n");
78       return 1;
79     }
80   switch (*argv[1])
81     {
82       case 'r':
83         {
84           struct fastbuf fb;
85           char *data = "Two\nlines\n";
86           fbbuf_init_read(&fb, data, strlen(data), 0);
87           char buffer[10];
88           while (bgets(&fb, buffer, 10))
89             puts(buffer);
90           bclose(&fb);
91           break;
92         }
93       case 'w':
94         {
95           struct fastbuf fb;
96           char buff[20];
97           fbbuf_init_write(&fb, buff, 20);
98           bputs(&fb, "Hello world\n");
99           bputc(&fb, 0);
100           fputs(buff, stdout);
101           break;
102         }
103       case 'o':
104         {
105           struct fastbuf fb;
106           char buff[4];
107           fbbuf_init_write(&fb, buff, 4);
108           bputs(&fb, "Hello");
109           bputc(&fb, 0);
110           fputs(buff, stdout);
111           break;
112         }
113     }
114   return 0;
115 }
116
117 #endif