2 * Sherlock Library -- Fast Buffered I/O on Memory Streams
4 * (c) 1997--2000 Martin Mares <mj@ucw.cz>
8 #include "lib/fastbuf.h"
16 struct msblock *first;
26 fbmem_refill(struct fastbuf *f)
28 struct memstream *s = f->lldata;
29 struct msblock *b = f->llpos;
37 else if (f->buffer == b->data && f->bstop < b->data + b->size)
39 f->bstop = b->data + b->size;
49 f->buffer = f->bptr = b->data;
50 f->bufend = f->bstop = b->data + b->size;
56 fbmem_spout(struct fastbuf *f)
58 struct memstream *s = f->lldata;
59 struct msblock *b = f->llpos;
64 b->size = f->bptr - b->data;
65 if (b->size < s->blocksize)
69 bb = xmalloc(sizeof(struct msblock) + s->blocksize);
76 f->buffer = f->bptr = f->bstop = bb->data;
77 f->bufend = bb->data + s->blocksize;
82 fbmem_seek(struct fastbuf *f, sh_off_t pos, int whence)
84 struct memstream *m = f->lldata;
88 if (whence != SEEK_SET)
89 die("fbmem_seek: only SEEK_SET supported");
90 for (b=m->first; b; b=b->next)
92 if ((unsigned) pos <= p + b->size) /* <=, because we need to be able to seek just after file end */
96 f->bptr = b->data + (pos - p);
97 f->bufend = f->bstop = b->data + b->size;
103 die("fbmem_seek to invalid offset");
107 fbmem_close(struct fastbuf *f)
109 struct memstream *m = f->lldata;
124 fbmem_create(unsigned blocksize)
126 struct fastbuf *f = xmalloc_zero(sizeof(struct fastbuf));
127 struct memstream *m = xmalloc_zero(sizeof(struct memstream));
129 m->blocksize = blocksize;
132 f->name = "<fbmem-write>";
134 f->spout = fbmem_spout;
135 f->close = fbmem_close;
140 fbmem_clone_read(struct fastbuf *b)
142 struct fastbuf *f = xmalloc_zero(sizeof(struct fastbuf));
143 struct memstream *s = b->lldata;
148 f->name = "<fbmem-read>";
150 f->refill = fbmem_refill;
151 f->seek = fbmem_seek;
152 f->close = fbmem_close;
160 struct fastbuf *w, *r;
164 r = fbmem_clone_read(w);
165 bwrite(w, "12345", 5);
166 bwrite(w, "12345", 5);
167 printf("<%d>", btell(w));
169 printf("<%d>", btell(w));
170 printf("<%d>", btell(r));
171 while ((t = bgetc(r)) >= 0)
173 printf("<%d>", btell(r));
174 bwrite(w, "12345", 5);
175 bwrite(w, "12345", 5);
176 printf("<%d>", btell(w));
179 printf("<!%d>", btell(r));
180 while ((t = bgetc(r)) >= 0)
183 printf("<!%d>", btell(r));
184 while ((t = bgetc(r)) >= 0)