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->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(sizeof(struct fastbuf));
127 struct memstream *m = xmalloc(sizeof(struct memstream));
129 m->blocksize = blocksize;
133 f->bptr = f->bstop = f->buffer = f->bufend = NULL;
134 f->pos = f->fdpos = 0;
135 f->name = "<fbmem-write>";
138 f->spout = fbmem_spout;
140 f->close = fbmem_close;
145 fbmem_clone_read(struct fastbuf *b)
147 struct fastbuf *f = xmalloc(sizeof(struct fastbuf));
148 struct memstream *s = b->lldata;
152 f->bptr = f->bstop = f->buffer = f->bufend = NULL;
153 f->pos = f->fdpos = 0;
154 f->name = "<fbmem-read>";
156 f->refill = fbmem_refill;
158 f->seek = fbmem_seek;
159 f->close = fbmem_close;
167 struct fastbuf *w, *r;
171 r = fbmem_clone_read(w);
172 bwrite(w, "12345", 5);
173 bwrite(w, "12345", 5);
174 printf("<%d>", btell(w));
176 printf("<%d>", btell(w));
177 printf("<%d>", btell(r));
178 while ((t = bgetc(r)) >= 0)
180 printf("<%d>", btell(r));
181 bwrite(w, "12345", 5);
182 bwrite(w, "12345", 5);
183 printf("<%d>", btell(w));
186 printf("<!%d>", btell(r));
187 while ((t = bgetc(r)) >= 0)
190 printf("<!%d>", btell(r));
191 while ((t = bgetc(r)) >= 0)