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 f->seek(f, pos, SEEK_SET);
45 void bseek(struct fastbuf *f, sh_off_t pos, int whence)
50 return bsetpos(f, pos);
52 return bsetpos(f, btell(f) + pos);
55 f->seek(f, pos, SEEK_END);
58 die("bseek: invalid whence=%d", whence);
62 int bgetc_slow(struct fastbuf *f)
64 if (f->bptr < f->bstop)
71 int bpeekc_slow(struct fastbuf *f)
73 if (f->bptr < f->bstop)
80 void bputc_slow(struct fastbuf *f, uns c)
82 if (f->bptr >= f->bufend)
87 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check)
92 uns k = f->bstop - f->bptr;
97 k = f->bstop - f->bptr;
103 memcpy(b, f->bptr, k);
109 if (check && total && l)
110 die("breadb: short read");
114 void bwrite_slow(struct fastbuf *f, void *b, uns l)
118 uns k = f->bufend - f->bptr;
123 k = f->bufend - f->bptr;
127 memcpy(f->bptr, b, k);
135 bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l)
140 uns favail, tavail, n;
142 favail = bdirect_read_prepare(f, &fptr);
147 die("bbcopy: source exhausted");
149 tavail = bdirect_write_prepare(t, &tptr);
152 memcpy(tptr, fptr, n);
153 bdirect_read_commit(f, fptr + n);
154 bdirect_write_commit(t, tptr + n);
161 bconfig(struct fastbuf *f, uns item, int value)
163 return f->config ? f->config(f, item, value) : -1;
167 brewind(struct fastbuf *f)
174 bskip_slow(struct fastbuf *f, uns len)
179 uns l = bdirect_read_prepare(f, &buf);
183 bdirect_read_commit(f, buf+l);
190 bfilesize(struct fastbuf *f)
194 sh_off_t pos = btell(f);
195 bseek(f, 0, SEEK_END);
196 sh_off_t len = btell(f);