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