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;
51 f->buffer = f->bptr = b->data;
52 f->bufend = f->bstop = b->data + b->size;
58 fbmem_spout(struct fastbuf *f)
60 struct memstream *s = f->lldata;
61 struct msblock *b = f->llpos;
66 b->size = f->bptr - b->data;
67 if (b->size < s->blocksize)
71 bb = xmalloc(sizeof(struct msblock) + s->blocksize);
78 f->buffer = f->bptr = f->bstop = bb->data;
79 f->bufend = bb->data + s->blocksize;
84 fbmem_seek(struct fastbuf *f, sh_off_t pos, int whence)
86 struct memstream *m = f->lldata;
90 if (whence != SEEK_SET)
91 die("fbmem_seek: only SEEK_SET supported");
92 for (b=m->first; b; b=b->next)
94 if ((unsigned) pos <= p + b->size) /* <=, because we need to be able to seek just after file end */
98 f->bptr = b->data + (pos - p);
99 f->bufend = f->bstop = b->data + b->size;
105 die("fbmem_seek to invalid offset");
109 fbmem_close(struct fastbuf *f)
111 struct memstream *m = f->lldata;
126 fbmem_create(unsigned blocksize)
128 struct fastbuf *f = xmalloc_zero(sizeof(struct fastbuf));
129 struct memstream *m = xmalloc_zero(sizeof(struct memstream));
131 m->blocksize = blocksize;
134 f->name = "<fbmem-write>";
136 f->spout = fbmem_spout;
137 f->close = fbmem_close;
142 fbmem_clone_read(struct fastbuf *b)
144 struct fastbuf *f = xmalloc_zero(sizeof(struct fastbuf));
145 struct memstream *s = b->lldata;
150 f->name = "<fbmem-read>";
152 f->refill = fbmem_refill;
153 f->seek = fbmem_seek;
154 f->close = fbmem_close;
162 struct fastbuf *w, *r;
166 r = fbmem_clone_read(w);
167 bwrite(w, "12345", 5);
168 bwrite(w, "12345", 5);
169 printf("<%d>", btell(w));
171 printf("<%d>", btell(w));
172 printf("<%d>", btell(r));
173 while ((t = bgetc(r)) >= 0)
175 printf("<%d>", btell(r));
176 bwrite(w, "12345", 5);
177 bwrite(w, "12345", 5);
178 printf("<%d>", btell(w));
181 printf("<!%d>", btell(r));
182 while ((t = bgetc(r)) >= 0)
185 printf("<!%d>", btell(r));
186 while ((t = bgetc(r)) >= 0)