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