]> mj.ucw.cz Git - libucw.git/blob - ucw/fastbuf.h
4a17bfdf4d3d38042dab7c14594c336e6784752f
[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  * Generic parts
62  * ~~~~~~~~~~~~~
63  ***/
64
65 /**
66  * Fastbuf structure.
67  * This structure is of main interest to fastbuf backends,
68  * it can be considered a black box for use.
69  **/
70 struct fastbuf {
71   byte is_fastbuf[0];                           /* Dummy field for checking of type casts */
72   byte *bptr, *bstop;                           /* Access pointers */
73   byte *buffer, *bufend;                        /* Start and end of the buffer */
74   char *name;                                   /* File name for error messages */
75   ucw_off_t pos;                                /* Position of bstop in the file */
76   int (*refill)(struct fastbuf *);              /* Get a buffer with new data */
77   void (*spout)(struct fastbuf *);              /* Write buffer data to the file */
78   int (*seek)(struct fastbuf *, ucw_off_t, int);/* Slow path for bseek(), buffer already flushed; returns success */
79   void (*close)(struct fastbuf *);              /* Close the stream */
80   int (*config)(struct fastbuf *, uns, int);    /* Configure the stream */
81   int can_overwrite_buffer;                     /* Can the buffer be altered? (see discussion above) 0=never, 1=temporarily, 2=permanently */
82 };
83
84 /*** === FastIO on files with several configurable back-ends ***/
85
86 /**
87  * Which back-end do you want to use?
88  */
89 enum fb_type {
90   FB_STD,                               /* Standard buffered I/O */
91   FB_DIRECT,                            /* Direct I/O bypassing system caches (see +fb-direct.c+ for a description) */
92   FB_MMAP                               /* Memory mapped files */
93 };
94
95 /**
96  * A way to configure created fastbuf.
97  */
98 struct fb_params {
99   enum fb_type type;
100   uns buffer_size;                      /* 0 for default size. */
101   uns keep_back_buf;                    /* FB_STD: optimize for bi-directional access. */
102   uns read_ahead;                       /* FB_DIRECT options. */
103   uns write_back;
104   struct asio_queue *asio;
105 };
106
107 struct cf_section;
108 extern struct cf_section fbpar_cf; /** Config. Can be used by fastbuf systems. **/
109 extern struct fb_params fbpar_def; /** Default parameters. **/
110
111 /**
112  * Opens a file.
113  * Use +@params = NULL+ for defaults.
114  * See standard unix open() for information about @mode.
115  **/
116 struct fastbuf *bopen_file(const char *name, int mode, struct fb_params *params);
117 struct fastbuf *bopen_file_try(const char *name, int mode, struct fb_params *params); /** Tries to open a file (does not die, if unsuccessful). **/
118
119 /**
120  * Opens a temporary file.
121  * It is placed with other temp files and is deleted when closed.
122  **/
123 struct fastbuf *bopen_tmp_file(struct fb_params *params);
124 /**
125  * Creates a fastbuf (wrapper) from a file descriptor.
126  * Sets it's filename to @name (used when outputting errors).
127  */
128 struct fastbuf *bopen_fd_name(int fd, struct fb_params *params, const char *name);
129 static inline struct fastbuf *bopen_fd(int fd, struct fb_params *params) /** Same as above, but with empty filename. **/
130 {
131   return bopen_fd_name(fd, params, NULL);
132 }
133
134 /***
135  * FastIO on standard files (shortcuts for FB_STD)
136  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
137  ***/
138
139 /**
140  * Opens a file in a usual way (with system cache enabled).
141  * Use +@buflen = 0+ for default buffer size.
142  * Dies if unsuccessful.
143  */
144 struct fastbuf *bopen(const char *name, uns mode, uns buflen);
145 struct fastbuf *bopen_try(const char *name, uns mode, uns buflen);/** Same as bopen(), but does not die when unsuccessful. **/
146 struct fastbuf *bopen_tmp(uns buflen);/** Opens a temporary file (read-write). Deletes it, when closed. **/
147 struct fastbuf *bfdopen(int fd, uns buflen);/** Wraps a filedescriptor into a fastbuf. **/
148 struct fastbuf *bfdopen_shared(int fd, uns buflen);/** Wraps a filedescriptor and marks it as shared. **/
149 void bfilesync(struct fastbuf *b);/** Sync file to disk. **/
150
151 /*** === Temporary files ***/
152
153 #define TEMP_FILE_NAME_LEN 256 /** Maximum length of temp file name. **/
154 /**
155  * Generates a temporary filename.
156  * Provide a buffer (as @name_buf, at last +TEMP_FILE_NAME_LEN+ long) to store the name into.
157  * If @open_flags are not +NULL+, flags that should be ored with other flags to open() will be set.
158  *
159  * The provided name can already exist.
160  * If it is not safe to overwrite existing files, +O_EXCL+ is specified in @open_flags.
161  * Check for the result of open().
162  *
163  * This is not specific to fastbufs, can be used separately.
164  **/
165 void temp_file_name(char *name_buf, int *open_flags);
166 /**
167  * Renames a temp fastbuf to given @name and marks it permanent (so it will not be deleted when closed).
168  * The fastbuf is closed by this call.
169  */
170 void bfix_tmp_file(struct fastbuf *fb, const char *name);
171 /**
172  * Opens a temporary file and returns it as file descriptor.
173  * You specify open @mode and @open_flags.
174  *
175  * If @name_buf (at last +TEMP_FILE_NAME_LEN+ long) is not +NULL+, the filename is stored there.
176  *
177  * This is not specific to fastbufs, can be used separately.
178  */
179 int open_tmp(char *name_buf, int open_flags, int mode);
180
181 /* Internal functions of some file back-ends */
182
183 struct fastbuf *bfdopen_internal(int fd, const char *name, uns buflen);
184 struct fastbuf *bfmmopen_internal(int fd, const char *name, uns mode);
185
186 extern uns fbdir_cheat;
187 struct asio_queue;
188 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);
189
190 void bclose_file_helper(struct fastbuf *f, int fd, int is_temp_file);
191
192 /***
193  * FastIO on in-memory streams
194  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~
195  * These behaves in a way similar to unix pipes.
196  * You create one for writing and another for reading.
197  * What you write to the first one can be read from the other.
198  ***/
199
200 struct fastbuf *fbmem_create(uns blocksize);            /** Create stream and return its writing fastbuf. **/
201 struct fastbuf *fbmem_clone_read(struct fastbuf *);     /** Create reading fastbuf. **/
202
203 /*** === FastI on file descriptors with limit ***/
204
205 /**
206  * Wrap a file descriptor @fd into a fastbuf.
207  * No more than @limit bytes will be read/written in the lifetime of this fastbuf.
208  **/
209 struct fastbuf *bopen_limited_fd(int fd, uns bufsize, uns limit);
210
211 /*** === FastIO on static buffers ***/
212
213 /**
214  * Creates a fastbuf that takes data from a memory buffer.
215  * The fastbuf is not allocated, it is initialized in @f.
216  * @buffer and @size specify the buffer with data.
217  * See top of this file for info about @can_overwrite.
218  *
219  * No resources are alocated by this, so you do not need to free it.
220  * It is not possible to close this fastbuf.
221  */
222 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uns size, uns can_overwrite);
223 /**
224  * Creates a fastbuf which writes into a provided memory buffer.
225  * Write over the end dies.
226  *
227  * No resources are allocated by this and you can not close this fastbuf.
228  *
229  * Data are written directly into the buffer, no need for flushes.
230  */
231 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uns size);
232 static inline uns fbbuf_count_written(struct fastbuf *f) /** How many bytes were written into the buffer already? **/
233 {
234   return f->bptr - f->bstop;
235 }
236
237 /*** === FastIO on recyclable growing buffers ***/
238
239 struct fastbuf *fbgrow_create(unsigned basic_size);     /** Create the growing buffer, with pre-allocated size @basic_size. **/
240 void fbgrow_reset(struct fastbuf *b);                   /** Reset stream and prepare for writing. **/
241 void fbgrow_rewind(struct fastbuf *b);                  /** Prepare for reading (of already written data). **/
242
243 /***
244  * FastO on memory pools
245  * ~~~~~~~~~~~~~~~~~~~~~
246  * You write to it and get buffers of written data.
247  ***/
248
249 struct mempool;
250 struct fbpool { /** Structure for fastbufs & mempools. **/
251   struct fastbuf fb;
252   struct mempool *mp;
253 };
254
255 void fbpool_init(struct fbpool *fb);    /** Initialize a new mempool fastbuf. **/
256 /**
257  * Start a new continuous block and prepare for writing (see mp_start()).
258  * Provide the memory pool you want to use for this block (in @mp).
259  **/
260 void fbpool_start(struct fbpool *fb, struct mempool *mp, uns init_size);
261 /**
262  * Close the block and return its address (see mp_end()).
263  * The length can be determined with mp_size(mp, ptr).
264  **/
265 void *fbpool_end(struct fbpool *fb);
266
267 /***
268  * === FastO with atomic writes for multi-threaded programs
269  * Use them, when you need to write records into single file from several threads.
270  * It does not ensure order of the records, but they will not intersect.
271  ***/
272
273 struct fb_atomic {
274   struct fastbuf fb;
275   struct fb_atomic_file *af;
276   byte *expected_max_bptr;
277   uns slack_size;
278 };
279 #define FB_ATOMIC(f) ((struct fb_atomic *)(f)->is_fastbuf)
280
281 /**
282  * Open an atomic fastbuf.
283  * If you specify @master, it is used to write into it (both the master
284  * and the new one will be the same file, with separate buffers).
285  * If @master is +NULL+, a file @name is opened.
286  *
287  * You can specify @record_len, if it is known (for optimisations).
288  *
289  * The file is closed when all fastbufs using it are closed.
290  **/
291 struct fastbuf *fbatomic_open(const char *name, struct fastbuf *master, uns bufsize, int record_len);
292 void fbatomic_internal_write(struct fastbuf *b);
293
294 /**
295  * Commit the last record.
296  * It may not yet write it to the file, but it will stay together.
297  **/
298 static inline void fbatomic_commit(struct fastbuf *b)
299 {
300   if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
301     fbatomic_internal_write(b);
302 }
303
304 /*** === Configuring stream parameters ***/
305
306 enum bconfig_type {                     /** Parameters that could be configured. **/
307   BCONFIG_IS_TEMP_FILE,                 /* 0=normal file, 1=temporary file, 2=shared fd */
308   BCONFIG_KEEP_BACK_BUF,                /* Optimize for bi-directional access */
309 };
310
311 int bconfig(struct fastbuf *f, uns type, int data); /** Configure a fastbuf. Returns previous value. **/
312
313 /*** === Universal functions working on all fastbuf's ***/
314
315 /**
316  * Close and free fastbuf.
317  * Can not be used for fastbufs not returned from function (initialized in a parameter, for example the one from +fbbuf_init_read+).
318  */
319 void bclose(struct fastbuf *f);
320 void bflush(struct fastbuf *f);                                 /** Write data (if it makes any sense, do not use for in-memory buffers). **/
321 void bseek(struct fastbuf *f, ucw_off_t pos, int whence);       /** Seek in the buffer. See +man fseek+ for description of @whence. Only for seekable fastbufs. **/
322 void bsetpos(struct fastbuf *f, ucw_off_t pos);                 /** Set position to @pos bytes from beginning. Only for seekable fastbufs. **/
323 void brewind(struct fastbuf *f);                                /** Go to the beginning of the fastbuf. Only for seekable ones. **/
324 ucw_off_t bfilesize(struct fastbuf *f);                         /** How large is the file? -1 if not seekable. **/
325
326 static inline ucw_off_t btell(struct fastbuf *f)                /** Where am I (from the beginning)? **/
327 {
328   return f->pos + (f->bptr - f->bstop);
329 }
330
331 int bgetc_slow(struct fastbuf *f);
332 static inline int bgetc(struct fastbuf *f)                      /** Return next character from the buffer. **/
333 {
334   return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
335 }
336
337 int bpeekc_slow(struct fastbuf *f);
338 static inline int bpeekc(struct fastbuf *f)                     /** Return next character from the buffer, but keep the current position. **/
339 {
340   return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
341 }
342
343 static inline void bungetc(struct fastbuf *f)                   /** Return last read character back. Only one back is guaranteed to work. **/
344 {
345   f->bptr--;
346 }
347
348 void bputc_slow(struct fastbuf *f, uns c);
349 static inline void bputc(struct fastbuf *f, uns c)              /** Write a single character. **/
350 {
351   if (f->bptr < f->bufend)
352     *f->bptr++ = c;
353   else
354     bputc_slow(f, c);
355 }
356
357 static inline uns bavailr(struct fastbuf *f)
358 {
359   return f->bstop - f->bptr;
360 }
361
362 static inline uns bavailw(struct fastbuf *f)
363 {
364   return f->bufend - f->bptr;
365 }
366
367 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check);
368 /**
369  * Read at most @l bytes of data into @b.
370  * Returns number of bytes read.
371  * 0 means end of file.
372  */
373 static inline uns bread(struct fastbuf *f, void *b, uns l)
374 {
375   if (bavailr(f) >= l)
376     {
377       memcpy(b, f->bptr, l);
378       f->bptr += l;
379       return l;
380     }
381   else
382     return bread_slow(f, b, l, 0);
383 }
384
385 /**
386  * Reads exactly @l bytes of data into @b.
387  * If at the end of file, it returns 0.
388  * If there are data, but less than @l, it dies.
389  */
390 static inline uns breadb(struct fastbuf *f, void *b, uns l)
391 {
392   if (bavailr(f) >= l)
393     {
394       memcpy(b, f->bptr, l);
395       f->bptr += l;
396       return l;
397     }
398   else
399     return bread_slow(f, b, l, 1);
400 }
401
402 void bwrite_slow(struct fastbuf *f, const void *b, uns l);
403 static inline void bwrite(struct fastbuf *f, const void *b, uns l) /** Writes buffer @b of length @l into fastbuf. **/
404 {
405   if (bavailw(f) >= l)
406     {
407       memcpy(f->bptr, b, l);
408       f->bptr += l;
409     }
410   else
411     bwrite_slow(f, b, l);
412 }
413
414 /**
415  * Reads a line into @b and strips trailing +\n+.
416  * Returns pointer to the terminating 0 or +NULL+ on EOF.
417  * Dies if the line is longer than @l.
418  **/
419 char *bgets(struct fastbuf *f, char *b, uns l);
420 char *bgets0(struct fastbuf *f, char *b, uns l);        /** The same as bgets(), but for 0-terminated strings. **/
421 /**
422  * Returns either length of read string (excluding the terminator) or -1 if it is too long.
423  * In such cases exactly @l bytes are read.
424  */
425 int bgets_nodie(struct fastbuf *f, char *b, uns l);
426
427 struct mempool;
428 struct bb_t;
429 /**
430  * Read a string, strip the trailing +\n+ and store it into growing buffer @b.
431  * Dies if the line is longer than @limit.
432  **/
433 uns bgets_bb(struct fastbuf *f, struct bb_t *b, uns limit);
434 /**
435  * Read a string, strip the trailing +\n+ and store it into buffer allocated from a memory pool.
436  **/
437 char *bgets_mp(struct fastbuf *f, struct mempool *mp);
438
439 struct bgets_stk_struct {
440   struct fastbuf *f;
441   byte *old_buf, *cur_buf, *src;
442   uns old_len, cur_len, src_len;
443 };
444 void bgets_stk_init(struct bgets_stk_struct *s);
445 void bgets_stk_step(struct bgets_stk_struct *s);
446
447 /**
448  * Read a string, strip the trailing +\n+ and store it on the stack (allocated using alloca()).
449  **/
450 #define bgets_stk(fb) \
451   ({ 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; })
452
453 /**
454  * Write a string, without 0 or +\n+ at the end.
455  **/
456 static inline void bputs(struct fastbuf *f, const char *b)
457 {
458   bwrite(f, b, strlen(b));
459 }
460
461 /**
462  * Write string, including terminating 0.
463  **/
464 static inline void bputs0(struct fastbuf *f, const char *b)
465 {
466   bwrite(f, b, strlen(b)+1);
467 }
468
469 /**
470  * Write string and append a newline to the end.
471  **/
472 static inline void bputsn(struct fastbuf *f, const char *b)
473 {
474   bputs(f, b);
475   bputc(f, '\n');
476 }
477
478 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l);
479 /**
480  * Copy @l bytes of data from fastbuf @f to fastbuf @t.
481  **/
482 static inline void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
483 {
484   if (bavailr(f) >= l && bavailw(t) >= l)
485     {
486       memcpy(t->bptr, f->bptr, l);
487       t->bptr += l;
488       f->bptr += l;
489     }
490   else
491     bbcopy_slow(f, t, l);
492 }
493
494 int bskip_slow(struct fastbuf *f, uns len);
495 static inline int bskip(struct fastbuf *f, uns len) /** Skip @len bytes without reading them. **/
496 {
497   if (bavailr(f) >= len)
498     {
499       f->bptr += len;
500       return 1;
501     }
502   else
503     return bskip_slow(f, len);
504 }
505
506 /*** === Direct I/O on buffers ***/
507 // TODO Documentation -- what do they do?
508
509 static inline uns
510 bdirect_read_prepare(struct fastbuf *f, byte **buf)
511 {
512   if (f->bptr == f->bstop && !f->refill(f))
513     {
514       *buf = NULL;  // This is not needed, but it helps to get rid of spurious warnings
515       return 0;
516     }
517   *buf = f->bptr;
518   return bavailr(f);
519 }
520
521 static inline void
522 bdirect_read_commit(struct fastbuf *f, byte *pos)
523 {
524   f->bptr = pos;
525 }
526
527 static inline void
528 bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
529 {
530   f->bptr = pos;
531   f->buffer = pos;      /* Avoid seeking backwards in the buffer */
532 }
533
534 static inline uns
535 bdirect_write_prepare(struct fastbuf *f, byte **buf)
536 {
537   if (f->bptr == f->bufend)
538     f->spout(f);
539   *buf = f->bptr;
540   return bavailw(f);
541 }
542
543 static inline void
544 bdirect_write_commit(struct fastbuf *f, byte *pos)
545 {
546   f->bptr = pos;
547 }
548
549 /*** === Formatted output ***/
550
551 /**
552  * printf into a fastbuf.
553  **/
554 int bprintf(struct fastbuf *b, const char *msg, ...)
555   FORMAT_CHECK(printf,2,3);
556 int vbprintf(struct fastbuf *b, const char *msg, va_list args); /** vprintf into a fastbuf. **/
557
558 #endif