]> mj.ucw.cz Git - libucw.git/blob - ucw/fastbuf.h
Fastbufs: Some improvements in documented rules for back-ends.
[libucw.git] / ucw / fastbuf.h
1 /*
2  *      UCW Library -- Fast Buffered I/O
3  *
4  *      (c) 1997--2011 Martin Mares <mj@ucw.cz>
5  *      (c) 2004 Robert Spalek <robert@ucw.cz>
6  *      (c) 2014 Pavel Charvat <pchar@ucw.cz>
7  *
8  *      This software may be freely distributed and used according to the terms
9  *      of the GNU Lesser General Public License.
10  */
11
12 #ifndef _UCW_FASTBUF_H
13 #define _UCW_FASTBUF_H
14
15 #include <string.h>
16 #include <alloca.h>
17
18 #ifdef CONFIG_UCW_CLEAN_ABI
19 #define bbcopy_slow ucw_bbcopy_slow
20 #define bclose ucw_bclose
21 #define bclose_file_helper ucw_bclose_file_helper
22 #define bconfig ucw_bconfig
23 #define beof_slow ucw_beof_slow
24 #define bfdopen ucw_bfdopen
25 #define bfdopen_internal ucw_bfdopen_internal
26 #define bfdopen_shared ucw_bfdopen_shared
27 #define bfilesize ucw_bfilesize
28 #define bfilesync ucw_bfilesync
29 #define bfix_tmp_file ucw_bfix_tmp_file
30 #define bflush ucw_bflush
31 #define bfmmopen_internal ucw_bfmmopen_internal
32 #define bgetc_slow ucw_bgetc_slow
33 #define bgets ucw_bgets
34 #define bgets0 ucw_bgets0
35 #define bgets_bb ucw_bgets_bb
36 #define bgets_mp ucw_bgets_mp
37 #define bgets_nodie ucw_bgets_nodie
38 #define bgets_stk_init ucw_bgets_stk_init
39 #define bgets_stk_step ucw_bgets_stk_step
40 #define bopen ucw_bopen
41 #define bopen_fd_name ucw_bopen_fd_name
42 #define bopen_file ucw_bopen_file
43 #define bopen_file_try ucw_bopen_file_try
44 #define bopen_limited_fd ucw_bopen_limited_fd
45 #define bopen_tmp ucw_bopen_tmp
46 #define bopen_tmp_file ucw_bopen_tmp_file
47 #define bopen_try ucw_bopen_try
48 #define bpeekc_slow ucw_bpeekc_slow
49 #define bprintf ucw_bprintf
50 #define bputc_slow ucw_bputc_slow
51 #define bread_slow ucw_bread_slow
52 #define brefill ucw_brefill
53 #define brewind ucw_brewind
54 #define bseek ucw_bseek
55 #define bsetpos ucw_bsetpos
56 #define bskip_slow ucw_bskip_slow
57 #define bspout ucw_bspout
58 #define bthrow ucw_bthrow
59 #define bwrite_slow ucw_bwrite_slow
60 #define fb_tie ucw_fb_tie
61 #define fbatomic_internal_write ucw_fbatomic_internal_write
62 #define fbatomic_open ucw_fbatomic_open
63 #define fbbuf_init_read ucw_fbbuf_init_read
64 #define fbbuf_init_write ucw_fbbuf_init_write
65 #define fbdir_cheat ucw_fbdir_cheat
66 #define fbdir_open_fd_internal ucw_fbdir_open_fd_internal
67 #define fbgrow_create ucw_fbgrow_create
68 #define fbgrow_create_mp ucw_fbgrow_create_mp
69 #define fbgrow_get_buf ucw_fbgrow_get_buf
70 #define fbgrow_reset ucw_fbgrow_reset
71 #define fbgrow_rewind ucw_fbgrow_rewind
72 #define fbmem_clone_read ucw_fbmem_clone_read
73 #define fbmem_create ucw_fbmem_create
74 #define fbmulti_append ucw_fbmulti_append
75 #define fbmulti_create ucw_fbmulti_create
76 #define fbmulti_remove ucw_fbmulti_remove
77 #define fbnull_open ucw_fbnull_open
78 #define fbnull_start ucw_fbnull_start
79 #define fbnull_test ucw_fbnull_test
80 #define fbpar_cf ucw_fbpar_cf
81 #define fbpar_def ucw_fbpar_def
82 #define fbpool_end ucw_fbpool_end
83 #define fbpool_init ucw_fbpool_init
84 #define fbpool_start ucw_fbpool_start
85 #define open_tmp ucw_open_tmp
86 #define temp_file_name ucw_temp_file_name
87 #define vbprintf ucw_vbprintf
88 #endif
89
90 /***
91  * === Internal structure [[internal]]
92  *
93  * Generally speaking, a fastbuf consists of a buffer and a set of callbacks.
94  * All front-end functions operate on the buffer and if the buffer becomes
95  * empty or fills up, they ask the corresponding callback to handle the
96  * situation. Back-ends then differ just in the definition of the callbacks.
97  *
98  * The state of the fastbuf is represented by a <<struct_fastbuf,`struct fastbuf`>>,
99  * which is a simple structure describing the allocated buffer (`buffer`, `bufend`),
100  * the front-end cursor (`bptr`), the back-end cursor (`bstop`),
101  * position of the back-end cursor in the file (`pos`), some flags (`flags`)
102  * and pointers to the callback functions.
103  *
104  * Fastbuf can be in one of the following logical modes. Transitions between
105  * them are controlled by application.
106  *
107  * 1. Flushed:
108  *
109  *   * Initial state of newly created fastbuf, after @bflush(), seeking or similar functions.
110  *   * There is no cached data and application is free to decide whether to continue with
111  *     reading or writing (well, only if the back-end supports it). Any such operation
112  *     commits fastbuf to the corresponding non-flushed mode.
113  *
114  *   Buffer layout:
115  *    +------------------------------------+---------------------------+
116  *    | unused                             | free space                |
117  *    +------------------------------------+---------------------------+
118  *    ^              ^                     ^                           ^
119  *    buffer      <= bstop (BE pos)     <= bptr (FE pos)            <= bufend
120  *
121  *   * The pointers can be either all non-`NULL` (possibly equal) or all NULL.
122  *   * `bstop == bptr` in most back-ends, but it is not necessary. Some
123  *     in-memory streams take advantage of this.
124  *   * Reading (transition to reading mode) calls `refill` callback.
125  *   * Writing (transition to writing mode) can immediately call `spout`
126  *     callback, but not necessarily if `bptr < bufend` (notice that the
127  *     flushed buffer layout is compatible with writing).
128  *
129  * 2. Reading:
130  *
131  *   * Application has committed to reading.
132  *   * No writing is allowed until a flush operation (but see caveat below).
133  *
134  *   Buffer layout:
135  *    +------------------------------------+---------------------------+
136  *    | read data                          | unused                    |
137  *    +------------------------------------+---------------------------+
138  *    ^               ^                    ^                           ^
139  *    buffer       <= bptr (FE pos)     <= bstop (BE pos)           <= bufend
140  *
141  *   * Interval `[buffer, bstop]` contains a block of data read by the back-end.
142  *     `bptr` is front-end's cursor which points to the next character to
143  *     be read by application.
144  *   * If we reach `bptr == bstop` and need to read at least one more byte,
145  *     `refill` is called to bring more (or to detect EOF). Notice that this gives
146  *      us an easy way to implement @bungetc().
147  *   * CAVEAT: Switching to writing by @bflush() simply sets `bptr` to `bstop`
148  *     and calls `spout`. This can, depending on the type of back-end, lead to
149  *     loss of any remaining buffered data and/or breaking position of
150  *     front-end's cursor. You can seek afterwards to fix that, but it's
151  *     not possible in unseekable back-ends like network sockets. In such
152  *     cases it may be useful to create pair of fastbufs, one for reading
153  *     and one for writing. Also beware that switching may be unsupported/buggy
154  *     in some types of back-ends.
155  *
156  * 3. Writing:
157  *
158  *   * Application has committed to writing.
159  *   * No reading is allowed until a flush operation.
160  *   * You can also use @blush() to explicitly flush any buffered data.
161  *
162  *   Buffer layout:
163  *    +-----------------------+----------------+-----------------------+
164  *    | unused                | written data   | free space            |
165  *    +-----------------------+----------------+-----------------------+
166  *    ^            ^                           ^                       ^
167  *    buffer    <= bstop (BE pos)            < bptr (FE pos)        <= bufend
168  *
169  *   * `bptr` points at the position where the next character will be written to.
170  *      If we reach `bptr == bufend` and want to write more, `spout` is called
171  *      to flush the written data and get some free space.
172  *   * `bstop` usually points at the beginning of the written data,
173  *     but it is not necessary.
174  *
175  *
176  * Rules for back-ends:
177  *
178  *   - Front-ends are only allowed to change the value of `bptr`, some flags
179  *     and if a fatal error occurs, then also `bstop`. Back-ends can rely on it.
180  *   - `buffer <= bstop <= bufend` and `buffer <= bptr <= bufend` at any time.
181  *   - `pos` corresponds to `bstop` and usually contains the real offset of that
182  *     cursor in file (but back-ends can define the exact meaning of `pos` differently).
183  *     It can be modified by any back-end's callback, but the position of `bptr` (`pos + (bptr - bstop)`)
184  *     should stay unchanged after `refill` or `spout`.
185  *   - Failed callbacks (except `close`) should use @bthrow().
186  *   - Any callback may be NULL if not implemented.
187  *   - Callbacks can change not only `bptr` and `bstop`, but also the location and size of the buffer;
188  *     the fb-mem back-end takes advantage of it.
189  *
190  *   - Initialization:
191  *     * out: `buffer <= bstop <= bptr <= bufend`, possibly all equal or even NULL (flushed).
192  *     * @fb_tie() should be called on the newly created fastbuf.
193  *
194  *   - `refill`:
195  *     * in: `buffer <= bstop <= bptr <= bufend` (reading or flushed).
196  *     * out: `buffer <= bptr <= bstop <= bufend` (reading).
197  *     * Resulting `bptr == bstop` signals the end of file.
198  *       The next reading attempt will again call `refill` which can succeed this time.
199  *     * The callback must also return zero on EOF (iff `bptr == bstop`).
200  *
201  *   - `spout`:
202  *     * in: `buffer <= bstop <= bptr <= bufend` (writing or flushed).
203  *     * out: `buffer <= bstop <= bptr < bufend` (writing or flushed; at least 1 byte of free space).
204  *
205  *   - `seek`:
206  *     * in: `buffer <= bstop <= bptr <= bufend` (flushed).
207  *     * in: `(ofs >= 0 && whence == SEEK_SET) || (ofs <= 0 && whence == SEEK_END)`.
208  *     * out: `buffer <= bstop <= bptr <= bufend` (flushed).
209  *
210  *   - `close`:
211  *     * in: `buffer <= bstop <= bptr <= bufend` (flushed or after @bthrow()).
212  *     * `close` must always free all internal structures, even when it throws an exception.
213  ***/
214
215 /**
216  * This structure contains the state of the fastbuf. See the discussion above
217  * for how it works.
218  **/
219 struct fastbuf {
220   byte *bptr, *bstop;                           /* State of the buffer */
221   byte *buffer, *bufend;                        /* Start and end of the buffer */
222   char *name;                                   /* File name (used for error messages) */
223   ucw_off_t pos;                                /* Position of bstop in the file */
224   uint flags;                                   /* See enum fb_flags */
225   int (*refill)(struct fastbuf *);              /* Get a buffer with new data, returns 0 on EOF */
226   void (*spout)(struct fastbuf *);              /* Write buffer data to the file */
227   int (*seek)(struct fastbuf *, ucw_off_t, int);/* Slow path for @bseek(), buffer already flushed; returns success */
228   void (*close)(struct fastbuf *);              /* Close the stream */
229   int (*config)(struct fastbuf *, uint, int);   /* Configure the stream */
230   int can_overwrite_buffer;                     /* Can the buffer be altered? 0=never, 1=temporarily, 2=permanently */
231   struct resource *res;                         /* The fastbuf can be tied to a resource pool */
232 };
233
234 /**
235  * Fastbuf flags
236  */
237 enum fb_flags {
238   FB_DEAD = 0x1,                                /* Some fastbuf's method has thrown an exception */
239   FB_DIE_ON_EOF = 0x2,                          /* Most of read operations throw "fb.eof" on EOF */
240 };
241
242 /** Tie a fastbuf to a resource in the current resource pool. Returns the pointer to the same fastbuf. **/
243 struct fastbuf *fb_tie(struct fastbuf *b);      /* Tie fastbuf to a resource if there is an active pool */
244
245 /***
246  * === Fastbuf on files [[fbparam]]
247  *
248  * If you want to use fastbufs to access files, you can choose one of several
249  * back-ends and set their parameters.
250  ***/
251
252 /**
253  * Back-end types
254  */
255 enum fb_type {
256   FB_STD,                               /* Standard buffered I/O */
257   FB_DIRECT,                            /* Direct I/O bypassing system caches (see fb-direct.c for a description) */
258   FB_MMAP                               /* Memory mapped files */
259 };
260
261 /**
262  * When you open a file fastbuf, you can use this structure to select a back-end
263  * and set its parameters. If you want just an "ordinary" file stream, you can
264  * happily pass NULL instead and the defaults from the configuration file (or
265  * hard-wired defaults if no config file has been read) will be used.
266  */
267 struct fb_params {
268   enum fb_type type;                    /* The chosen back-end */
269   uint buffer_size;                     /* 0 for default size */
270   uint keep_back_buf;                   /* FB_STD: optimize for bi-directional access */
271   uint read_ahead;                      /* FB_DIRECT options */
272   uint write_back;
273   struct asio_queue *asio;
274 };
275
276 struct cf_section;
277 extern struct cf_section fbpar_cf;      /** Configuration section with which you can fill the `fb_params` **/
278 extern struct fb_params fbpar_def;      /** The default `fb_params` **/
279
280 /**
281  * Opens a file with file mode @mode (see the man page of open()).
282  * Use @params to select the fastbuf back-end and its parameters or
283  * pass NULL if you are fine with defaults.
284  *
285  * Raises `ucw.fb.open` if the file does not exist.
286  **/
287 struct fastbuf *bopen_file(const char *name, int mode, struct fb_params *params);
288 struct fastbuf *bopen_file_try(const char *name, int mode, struct fb_params *params); /** Like @bopen_file(), but returns NULL on failure. **/
289
290 /**
291  * Opens a temporary file.
292  * It is placed with other temp files and it is deleted when closed.
293  * Again, use NULL for @params if you want the defaults.
294  **/
295 struct fastbuf *bopen_tmp_file(struct fb_params *params);
296
297 /**
298  * Creates a fastbuf from a file descriptor @fd and sets its filename
299  * to @name (the name is used only in error messages).
300  * When the fastbuf is closed, the fd is closed as well. You can override
301  * this behavior by calling @bconfig().
302  */
303 struct fastbuf *bopen_fd_name(int fd, struct fb_params *params, const char *name);
304 static inline struct fastbuf *bopen_fd(int fd, struct fb_params *params) /** Same as above, but with an auto-generated filename. **/
305 {
306   return bopen_fd_name(fd, params, NULL);
307 }
308
309 /**
310  * Flushes all buffers and makes sure that they are written to the disk.
311  **/
312 void bfilesync(struct fastbuf *b);
313
314 /***
315  * === Fastbufs on regular files [[fbfile]]
316  *
317  * If you want to use the `FB_STD` back-end and not worry about setting
318  * up any parameters, there is a couple of shortcuts.
319  ***/
320
321 struct fastbuf *bopen(const char *name, uint mode, uint buflen);        /** Equivalent to @bopen_file() with `FB_STD` back-end. **/
322 struct fastbuf *bopen_try(const char *name, uint mode, uint buflen);    /** Equivalent to @bopen_file_try() with `FB_STD` back-end. **/
323 struct fastbuf *bopen_tmp(uint buflen);                                 /** Equivalent to @bopen_tmp_file() with `FB_STD` back-end. **/
324 struct fastbuf *bfdopen(int fd, uint buflen);                           /** Equivalent to @bopen_fd() with `FB_STD` back-end. **/
325 struct fastbuf *bfdopen_shared(int fd, uint buflen);                    /** Like @bfdopen(), but it does not close the @fd on @bclose(). **/
326
327 /***
328  * === Temporary files [[fbtemp]]
329  *
330  * Usually, @bopen_tmp_file() is the best way how to come to a temporary file.
331  * However, in some specific cases you can need more, so there is also a set
332  * of more general functions.
333  ***/
334
335 #define TEMP_FILE_NAME_LEN 256
336
337 /**
338  * Generates a temporary filename and stores it to the @name_buf (of size
339  * at least * `TEMP_FILE_NAME_LEN`). If @open_flags are not NULL, flags that
340  * should be OR-ed with other flags to open() will be stored there.
341  *
342  * The location and style of temporary files is controlled by the configuration.
343  * By default, the system temp directory (`$TMPDIR` or `/tmp`) is used.
344  *
345  * If the location is a publicly writeable directory (like `/tmp`), the
346  * generated filename cannot be guaranteed to be unique, so @open_flags
347  * will include `O_EXCL` and you have to check the result of open() and
348  * iterate if needed.
349  *
350  * This function is not specific to fastbufs, it can be used separately.
351  **/
352 void temp_file_name(char *name_buf, int *open_flags);
353
354 /**
355  * Opens a temporary file and returns its file descriptor.
356  * You specify the file @mode and @open_flags passed to open().
357  *
358  * If the @name_buf (of at last `TEMP_FILE_NAME_LEN` chars) is not NULL,
359  * the filename is also stored in it.
360  *
361  * This function is not specific to fastbufs, it can be used separately.
362  */
363 int open_tmp(char *name_buf, int open_flags, int mode);
364
365 /**
366  * Sometimes, a file is created as temporary and then moved to a stable
367  * location. This function takes a fastbuf created by @bopen_tmp_file()
368  * or @bopen_tmp(), marks it as permanent, closes it and renames it to
369  * @name.
370  *
371  * Please note that it assumes that the temporary file and the @name
372  * are on the same volume (otherwise, rename() fails), so you might
373  * want to configure a special location for the temporary files
374  * beforehand.
375  */
376 void bfix_tmp_file(struct fastbuf *fb, const char *name);
377
378 /* Internal functions of some file back-ends */
379
380 struct fastbuf *bfdopen_internal(int fd, const char *name, uint buflen);
381 struct fastbuf *bfmmopen_internal(int fd, const char *name, uint mode);
382
383 #ifdef CONFIG_UCW_FB_DIRECT
384 extern uint fbdir_cheat;
385 struct asio_queue;
386 struct fastbuf *fbdir_open_fd_internal(int fd, const char *name, struct asio_queue *io_queue, uint buffer_size, uint read_ahead, uint write_back);
387 #endif
388
389 void bclose_file_helper(struct fastbuf *f, int fd, int is_temp_file);
390
391 /***
392  * === Fastbufs on file fragments [[fblim]]
393  *
394  * The `fblim` back-end reads from a file handle, but at most a given
395  * number of bytes. This is frequently used for reading from sockets.
396  ***/
397
398 struct fastbuf *bopen_limited_fd(int fd, uint bufsize, uint limit); /** Create a fastbuf which reads at most @limit bytes from @fd. **/
399
400 /***
401  * === Fastbufs on in-memory streams [[fbmem]]
402  *
403  * The `fbmem` back-end keeps the whole contents of the stream
404  * in memory (as a linked list of memory blocks, so address space
405  * fragmentation is avoided).
406  *
407  * First, you use @fbmem_create() to create the stream and the fastbuf
408  * used for writing to it. Then you can call @fbmem_clone_read() to get
409  * an arbitrary number of fastbuf for reading from the stream.
410  ***/
411
412 struct fastbuf *fbmem_create(uint blocksize);           /** Create stream and return its writing fastbuf. **/
413 struct fastbuf *fbmem_clone_read(struct fastbuf *f);    /** Given a writing fastbuf, create a new reading fastbuf. **/
414
415 /***
416  * === Fastbufs on static buffers [[fbbuf]]
417  *
418  * The `fbbuf` back-end stores the stream in a given block of memory.
419  * This is useful for parsing and generating of complex data structures.
420  ***/
421
422 /**
423  * Creates a read-only fastbuf that takes its data from a given buffer.
424  * The fastbuf structure is allocated by the caller and pointed to by @f.
425  * The @buffer and @size specify the location and size of the buffer.
426  *
427  * In some cases, the front-ends can take advantage of rewriting the contents
428  * of the buffer temporarily. In this case, set @can_overwrite as described
429  * in <<internal,Internals>>. If you do not care, keep @can_overwrite zero.
430  *
431  * A @bclose() on this fastbuf is allowed and it does nothing.
432  */
433 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uint size, uint can_overwrite);
434
435 /**
436  * Creates a write-only fastbuf which writes into a provided memory buffer.
437  * The fastbuf structure is allocated by the caller and pointed to by @f.
438  * An attempt to write behind the end of the buffer causes the `ucw.fb.write` exception.
439  *
440  * Data are written directly into the buffer, so it is not necessary to call @bflush()
441  * at any moment.
442  *
443  * A @bclose() on this fastbuf is allowed and it does nothing.
444  */
445 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uint size);
446
447 static inline uint fbbuf_count_written(struct fastbuf *f) /** Calculates, how many bytes were already written into the buffer. **/
448 {
449   return f->bptr - f->bstop;
450 }
451
452 /***
453  * === Fastbuf on recyclable growing buffers [[fbgrow]]
454  *
455  * The `fbgrow` back-end keeps the stream in a contiguous buffer stored in the
456  * main memory, but unlike <<fbmem,`fbmem`>>, the buffer does not have a fixed
457  * size and it is expanded to accomodate all data.
458  *
459  * At every moment, you can use `fastbuf->buffer` to gain access to the stream.
460  ***/
461
462 struct mempool;
463
464 struct fastbuf *fbgrow_create(uint basic_size);         /** Create the growing buffer pre-allocated to @basic_size bytes. **/
465 struct fastbuf *fbgrow_create_mp(struct mempool *mp, uint basic_size); /** Create the growing buffer pre-allocated to @basic_size bytes. **/
466 void fbgrow_reset(struct fastbuf *b);                   /** Reset stream and prepare for writing. **/
467 void fbgrow_rewind(struct fastbuf *b);                  /** Prepare for reading (of already written data). **/
468
469 /**
470  * Can be used in any state of @b (for example when writing or after
471  * @fbgrow_rewind()) to return the pointer to internal buffer and its length in
472  * bytes. The returned buffer can be invalidated by further requests.
473  **/
474 uint fbgrow_get_buf(struct fastbuf *b, byte **buf);
475
476 /***
477  * === Fastbuf on memory pools [[fbpool]]
478  *
479  * The write-only `fbpool` back-end also keeps the stream in a contiguous
480  * buffer, but this time the buffer is allocated from within a memory pool.
481  ***/
482
483 struct fbpool { /** Structure for fastbufs & mempools. **/
484   struct fastbuf fb;
485   struct mempool *mp;
486 };
487
488 /**
489  * Initialize a new `fbpool`. The structure is allocated by the caller.
490  * Calling @bclose() is optional.
491  **/
492 void fbpool_init(struct fbpool *fb);    /** Initialize a new mempool fastbuf. **/
493 /**
494  * Start a new continuous block and prepare for writing (see <<mempool:mp_start()>>).
495  * Provide the memory pool you want to use for this block as @mp.
496  **/
497 void fbpool_start(struct fbpool *fb, struct mempool *mp, size_t init_size);
498 /**
499  * Close the block and return the address of its start (see <<mempool:mp_end()>>).
500  * The length can be determined by calling <<mempool:mp_size(mp, ptr)>>.
501  **/
502 void *fbpool_end(struct fbpool *fb);
503
504 /***
505  * === Atomic files for multi-threaded programs [[fbatomic]]
506  *
507  * This fastbuf backend is designed for cases when several threads
508  * of a single program append records to a common file and while the
509  * record can mix in an arbitrary way, the bytes inside a single
510  * record must remain uninterrupted.
511  *
512  * In case of files with fixed record size, we just allocate the
513  * buffer to hold a whole number of records and take advantage
514  * of the atomicity of the write() system call.
515  *
516  * With variable-sized records, we need another solution: when
517  * writing a record, we keep the fastbuf in a locked state, which
518  * prevents buffer flushing (and if the buffer becomes full, we extend it),
519  * and we wait for an explicit commit operation which write()s the buffer
520  * if the free space in the buffer falls below the expected maximum record
521  * length.
522  *
523  * Please note that initialization of the clones is not thread-safe,
524  * so you have to serialize it yourself.
525  ***/
526
527 struct fb_atomic {
528   struct fastbuf fb;
529   struct fb_atomic_file *af;
530   byte *expected_max_bptr;
531   uint slack_size;
532 };
533
534 /**
535  * Open an atomic fastbuf.
536  * If @master is NULL, the file @name is opened. If it is non-null,
537  * a new clone of an existing atomic fastbuf is created.
538  *
539  * If the file has fixed record length, just set @record_len to it.
540  * Otherwise set @record_len to the expected maximum record length
541  * with a negative sign (you need not fit in this length, but as long
542  * as you do, the fastbuf is more efficient) and call @fbatomic_commit()
543  * after each record.
544  *
545  * You can specify @record_len, if it is known (for optimisations).
546  *
547  * The file is closed when all fastbufs using it are closed.
548  **/
549 struct fastbuf *fbatomic_open(const char *name, struct fastbuf *master, uint bufsize, int record_len);
550 void fbatomic_internal_write(struct fastbuf *b);
551
552 /**
553  * Declare that you have finished writing a record. This is required only
554  * if a fixed record size was not specified.
555  **/
556 static inline void fbatomic_commit(struct fastbuf *b)
557 {
558   if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
559     fbatomic_internal_write(b);
560 }
561
562 /*** === Null fastbufs ***/
563
564 /**
565  * Creates a new "/dev/null"-like  fastbuf.
566  * Any read attempt returns an EOF, any write attempt is silently ignored.
567  **/
568 struct fastbuf *fbnull_open(uint bufsize);
569
570 /**
571  * Can be used by any back-end to switch it to the null mode.
572  * You need to provide at least one byte long buffer for writing.
573  **/
574 void fbnull_start(struct fastbuf *b, byte *buf, uint bufsize);
575
576 /**
577  * Checks whether a fastbuf has been switched to the null mode.
578  **/
579 bool fbnull_test(struct fastbuf *b);
580
581 /***
582  * === Fastbufs atop other fastbufs [[fbmulti]]
583  *
584  * Imagine some code which does massive string processing. It takes an input
585  * buffer, writes a part of it into an output buffer, then some other string
586  * and then the remaining part of the input buffer. Or anything else where you
587  * copy all the data at each stage of the complicated process.
588  *
589  * This backend takes multiple fastbufs and concatenates them formally into
590  * one. You may then read them consecutively as they were one fastbuf at all.
591  *
592  * This backend is read-only.
593  *
594  * This backend is seekable iff all of the supplied fastbufs are seekable.
595  *
596  * You aren't allowed to do anything with the underlying buffers while these
597  * are connected into fbmulti.
598  *
599  * The fbmulti is inited by @fbmulti_create(). It returns an empty fbmulti.
600  * Then you call @fbmulti_append() for each fbmulti.
601  *
602  * If @bclose() is called on fbmulti, all the underlying buffers get closed
603  * recursively.
604  *
605  * If you want to keep an underlying fastbuf open after @bclose, just remove it
606  * by @fbmulti_remove where the second parameter is a pointer to the removed
607  * fastbuf. If you pass NULL, all the underlying fastbufs are removed.
608  *
609  * After @fbmulti_remove, the state of the fbmulti is undefined. The only allowed
610  * operation is either another @fbmulti_remove or @bclose on the fbmulti.
611  ***/
612
613 /**
614  * Create an empty fbmulti
615  **/
616 struct fastbuf *fbmulti_create(void);
617
618 /**
619  * Append a fb to fbmulti
620  **/
621 void fbmulti_append(struct fastbuf *f, struct fastbuf *fb);
622
623 /**
624  * Remove a fb from fbmulti
625  **/
626 void fbmulti_remove(struct fastbuf *f, struct fastbuf *fb);
627
628 /*** === Configuring stream parameters [[bconfig]] ***/
629
630 enum bconfig_type {                     /** Parameters that could be configured. **/
631   BCONFIG_IS_TEMP_FILE,                 /* 0=normal file, 1=temporary file, 2=shared fd */
632   BCONFIG_KEEP_BACK_BUF,                /* Optimize for bi-directional access */
633 };
634
635 int bconfig(struct fastbuf *f, uint type, int data); /** Configure a fastbuf. Returns previous value. **/
636
637 /*** === Universal functions working on all fastbuf's [[ffbasic]] ***/
638
639 /**
640  * Close and free fastbuf.
641  * Some kinds of fastbufs are allocated by the caller (e.g., in @fbbuf_init_read());
642  * in such cases, @bclose() does not free any memory.
643  */
644 void bclose(struct fastbuf *f);
645 void bthrow(struct fastbuf *f, const char *id, const char *fmt, ...) FORMAT_CHECK(printf,3,4) NONRET;   /** Throw exception on a given fastbuf **/
646 int brefill(struct fastbuf *f, int allow_eof);
647 void bspout(struct fastbuf *f);
648 void bflush(struct fastbuf *f);                                 /** Write data (if it makes any sense, do not use for in-memory buffers). **/
649 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. **/
650 void bsetpos(struct fastbuf *f, ucw_off_t pos);                 /** Set position to @pos bytes from beginning. Only for seekable fastbufs. **/
651 void brewind(struct fastbuf *f);                                /** Go to the beginning of the fastbuf. Only for seekable ones. **/
652 ucw_off_t bfilesize(struct fastbuf *f);                         /** How large is the file? -1 if not seekable. **/
653
654 static inline ucw_off_t btell(struct fastbuf *f)                /** Where am I (from the beginning)? **/
655 {
656   return f->pos + (f->bptr - f->bstop);
657 }
658
659 int bgetc_slow(struct fastbuf *f);
660 static inline int bgetc(struct fastbuf *f)                      /** Return next character from the buffer. **/
661 {
662   return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
663 }
664
665 int bpeekc_slow(struct fastbuf *f);
666 static inline int bpeekc(struct fastbuf *f)                     /** Return next character from the buffer, but keep the current position. **/
667 {
668   return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
669 }
670
671 int beof_slow(struct fastbuf *f);
672 static inline int beof(struct fastbuf *f)                       /** Have I reached EOF? **/
673 {
674   return (f->bptr < f->bstop) ? 0 : beof_slow(f);
675 }
676
677 static inline void bungetc(struct fastbuf *f)                   /** Return last read character back. Only one back is guaranteed to work. **/
678 {
679   f->bptr--;
680 }
681
682 void bputc_slow(struct fastbuf *f, uint c);
683 static inline void bputc(struct fastbuf *f, uint c)             /** Write a single character. **/
684 {
685   if (f->bptr < f->bufend)
686     *f->bptr++ = c;
687   else
688     bputc_slow(f, c);
689 }
690
691 static inline uint bavailr(struct fastbuf *f)                   /** Return the length of the cached data to be read. Do not use directly. **/
692 {
693   return f->bstop - f->bptr;
694 }
695
696 static inline uint bavailw(struct fastbuf *f)                   /** Return the length of the buffer available for writing. Do not use directly. **/
697 {
698   return f->bufend - f->bptr;
699 }
700
701 uint bread_slow(struct fastbuf *f, void *b, uint l, uint check);
702 /**
703  * Read at most @l bytes of data into @b.
704  * Returns number of bytes read.
705  * 0 means end of file.
706  */
707 static inline uint bread(struct fastbuf *f, void *b, uint l)
708 {
709   if (bavailr(f) >= l)
710     {
711       memcpy(b, f->bptr, l);
712       f->bptr += l;
713       return l;
714     }
715   else
716     return bread_slow(f, b, l, 0);
717 }
718
719 /**
720  * Reads exactly @l bytes of data into @b.
721  * If at the end of file, it returns 0.
722  * If there are data, but less than @l, it raises `ucw.fb.eof`.
723  */
724 static inline uint breadb(struct fastbuf *f, void *b, uint l)
725 {
726   if (bavailr(f) >= l)
727     {
728       memcpy(b, f->bptr, l);
729       f->bptr += l;
730       return l;
731     }
732   else
733     return bread_slow(f, b, l, 1);
734 }
735
736 void bwrite_slow(struct fastbuf *f, const void *b, uint l);
737 static inline void bwrite(struct fastbuf *f, const void *b, uint l) /** Writes buffer @b of length @l into fastbuf. **/
738 {
739   if (bavailw(f) >= l)
740     {
741       memcpy(f->bptr, b, l);
742       f->bptr += l;
743     }
744   else
745     bwrite_slow(f, b, l);
746 }
747
748 /**
749  * Reads a line into @b and strips trailing `\n`.
750  * Returns pointer to the terminating 0 or NULL on `EOF`.
751  * Raises `ucw.fb.toolong` if the line is longer than @l.
752  **/
753 char *bgets(struct fastbuf *f, char *b, uint l);
754 char *bgets0(struct fastbuf *f, char *b, uint l);       /** The same as @bgets(), but for 0-terminated strings. **/
755 /**
756  * Returns either length of read string (excluding the terminator) or -1 if it is too long.
757  * In such cases exactly @l bytes are read.
758  */
759 int bgets_nodie(struct fastbuf *f, char *b, uint l);
760
761 struct mempool;
762 struct bb_t;
763 /**
764  * Read a string, strip the trailing `\n` and store it into growing buffer @b.
765  * Raises `ucw.fb.toolong` if the line is longer than @limit.
766  **/
767 uint bgets_bb(struct fastbuf *f, struct bb_t *b, uint limit);
768 /**
769  * Read a string, strip the trailing `\n` and store it into buffer allocated from a memory pool.
770  **/
771 char *bgets_mp(struct fastbuf *f, struct mempool *mp);
772
773 struct bgets_stk_struct {
774   struct fastbuf *f;
775   byte *old_buf, *cur_buf, *src;
776   uint old_len, cur_len, src_len;
777 };
778 void bgets_stk_init(struct bgets_stk_struct *s);
779 void bgets_stk_step(struct bgets_stk_struct *s);
780
781 /**
782  * Read a string, strip the trailing `\n` and store it on the stack (allocated using alloca()).
783  **/
784 #define bgets_stk(fb) \
785   ({ 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; })
786
787 /**
788  * Write a string, without 0 or `\n` at the end.
789  **/
790 static inline void bputs(struct fastbuf *f, const char *b)
791 {
792   bwrite(f, b, strlen(b));
793 }
794
795 /**
796  * Write string, including terminating 0.
797  **/
798 static inline void bputs0(struct fastbuf *f, const char *b)
799 {
800   bwrite(f, b, strlen(b)+1);
801 }
802
803 /**
804  * Write string and append a newline to the end.
805  **/
806 static inline void bputsn(struct fastbuf *f, const char *b)
807 {
808   bputs(f, b);
809   bputc(f, '\n');
810 }
811
812 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uint l);
813 /**
814  * Copy @l bytes of data from fastbuf @f to fastbuf @t.
815  * `UINT_MAX` (`~0U`) means all data, even if more than `UINT_MAX` bytes remain.
816  **/
817 static inline void bbcopy(struct fastbuf *f, struct fastbuf *t, uint l)
818 {
819   if (bavailr(f) >= l && bavailw(t) >= l)
820     {
821       memcpy(t->bptr, f->bptr, l);
822       t->bptr += l;
823       f->bptr += l;
824     }
825   else
826     bbcopy_slow(f, t, l);
827 }
828
829 int bskip_slow(struct fastbuf *f, uint len);
830 static inline int bskip(struct fastbuf *f, uint len) /** Skip @len bytes without reading them. **/
831 {
832   if (bavailr(f) >= len)
833     {
834       f->bptr += len;
835       return 1;
836     }
837   else
838     return bskip_slow(f, len);
839 }
840
841 /*** === Direct I/O on buffers ***/
842
843 /**
844  * Begin direct reading from fastbuf's internal buffer to avoid unnecessary copying.
845  * The function returns a buffer @buf together with its length in bytes (zero means EOF)
846  * with cached data to be read.
847  *
848  * Some back-ends allow the user to modify the data in the returned buffer to avoid unnecessary.
849  * If the back-end allows such modifications, it can set `f->can_overwrite_buffer` accordingly:
850  *
851  *   - 0 if no modification is allowed,
852  *   - 1 if the user can modify the buffer on the condition that
853  *       the modifications will be undone before calling the next
854  *       fastbuf operation
855  *   - 2 if the user is allowed to overwrite the data in the buffer
856  *       if @bdirect_read_commit_modified() is called afterwards.
857  *       In this case, the back-end must be prepared for trimming
858  *       of the buffer which is done by the commit function.
859  *
860  * The reading must be ended by @bdirect_read_commit() or @bdirect_read_commit_modified(),
861  * unless the user did not read or modify anything.
862  **/
863 static inline uint bdirect_read_prepare(struct fastbuf *f, byte **buf)
864 {
865   if (f->bptr == f->bstop && !f->refill(f))
866     {
867       *buf = NULL;  // This is not needed, but it helps to get rid of spurious warnings
868       return 0;
869     }
870   *buf = f->bptr;
871   return bavailr(f);
872 }
873
874 /**
875  * End direct reading started by @bdirect_read_prepare() and move the cursor at @pos.
876  * Data in the returned buffer must be same as after @bdirect_read_prepare() and
877  * @pos must point somewhere inside the buffer.
878  **/
879 static inline void bdirect_read_commit(struct fastbuf *f, byte *pos)
880 {
881   f->bptr = pos;
882 }
883
884 /**
885  * Similar to @bdirect_read_commit(), but accepts also modified data before @pos.
886  * Note that such modifications are supported only if `f->can_overwrite_buffer == 2`.
887  **/
888 static inline void bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
889 {
890   f->bptr = pos;
891   f->buffer = pos;      /* Avoid seeking backwards in the buffer */
892 }
893
894 /**
895  * Start direct writing to fastbuf's internal buffer to avoid copy overhead.
896  * The function returns the length of the buffer in @buf (at least one byte)
897  * where we can write to. The operation must be ended by @bdirect_write_commit(),
898  * unless nothing is written.
899  **/
900 static inline uint bdirect_write_prepare(struct fastbuf *f, byte **buf)
901 {
902   if (f->bptr == f->bufend)
903     f->spout(f);
904   *buf = f->bptr;
905   return bavailw(f);
906 }
907
908 /**
909  * Commit the data written to the buffer returned by @bdirect_write_prepare().
910  * The length is specified by @pos which must point just after the written data.
911  * Also moves the cursor to @pos.
912  **/
913 static inline void bdirect_write_commit(struct fastbuf *f, byte *pos)
914 {
915   f->bptr = pos;
916 }
917
918 /*** === Formatted output ***/
919
920 /**
921  * printf into a fastbuf.
922  **/
923 int bprintf(struct fastbuf *b, const char *msg, ...)
924   FORMAT_CHECK(printf,2,3);
925 int vbprintf(struct fastbuf *b, const char *msg, va_list args); /** vprintf into a fastbuf. **/
926
927 #endif