2 * UCW Library -- Fast Buffered I/O on Growing Buffers
4 * (c) 2006 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "ucw/fastbuf.h"
12 #include "ucw/mempool.h"
22 #define FB_GBUF(f) ((struct fb_gbuf *)(f)->is_fastbuf)
24 static int fbgrow_refill(struct fastbuf *b)
26 b->bstop = FB_GBUF(b)->end;
27 b->pos = b->bstop - b->buffer;
28 return b->bstop > b->bptr;
31 static void fbgrow_spout(struct fastbuf *b)
33 if (b->bptr == b->bufend)
35 uns len = b->bufend - b->buffer;
38 byte *old = b->buffer;
39 b->buffer = mp_alloc(FB_GBUF(b)->mp, 2 * len);
40 memcpy(b->buffer, old, len);
43 b->buffer = xrealloc(b->buffer, 2 * len);
44 b->bufend = b->buffer + 2 * len;
45 FB_GBUF(b)->end = b->bptr = b->buffer + len;
47 else if (FB_GBUF(b)->end < b->bptr)
48 FB_GBUF(b)->end = b->bptr;
53 static int fbgrow_seek(struct fastbuf *b, ucw_off_t pos, int whence)
55 ucw_off_t len = FB_GBUF(b)->end - b->buffer;
56 if (whence == SEEK_END)
58 if (pos < 0 || pos > len)
59 bthrow(b, "fb.seek", "Seek out of range");
60 b->bptr = b->buffer + pos;
66 static void fbgrow_close(struct fastbuf *b)
72 struct fastbuf *fbgrow_create_mp(struct mempool *mp, unsigned basic_size)
78 b = mp_alloc_zero(mp, sizeof(struct fb_gbuf));
79 b->buffer = mp_alloc(mp, basic_size);
84 b = xmalloc_zero(sizeof(struct fb_gbuf));
85 b->buffer = xmalloc(basic_size);
86 b->close = fbgrow_close;
88 b->bufend = b->buffer + basic_size;
89 b->bptr = b->bstop = b->buffer;
91 b->refill = fbgrow_refill;
92 b->spout = fbgrow_spout;
93 b->seek = fbgrow_seek;
94 b->can_overwrite_buffer = 1;
98 struct fastbuf *fbgrow_create(unsigned basic_size)
100 return fbgrow_create_mp(NULL, basic_size);
103 void fbgrow_reset(struct fastbuf *b)
105 FB_GBUF(b)->end = b->bptr = b->bstop = b->buffer;
109 void fbgrow_rewind(struct fastbuf *b)
121 f = fbgrow_create(3);
122 for (uns i=0; i<5; i++)
125 bwrite(f, "12345", 5);
126 bwrite(f, "12345", 5);
127 printf("<%d>", (int)btell(f));
129 printf("<%d>", (int)btell(f));
131 printf("<%d>", (int)btell(f));
132 while ((t = bgetc(f)) != ~0U)
134 printf("<%d>", (int)btell(f));
136 bseek(f, -1, SEEK_END);
137 printf("<%d>", (int)btell(f));
138 while ((t = bgetc(f)) != ~0U)
140 printf("<%d>\n", (int)btell(f));