]> mj.ucw.cz Git - libucw.git/blob - ucw/fastbuf.h
89294f31f02aa009fcc160337a0c7153134baee7
[libucw.git] / ucw / 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 files with several configurable back-ends */
77
78 enum fb_type {                          /* Which back-end you want to use */
79   FB_STD,                               /* Standard buffered I/O */
80   FB_DIRECT,                            /* Direct I/O bypassing system caches (see fb-direct.c for a description) */
81   FB_MMAP                               /* Memory mapped files */
82 };
83
84 struct fb_params {
85   enum fb_type type;
86   uns buffer_size;                      /* 0 for default size */
87   uns keep_back_buf;                    /* FB_STD: optimize for bi-directional access */
88   uns read_ahead;                       /* FB_DIRECT options */
89   uns write_back;
90   struct asio_queue *asio;
91 };
92
93 struct cf_section;
94 extern struct cf_section fbpar_cf;
95 extern struct fb_params fbpar_def;
96
97 struct fastbuf *bopen_file(const char *name, int mode, struct fb_params *params);       /* Use params==NULL for defaults */
98 struct fastbuf *bopen_file_try(const char *name, int mode, struct fb_params *params);
99 struct fastbuf *bopen_tmp_file(struct fb_params *params);
100 struct fastbuf *bopen_fd_name(int fd, struct fb_params *params, const char *name);
101 static inline struct fastbuf *bopen_fd(int fd, struct fb_params *params)
102 {
103   return bopen_fd_name(fd, params, NULL);
104 }
105
106 /* FastIO on standard files (shortcuts for FB_STD) */
107
108 struct fastbuf *bopen(const char *name, uns mode, uns buflen);
109 struct fastbuf *bopen_try(const char *name, uns mode, uns buflen);
110 struct fastbuf *bopen_tmp(uns buflen);
111 struct fastbuf *bfdopen(int fd, uns buflen);
112 struct fastbuf *bfdopen_shared(int fd, uns buflen);
113 void bfilesync(struct fastbuf *b);
114
115 /* Temporary files */
116
117 #define TEMP_FILE_NAME_LEN 256
118 void temp_file_name(char *name);
119 void bfix_tmp_file(struct fastbuf *fb, const char *name);
120
121 /* Internal functions of some file back-ends */
122
123 struct fastbuf *bfdopen_internal(int fd, const char *name, uns buflen);
124 struct fastbuf *bfmmopen_internal(int fd, const char *name, uns mode);
125
126 extern uns fbdir_cheat;
127 struct asio_queue;
128 struct fastbuf *fbdir_open_fd_internal(int fd, const char *name, struct asio_queue *io_queue, uns buffer_size, uns read_ahead, uns write_back);
129
130 void bclose_file_helper(struct fastbuf *f, int fd, int is_temp_file);
131
132 /* FastIO on in-memory streams */
133
134 struct fastbuf *fbmem_create(uns blocksize);            /* Create stream and return its writing fastbuf */
135 struct fastbuf *fbmem_clone_read(struct fastbuf *);     /* Create reading fastbuf */
136
137 /* FastI on file descriptors with limit */
138
139 struct fastbuf *bopen_limited_fd(int fd, uns bufsize, uns limit);
140
141 /* FastIO on static buffers */
142
143 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uns size, uns can_overwrite);
144 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uns size);
145 static inline uns
146 fbbuf_count_written(struct fastbuf *f)
147 {
148   return f->bptr - f->bstop;
149 }
150
151 /* FastIO on recyclable growing buffers */
152
153 struct fastbuf *fbgrow_create(unsigned basic_size);
154 void fbgrow_reset(struct fastbuf *b);                   /* Reset stream and prepare for writing */
155 void fbgrow_rewind(struct fastbuf *b);                  /* Prepare for reading */
156
157 /* FastO on memory pools */
158
159 struct mempool;
160 struct fbpool {
161   struct fastbuf fb;
162   struct mempool *mp;
163 };
164
165 void fbpool_init(struct fbpool *fb);    /* Initialize a new fastbuf */
166 void fbpool_start(struct fbpool *fb, struct mempool *mp, uns init_size);
167                                         /* Start a new continuous block and prepare for writing (see mp_start()) */
168 void *fbpool_end(struct fbpool *fb);    /* Close the block and return its address (see mp_end()).
169                                            The length can be determined with mp_size(mp, ptr). */
170
171 /* FastO with atomic writes for multi-threaded programs */
172
173 struct fb_atomic {
174   struct fastbuf fb;
175   struct fb_atomic_file *af;
176   byte *expected_max_bptr;
177   uns slack_size;
178 };
179 #define FB_ATOMIC(f) ((struct fb_atomic *)(f)->is_fastbuf)
180
181 struct fastbuf *fbatomic_open(const char *name, struct fastbuf *master, uns bufsize, int record_len);
182 void fbatomic_internal_write(struct fastbuf *b);
183
184 static inline void
185 fbatomic_commit(struct fastbuf *b)
186 {
187   if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
188     fbatomic_internal_write(b);
189 }
190
191 /* Configuring stream parameters */
192
193 enum bconfig_type {
194   BCONFIG_IS_TEMP_FILE,                 /* 0=normal file, 1=temporary file, 2=shared fd */
195   BCONFIG_KEEP_BACK_BUF,                /* Optimize for bi-directional access */
196 };
197
198 int bconfig(struct fastbuf *f, uns type, int data);
199
200 /* Universal functions working on all fastbuf's */
201
202 void bclose(struct fastbuf *f);
203 void bflush(struct fastbuf *f);
204 void bseek(struct fastbuf *f, sh_off_t pos, int whence);
205 void bsetpos(struct fastbuf *f, sh_off_t pos);
206 void brewind(struct fastbuf *f);
207 sh_off_t bfilesize(struct fastbuf *f);          /* -1 if not seekable */
208
209 static inline sh_off_t btell(struct fastbuf *f)
210 {
211   return f->pos + (f->bptr - f->bstop);
212 }
213
214 int bgetc_slow(struct fastbuf *f);
215 static inline int bgetc(struct fastbuf *f)
216 {
217   return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
218 }
219
220 int bpeekc_slow(struct fastbuf *f);
221 static inline int bpeekc(struct fastbuf *f)
222 {
223   return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
224 }
225
226 static inline void bungetc(struct fastbuf *f)
227 {
228   f->bptr--;
229 }
230
231 void bputc_slow(struct fastbuf *f, uns c);
232 static inline void bputc(struct fastbuf *f, uns c)
233 {
234   if (f->bptr < f->bufend)
235     *f->bptr++ = c;
236   else
237     bputc_slow(f, c);
238 }
239
240 static inline uns
241 bavailr(struct fastbuf *f)
242 {
243   return f->bstop - f->bptr;
244 }
245
246 static inline uns
247 bavailw(struct fastbuf *f)
248 {
249   return f->bufend - f->bptr;
250 }
251
252 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check);
253 static inline uns bread(struct fastbuf *f, void *b, uns l)
254 {
255   if (bavailr(f) >= l)
256     {
257       memcpy(b, f->bptr, l);
258       f->bptr += l;
259       return l;
260     }
261   else
262     return bread_slow(f, b, l, 0);
263 }
264
265 static inline uns breadb(struct fastbuf *f, void *b, uns l)
266 {
267   if (bavailr(f) >= l)
268     {
269       memcpy(b, f->bptr, l);
270       f->bptr += l;
271       return l;
272     }
273   else
274     return bread_slow(f, b, l, 1);
275 }
276
277 void bwrite_slow(struct fastbuf *f, const void *b, uns l);
278 static inline void bwrite(struct fastbuf *f, const void *b, uns l)
279 {
280   if (bavailw(f) >= l)
281     {
282       memcpy(f->bptr, b, l);
283       f->bptr += l;
284     }
285   else
286     bwrite_slow(f, b, l);
287 }
288
289 /*
290  *  Functions for reading of strings:
291  *
292  *     bgets()          reads a line, strip the trailing '\n' and return a pointer
293  *                      to the terminating 0 or NULL on EOF. Dies if the line is too long.
294  *     bgets0()         does the same for 0-terminated strings.
295  *     bgets_nodie()    a variant of bgets() which returns either the length of the
296  *                      string (excluding the terminator) or -1 if the line does not fit
297  *                      in the buffer. In such cases, it returns after reading exactly `l'
298  *                      bytes of input.
299  *     bgets_bb()       a variant of bgets() which allocates the string in a growing buffer
300  *     bgets_mp()       the same, but in a mempool
301  *     bgets_stk()      the same, but on the stack by alloca()
302  */
303
304 char *bgets(struct fastbuf *f, char *b, uns l);
305 char *bgets0(struct fastbuf *f, char *b, uns l);
306 int bgets_nodie(struct fastbuf *f, char *b, uns l);
307
308 struct mempool;
309 struct bb_t;
310 uns bgets_bb(struct fastbuf *f, struct bb_t *b, uns limit);
311 char *bgets_mp(struct fastbuf *f, struct mempool *mp);
312
313 struct bgets_stk_struct {
314   struct fastbuf *f;
315   byte *old_buf, *cur_buf, *src;
316   uns old_len, cur_len, src_len;
317 };
318 void bgets_stk_init(struct bgets_stk_struct *s);
319 void bgets_stk_step(struct bgets_stk_struct *s);
320 #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; })
321
322 static inline void
323 bputs(struct fastbuf *f, const char *b)
324 {
325   bwrite(f, b, strlen(b));
326 }
327
328 static inline void
329 bputs0(struct fastbuf *f, const char *b)
330 {
331   bwrite(f, b, strlen(b)+1);
332 }
333
334 static inline void
335 bputsn(struct fastbuf *f, const char *b)
336 {
337   bputs(f, b);
338   bputc(f, '\n');
339 }
340
341 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l);
342 static inline void
343 bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
344 {
345   if (bavailr(f) >= l && bavailw(t) >= l)
346     {
347       memcpy(t->bptr, f->bptr, l);
348       t->bptr += l;
349       f->bptr += l;
350     }
351   else
352     bbcopy_slow(f, t, l);
353 }
354
355 int bskip_slow(struct fastbuf *f, uns len);
356 static inline int bskip(struct fastbuf *f, uns len)
357 {
358   if (bavailr(f) >= len)
359     {
360       f->bptr += len;
361       return 1;
362     }
363   else
364     return bskip_slow(f, len);
365 }
366
367 /* Direct I/O on buffers */
368
369 static inline uns
370 bdirect_read_prepare(struct fastbuf *f, byte **buf)
371 {
372   if (f->bptr == f->bstop && !f->refill(f))
373     {
374       *buf = NULL;  // This is not needed, but it helps to get rid of spurious warnings
375       return 0;
376     }
377   *buf = f->bptr;
378   return bavailr(f);
379 }
380
381 static inline void
382 bdirect_read_commit(struct fastbuf *f, byte *pos)
383 {
384   f->bptr = pos;
385 }
386
387 static inline void
388 bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
389 {
390   f->bptr = pos;
391   f->buffer = pos;      /* Avoid seeking backwards in the buffer */
392 }
393
394 static inline uns
395 bdirect_write_prepare(struct fastbuf *f, byte **buf)
396 {
397   if (f->bptr == f->bufend)
398     f->spout(f);
399   *buf = f->bptr;
400   return bavailw(f);
401 }
402
403 static inline void
404 bdirect_write_commit(struct fastbuf *f, byte *pos)
405 {
406   f->bptr = pos;
407 }
408
409 /* Formatted output */
410
411 int bprintf(struct fastbuf *b, const char *msg, ...) FORMAT_CHECK(printf,2,3);
412 int vbprintf(struct fastbuf *b, const char *msg, va_list args);
413
414 #endif