]> mj.ucw.cz Git - libucw.git/blob - lib/fastbuf.h
few "byte *" -> "char *" conversions
[libucw.git] / lib / fastbuf.h
1 /*
2  *      UCW Library -- Fast Buffered I/O
3  *
4  *      (c) 1997--2007 Martin Mares <mj@ucw.cz>
5  *      (c) 2004 Robert Spalek <robert@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #ifndef _UCW_FASTBUF_H
12 #define _UCW_FASTBUF_H
13
14 #include <string.h>
15 #include <alloca.h>
16
17 /*
18  *  Generic buffered I/O. You supply hooks to be called for low-level operations
19  *  (swapping of buffers, seeking and closing), we do the rest.
20  *
21  *  Buffer layout when reading:
22  *
23  *  +----------------+---------------------------+
24  *  | read data      | free space                |
25  *  +----------------+---------------------------+
26  *  ^        ^        ^                           ^
27  *  buffer   bptr     bstop                       bufend
28  *
29  *  After the last character is read, bptr == bstop and buffer refill
30  *  is deferred to the next read attempt. This gives us an easy way
31  *  how to implement bungetc().
32  *
33  *  When writing:
34  *
35  *  +--------+--------------+--------------------+
36  *  | unused | written data | free space         |
37  *  +--------+--------------+--------------------+
38  *  ^         ^              ^                    ^
39  *  buffer    bstop          bptr                 bufend
40  *
41  *  Dirty tricks:
42  *
43  *    - You can mix reads and writes on the same stream, but you must
44  *      call bflush() in between and remember that the file position
45  *      points after the flushed buffer which is not necessarily the same
46  *      as after the data you've read.
47  *    - The spout/refill hooks can change not only bptr and bstop, but also
48  *      the location of the buffer; fb-mem.c takes advantage of it.
49  *    - In some cases, the user of the bdirect interface can be allowed to modify
50  *      the data in the buffer to avoid unnecessary copying. If the back-end
51  *      allows such modifications, it can set can_overwrite_buffer accordingly:
52  *              *  0 if no modification is allowed,
53  *              *  1 if the user can modify the buffer on the condition that
54  *                   the modifications will be undone before calling the next
55  *                   fastbuf operation
56  *              *  2 if the user is allowed to overwrite the data in the buffer
57  *                   if bdirect_read_commit_modified() is called afterwards.
58  *                   In this case, the back-end must be prepared for trimming
59  *                   of the buffer which is done by the commit function.
60  */
61
62 struct fastbuf {
63   byte is_fastbuf[0];                   /* Dummy field for checking of type casts */
64   byte *bptr, *bstop;                   /* Access pointers */
65   byte *buffer, *bufend;                /* Start and end of the buffer */
66   char *name;                           /* File name for error messages */
67   sh_off_t pos;                         /* Position of bstop in the file */
68   int (*refill)(struct fastbuf *);      /* Get a buffer with new data */
69   void (*spout)(struct fastbuf *);      /* Write buffer data to the file */
70   int (*seek)(struct fastbuf *, sh_off_t, int);  /* Slow path for bseek(), buffer already flushed; returns success */
71   void (*close)(struct fastbuf *);      /* Close the stream */
72   int (*config)(struct fastbuf *, uns, int);    /* Configure the stream */
73   int can_overwrite_buffer;             /* Can the buffer be altered? (see discussion above) 0=never, 1=temporarily, 2=permanently */
74 };
75
76 /* FastIO on standard files (specify buffer size 0 to enable mmaping) */
77
78 struct fastbuf *bopen(const char *name, uns mode, uns buflen);
79 struct fastbuf *bopen_try(const char *name, uns mode, uns buflen);
80 struct fastbuf *bopen_tmp(uns buflen);
81 struct fastbuf *bfdopen(int fd, uns buflen);
82 struct fastbuf *bfdopen_shared(int fd, uns buflen);
83 void bfilesync(struct fastbuf *b);
84
85 #define TEMP_FILE_NAME_LEN 256
86 void temp_file_name(char *name);
87
88 /* FastIO on in-memory streams */
89
90 struct fastbuf *fbmem_create(uns blocksize);            /* Create stream and return its writing fastbuf */
91 struct fastbuf *fbmem_clone_read(struct fastbuf *);     /* Create reading fastbuf */
92
93 /* FastIO on memory mapped files */
94
95 struct fastbuf *bopen_mm(const char *name, uns mode);
96
97 /* FastI on file descriptors with limit */
98
99 struct fastbuf *bopen_limited_fd(int fd, uns bufsize, uns limit);
100
101 /* FastIO on static buffers */
102
103 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uns size, uns can_overwrite);
104 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uns size);
105 static inline uns
106 fbbuf_count_written(struct fastbuf *f)
107 {
108   return f->bptr - f->bstop;
109 }
110
111 /* FastIO on recyclable growing buffers */
112
113 struct fastbuf *fbgrow_create(unsigned basic_size);
114 void fbgrow_reset(struct fastbuf *b);                   /* Reset stream and prepare for writing */
115 void fbgrow_rewind(struct fastbuf *b);                  /* Prepare for reading */
116
117 /* FastO with atomic writes for multi-threaded programs */
118
119 struct fb_atomic {
120   struct fastbuf fb;
121   struct fb_atomic_file *af;
122   byte *expected_max_bptr;
123   uns slack_size;
124 };
125 #define FB_ATOMIC(f) ((struct fb_atomic *)(f)->is_fastbuf)
126
127 struct fastbuf *fbatomic_open(const char *name, struct fastbuf *master, uns bufsize, int record_len);
128 void fbatomic_internal_write(struct fastbuf *b);
129
130 static inline void
131 fbatomic_commit(struct fastbuf *b)
132 {
133   if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
134     fbatomic_internal_write(b);
135 }
136
137 /* Configuring stream parameters */
138
139 int bconfig(struct fastbuf *f, uns type, int data);
140
141 #define BCONFIG_IS_TEMP_FILE 0
142
143 /* Universal functions working on all fastbuf's */
144
145 void bclose(struct fastbuf *f);
146 void bflush(struct fastbuf *f);
147 void bseek(struct fastbuf *f, sh_off_t pos, int whence);
148 void bsetpos(struct fastbuf *f, sh_off_t pos);
149 void brewind(struct fastbuf *f);
150 sh_off_t bfilesize(struct fastbuf *f);          // -1 if not seekable
151
152 static inline sh_off_t btell(struct fastbuf *f)
153 {
154   return f->pos + (f->bptr - f->bstop);
155 }
156
157 int bgetc_slow(struct fastbuf *f);
158 static inline int bgetc(struct fastbuf *f)
159 {
160   return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
161 }
162
163 int bpeekc_slow(struct fastbuf *f);
164 static inline int bpeekc(struct fastbuf *f)
165 {
166   return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
167 }
168
169 static inline void bungetc(struct fastbuf *f)
170 {
171   f->bptr--;
172 }
173
174 void bputc_slow(struct fastbuf *f, uns c);
175 static inline void bputc(struct fastbuf *f, uns c)
176 {
177   if (f->bptr < f->bufend)
178     *f->bptr++ = c;
179   else
180     bputc_slow(f, c);
181 }
182
183 static inline uns
184 bavailr(struct fastbuf *f)
185 {
186   return f->bstop - f->bptr;
187 }
188
189 static inline uns
190 bavailw(struct fastbuf *f)
191 {
192   return f->bufend - f->bptr;
193 }
194
195 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check);
196 static inline uns bread(struct fastbuf *f, void *b, uns l)
197 {
198   if (bavailr(f) >= l)
199     {
200       memcpy(b, f->bptr, l);
201       f->bptr += l;
202       return l;
203     }
204   else
205     return bread_slow(f, b, l, 0);
206 }
207
208 static inline uns breadb(struct fastbuf *f, void *b, uns l)
209 {
210   if (bavailr(f) >= l)
211     {
212       memcpy(b, f->bptr, l);
213       f->bptr += l;
214       return l;
215     }
216   else
217     return bread_slow(f, b, l, 1);
218 }
219
220 void bwrite_slow(struct fastbuf *f, const void *b, uns l);
221 static inline void bwrite(struct fastbuf *f, const void *b, uns l)
222 {
223   if (bavailw(f) >= l)
224     {
225       memcpy(f->bptr, b, l);
226       f->bptr += l;
227     }
228   else
229     bwrite_slow(f, b, l);
230 }
231
232 /*
233  *  Functions for reading of strings:
234  *
235  *     bgets()          reads a line, strip the trailing '\n' and return a pointer
236  *                      to the terminating 0 or NULL on EOF. Dies if the line is too long.
237  *     bgets0()         does the same for 0-terminated strings.
238  *     bgets_nodie()    a variant of bgets() which returns either the length of the
239  *                      string (excluding the terminator) or -1 if the line does not fit
240  *                      in the buffer. In such cases, it returns after reading exactly `l'
241  *                      bytes of input.
242  *     bgets_bb()       a variant of bgets() which allocates the string in a growing buffer
243  *     bgets_mp()       the same, but in a mempool
244  *     bgets_stk()      the same, but on the stack by alloca()
245  */
246
247 char *bgets(struct fastbuf *f, char *b, uns l);
248 char *bgets0(struct fastbuf *f, char *b, uns l);
249 int bgets_nodie(struct fastbuf *f, char *b, uns l);
250
251 struct mempool;
252 struct bb_t;
253 uns bgets_bb(struct fastbuf *f, struct bb_t *b, uns limit);
254 char *bgets_mp(struct fastbuf *f, struct mempool *mp);
255
256 struct bgets_stk_struct {
257   struct fastbuf *f;
258   byte *old_buf, *cur_buf, *src;
259   uns old_len, cur_len, src_len;
260 };
261 void bgets_stk_init(struct bgets_stk_struct *s);
262 void bgets_stk_step(struct bgets_stk_struct *s);
263 #define bgets_stk(fb) ({ struct bgets_stk_struct _s; _s.f = (fb); for (bgets_stk_init(&_s); _s.cur_len; _s.cur_buf = alloca(_s.cur_len), bgets_stk_step(&_s)); _s.cur_buf; })
264
265 static inline void
266 bputs(struct fastbuf *f, const char *b)
267 {
268   bwrite(f, b, strlen(b));
269 }
270
271 static inline void
272 bputs0(struct fastbuf *f, const char *b)
273 {
274   bwrite(f, b, strlen(b)+1);
275 }
276
277 static inline void
278 bputsn(struct fastbuf *f, const char *b)
279 {
280   bputs(f, b);
281   bputc(f, '\n');
282 }
283
284 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l);
285 static inline void
286 bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
287 {
288   if (bavailr(f) >= l && bavailw(t) >= l)
289     {
290       memcpy(t->bptr, f->bptr, l);
291       t->bptr += l;
292       f->bptr += l;
293     }
294   else
295     bbcopy_slow(f, t, l);
296 }
297
298 int bskip_slow(struct fastbuf *f, uns len);
299 static inline int bskip(struct fastbuf *f, uns len)
300 {
301   if (bavailr(f) >= len)
302     {
303       f->bptr += len;
304       return 1;
305     }
306   else
307     return bskip_slow(f, len);
308 }
309
310 /* Direct I/O on buffers */
311
312 static inline uns
313 bdirect_read_prepare(struct fastbuf *f, byte **buf)
314 {
315   if (f->bptr == f->bstop && !f->refill(f))
316     {
317       *buf = NULL;  // This is not needed, but it helps to get rid of spurious warnings
318       return 0;
319     }
320   *buf = f->bptr;
321   return bavailr(f);
322 }
323
324 static inline void
325 bdirect_read_commit(struct fastbuf *f, byte *pos)
326 {
327   f->bptr = pos;
328 }
329
330 static inline void
331 bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
332 {
333   f->bptr = pos;
334   f->buffer = pos;      /* Avoid seeking backwards in the buffer */
335 }
336
337 static inline uns
338 bdirect_write_prepare(struct fastbuf *f, byte **buf)
339 {
340   if (f->bptr == f->bufend)
341     f->spout(f);
342   *buf = f->bptr;
343   return bavailw(f);
344 }
345
346 static inline void
347 bdirect_write_commit(struct fastbuf *f, byte *pos)
348 {
349   f->bptr = pos;
350 }
351
352 /* Formatted output */
353
354 int bprintf(struct fastbuf *b, const char *msg, ...) FORMAT_CHECK(printf,2,3);
355 int vbprintf(struct fastbuf *b, const char *msg, va_list args);
356
357 #endif