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))
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 uint 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, "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, uint 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(uint 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)
114 uint fbgrow_get_buf(struct fastbuf *b, byte **buf)
116 byte *end = FB_GBUF(b)->end;
117 end = MAX(end, b->bptr);
120 return end - b->buffer;
130 f = fbgrow_create(3);
131 for (uint i=0; i<5; i++)
134 bwrite(f, "12345", 5);
135 bwrite(f, "12345", 5);
136 printf("<%d>", (int)btell(f));
138 printf("<%d>", (int)btell(f));
140 printf("<%d>", (int)btell(f));
141 while ((t = bgetc(f)) != ~0U)
143 printf("<%d>", (int)btell(f));
145 bseek(f, -1, SEEK_END);
146 printf("<%d>", (int)btell(f));
147 while ((t = bgetc(f)) != ~0U)
149 printf("<%d>\n", (int)btell(f));