2 * UCW Library -- Fast Buffered I/O
4 * (c) 1997--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 "lib/fastbuf.h"
15 void bclose(struct fastbuf *f)
25 void bflush(struct fastbuf *f)
27 if (f->bptr > f->bstop)
29 else if (f->bstop > f->buffer)
30 f->bptr = f->bstop = f->buffer;
33 inline void bsetpos(struct fastbuf *f, sh_off_t pos)
35 /* We can optimize seeks only when reading */
36 if (pos >= f->pos - (f->bstop - f->buffer) && pos <= f->pos)
37 f->bptr = f->bstop + (pos - f->pos);
41 if (!f->seek || !f->seek(f, pos, SEEK_SET))
42 die("bsetpos: stream not seekable");
46 void bseek(struct fastbuf *f, sh_off_t pos, int whence)
51 return bsetpos(f, pos);
53 return bsetpos(f, btell(f) + pos);
56 if (!f->seek || !f->seek(f, pos, SEEK_END))
57 die("bseek: stream not seekable");
60 die("bseek: invalid whence=%d", whence);
64 int bgetc_slow(struct fastbuf *f)
66 if (f->bptr < f->bstop)
73 int bpeekc_slow(struct fastbuf *f)
75 if (f->bptr < f->bstop)
82 void bputc_slow(struct fastbuf *f, uns c)
84 if (f->bptr >= f->bufend)
89 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check)
94 uns k = f->bstop - f->bptr;
99 k = f->bstop - f->bptr;
105 memcpy(b, f->bptr, k);
111 if (check && total && l)
112 die("breadb: short read");
116 void bwrite_slow(struct fastbuf *f, void *b, uns l)
120 uns k = f->bufend - f->bptr;
125 k = f->bufend - f->bptr;
129 memcpy(f->bptr, b, k);
137 bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l)
142 uns favail, tavail, n;
144 favail = bdirect_read_prepare(f, &fptr);
149 die("bbcopy: source exhausted");
151 tavail = bdirect_write_prepare(t, &tptr);
154 memcpy(tptr, fptr, n);
155 bdirect_read_commit(f, fptr + n);
156 bdirect_write_commit(t, tptr + n);
163 bconfig(struct fastbuf *f, uns item, int value)
165 return f->config ? f->config(f, item, value) : -1;
169 brewind(struct fastbuf *f)
176 bskip_slow(struct fastbuf *f, uns len)
181 uns l = bdirect_read_prepare(f, &buf);
185 bdirect_read_commit(f, buf+l);
192 bfilesize(struct fastbuf *f)
196 sh_off_t pos = btell(f);
198 if (!f->seek(f, pos, SEEK_END))
200 sh_off_t len = btell(f);