2 * Sherlock Library -- Fast Buffered I/O
4 * (c) 1997--2000 Martin Mares <mj@ucw.cz>
8 #include "lib/fastbuf.h"
13 void bclose(struct fastbuf *f)
20 void bflush(struct fastbuf *f)
22 if (f->bptr != f->buffer)
23 { /* Have something to flush */
24 if (f->bstop > f->buffer) /* Read data? */
26 f->bptr = f->bstop = f->buffer;
29 else /* Write data... */
34 inline void bsetpos(struct fastbuf *f, sh_off_t pos)
36 if (pos >= f->pos && (pos <= f->pos + (f->bptr - f->buffer) || pos <= f->pos + (f->bstop - f->buffer)))
37 f->bptr = f->buffer + (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, byte c)
82 if (f->bptr >= f->bufend)
87 word bgetw_slow(struct fastbuf *f)
89 word w = bgetc_slow(f);
91 return (w << 8) | bgetc_slow(f);
93 return w | (bgetc_slow(f) << 8);
97 u32 bgetl_slow(struct fastbuf *f)
99 u32 l = bgetc_slow(f);
100 #ifdef CPU_BIG_ENDIAN
101 l = (l << 8) | bgetc_slow(f);
102 l = (l << 8) | bgetc_slow(f);
103 return (l << 8) | bgetc_slow(f);
105 l = (bgetc_slow(f) << 8) | l;
106 l = (bgetc_slow(f) << 16) | l;
107 return (bgetc_slow(f) << 24) | l;
111 u64 bgetq_slow(struct fastbuf *f)
114 #ifdef CPU_BIG_ENDIAN
121 return ((u64) h << 32) | l;
124 u64 bget5_slow(struct fastbuf *f)
127 #ifdef CPU_BIG_ENDIAN
134 return ((u64) h << 32) | l;
137 void bputw_slow(struct fastbuf *f, word w)
139 #ifdef CPU_BIG_ENDIAN
140 bputc_slow(f, w >> 8);
144 bputc_slow(f, w >> 8);
148 void bputl_slow(struct fastbuf *f, u32 l)
150 #ifdef CPU_BIG_ENDIAN
151 bputc_slow(f, l >> 24);
152 bputc_slow(f, l >> 16);
153 bputc_slow(f, l >> 8);
157 bputc_slow(f, l >> 8);
158 bputc_slow(f, l >> 16);
159 bputc_slow(f, l >> 24);
163 void bputq_slow(struct fastbuf *f, u64 q)
165 #ifdef CPU_BIG_ENDIAN
166 bputl_slow(f, q >> 32);
170 bputl_slow(f, q >> 32);
174 void bput5_slow(struct fastbuf *f, u64 o)
178 #ifdef CPU_BIG_ENDIAN
187 uns bread_slow(struct fastbuf *f, void *b, uns l)
192 uns k = f->bstop - f->bptr;
197 k = f->bstop - f->bptr;
203 memcpy(b, f->bptr, k);
212 void bwrite_slow(struct fastbuf *f, void *b, uns l)
216 uns k = f->bufend - f->bptr;
221 k = f->bufend - f->bptr;
225 memcpy(f->bptr, b, k);
232 byte * /* Non-standard */
233 bgets(struct fastbuf *f, byte *b, uns l)
243 if (k == '\n' || k == EOF)
251 die("%s: Line too long", f->name);