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