2 * UCW Library -- Fast Buffered I/O
4 * (c) 1997--2007 Martin Mares <mj@ucw.cz>
5 * (c) 2004 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
11 #ifndef _UCW_FASTBUF_H
12 #define _UCW_FASTBUF_H
18 * Generic buffered I/O. You supply hooks to be called for low-level operations
19 * (swapping of buffers, seeking and closing), we do the rest.
21 * Buffer layout when reading:
23 * +----------------+---------------------------+
24 * | read data | free space |
25 * +----------------+---------------------------+
27 * buffer bptr bstop bufend
29 * After the last character is read, +bptr == bstop+ and buffer refill
30 * is deferred to the next read attempt. This gives us an easy way
31 * how to implement +bungetc()+.
35 * +--------+--------------+--------------------+
36 * | unused | written data | free space |
37 * +--------+--------------+--------------------+
39 * buffer bstop bptr bufend
43 * - You can mix reads and writes on the same stream, but you must
44 * call +bflush()+ in between and remember that the file position
45 * points after the flushed buffer which is not necessarily the same
46 * as after the data you've read.
47 * - The spout/refill hooks can change not only bptr and bstop, but also
48 * the location of the buffer; +fb-mem.c+ takes advantage of it.
49 * - In some cases, the user of the +bdirect+ interface can be allowed to modify
50 * the data in the buffer to avoid unnecessary copying. If the back-end
51 * allows such modifications, it can set +can_overwrite_buffer+ accordingly:
52 * * 0 if no modification is allowed,
53 * * 1 if the user can modify the buffer on the condition that
54 * the modifications will be undone before calling the next
56 * * 2 if the user is allowed to overwrite the data in the buffer
57 * if +bdirect_read_commit_modified()+ is called afterwards.
58 * In this case, the back-end must be prepared for trimming
59 * of the buffer which is done by the commit function.
67 * This structure is of main interest to fastbuf backends,
68 * it can be considered a black box for use.
71 byte is_fastbuf[0]; /* Dummy field for checking of type casts */
72 byte *bptr, *bstop; /* Access pointers */
73 byte *buffer, *bufend; /* Start and end of the buffer */
74 char *name; /* File name for error messages */
75 ucw_off_t pos; /* Position of bstop in the file */
76 int (*refill)(struct fastbuf *); /* Get a buffer with new data */
77 void (*spout)(struct fastbuf *); /* Write buffer data to the file */
78 int (*seek)(struct fastbuf *, ucw_off_t, int);/* Slow path for bseek(), buffer already flushed; returns success */
79 void (*close)(struct fastbuf *); /* Close the stream */
80 int (*config)(struct fastbuf *, uns, int); /* Configure the stream */
81 int can_overwrite_buffer; /* Can the buffer be altered? (see discussion above) 0=never, 1=temporarily, 2=permanently */
84 /*** === FastIO on files with several configurable back-ends ***/
87 * Which back-end do you want to use?
90 FB_STD, /* Standard buffered I/O */
91 FB_DIRECT, /* Direct I/O bypassing system caches (see +fb-direct.c+ for a description) */
92 FB_MMAP /* Memory mapped files */
96 * A way to configure created fastbuf.
100 uns buffer_size; /* 0 for default size. */
101 uns keep_back_buf; /* FB_STD: optimize for bi-directional access. */
102 uns read_ahead; /* FB_DIRECT options. */
104 struct asio_queue *asio;
108 extern struct cf_section fbpar_cf; /** Config. Can be used by fastbuf systems. **/
109 extern struct fb_params fbpar_def; /** Default parameters. **/
113 * Use +@params = NULL+ for defaults.
114 * See standard unix +open+ for information about @mode.
116 struct fastbuf *bopen_file(const char *name, int mode, struct fb_params *params);
117 struct fastbuf *bopen_file_try(const char *name, int mode, struct fb_params *params); /** Tries to open a file (does not die, if unsuccessful). **/
120 * Opens a temporary file.
121 * It is placed with other temp files and is deleted when closed.
123 struct fastbuf *bopen_tmp_file(struct fb_params *params);
125 * Creates a fastbuf (wrapper) from a file descriptor.
126 * Sets it's filename to @name (used when outputting errors).
128 struct fastbuf *bopen_fd_name(int fd, struct fb_params *params, const char *name);
129 static inline struct fastbuf *bopen_fd(int fd, struct fb_params *params) /** Same as above, but with empty filename. **/
131 return bopen_fd_name(fd, params, NULL);
135 * FastIO on standard files (shortcuts for FB_STD)
136 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
140 * Opens a file in a usual way (with system cache enabled).
141 * Use +@buflen = 0+ for default buffer size.
142 * Dies if unsuccessful.
144 struct fastbuf *bopen(const char *name, uns mode, uns buflen);
145 struct fastbuf *bopen_try(const char *name, uns mode, uns buflen);/** Same as +bopen+, but does not die when unsuccessful. **/
146 struct fastbuf *bopen_tmp(uns buflen);/** Opens a temporary file (read-write). Deletes it, when closed. **/
147 struct fastbuf *bfdopen(int fd, uns buflen);/** Wraps a filedescriptor into a fastbuf. **/
148 struct fastbuf *bfdopen_shared(int fd, uns buflen);/** Wraps a filedescriptor and marks it as shared. **/
149 void bfilesync(struct fastbuf *b);/** Sync file to disk. **/
151 /*** === Temporary files ***/
153 #define TEMP_FILE_NAME_LEN 256 /** Maximum length of temp file name. **/
155 * Generates a temporary filename.
156 * Provide a buffer (as @name_buf, at last +TEMP_FILE_NAME_LEN+ long) to store the name into.
157 * If @open_flags are not +NULL+, flags that should be ored with other flags to +open+ will be set.
159 * The provided name can already exist.
160 * If it is not safe to overwrite existing files, +O_EXCL+ is specified in @open_flags.
161 * Check for the result of +open+.
163 * This is not specific to fastbufs, can be used separately.
165 void temp_file_name(char *name_buf, int *open_flags);
167 * Renames a temp fastbuf to given @name and marks it permanent (so it will not be deleted when closed).
168 * The fastbuf is closed by this call.
170 void bfix_tmp_file(struct fastbuf *fb, const char *name);
172 * Opens a temporary file and returns it as file descriptor.
173 * You specify open @mode and @open_flags.
175 * If @name_buf (at last +TEMP_FILE_NAME_LEN+ long) is not +NULL+, the filename is stored there.
177 * This is not specific to fastbufs, can be used separately.
179 int open_tmp(char *name_buf, int open_flags, int mode);
181 /* Internal functions of some file back-ends */
183 struct fastbuf *bfdopen_internal(int fd, const char *name, uns buflen);
184 struct fastbuf *bfmmopen_internal(int fd, const char *name, uns mode);
186 extern uns fbdir_cheat;
188 struct fastbuf *fbdir_open_fd_internal(int fd, const char *name, struct asio_queue *io_queue, uns buffer_size, uns read_ahead, uns write_back);
190 void bclose_file_helper(struct fastbuf *f, int fd, int is_temp_file);
193 * FastIO on in-memory streams
194 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~
195 * These behaves in a way similar to unix pipes.
196 * You create one for writing and another for reading.
197 * What you write to the first one can be read from the other.
200 struct fastbuf *fbmem_create(uns blocksize); /** Create stream and return its writing fastbuf. **/
201 struct fastbuf *fbmem_clone_read(struct fastbuf *); /** Create reading fastbuf. **/
203 /*** === FastI on file descriptors with limit ***/
206 * Wrap a file descriptor @fd into a fastbuf.
207 * No more than @limit bytes will be read/written in the lifetime of this fastbuf.
209 struct fastbuf *bopen_limited_fd(int fd, uns bufsize, uns limit);
211 /*** === FastIO on static buffers ***/
214 * Creates a fastbuf that takes data from a memory buffer.
215 * The fastbuf is not allocated, it is initialized in @f.
216 * @buffer and @size specify the buffer with data.
217 * See top of this file for info about @can_overwrite.
219 * No resources are alocated by this, so you do not need to free it.
220 * It is not possible to close this fastbuf.
222 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uns size, uns can_overwrite);
224 * Creates a fastbuf which writes into a provided memory buffer.
225 * Write over the end dies.
227 * No resources are allocated by this and you can not close this fastbuf.
229 * Data are written directly into the buffer, no need for flushes.
231 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uns size);
232 static inline uns fbbuf_count_written(struct fastbuf *f) /** How many bytes were written into the buffer already? **/
234 return f->bptr - f->bstop;
237 /*** === FastIO on recyclable growing buffers ***/
239 struct fastbuf *fbgrow_create(unsigned basic_size); /** Create the growing buffer, with pre-allocated size @basic_size. **/
240 void fbgrow_reset(struct fastbuf *b); /** Reset stream and prepare for writing. **/
241 void fbgrow_rewind(struct fastbuf *b); /** Prepare for reading (of already written data). **/
244 * FastO on memory pools
245 * ~~~~~~~~~~~~~~~~~~~~~
246 * You write to it and get buffers of written data.
250 struct fbpool { /** Structure for fastbufs & mempools. **/
255 void fbpool_init(struct fbpool *fb); /** Initialize a new mempool fastbuf. **/
257 * Start a new continuous block and prepare for writing (see +mp_start()+).
258 * Provide the memory pool you want to use for this block (in @mp).
260 void fbpool_start(struct fbpool *fb, struct mempool *mp, uns init_size);
262 * Close the block and return its address (see +mp_end()+).
263 * The length can be determined with +mp_size(mp, ptr)+.
265 void *fbpool_end(struct fbpool *fb);
268 * === FastO with atomic writes for multi-threaded programs
269 * Use them, when you need to write records into single file from several threads.
270 * It does not ensure order of the records, but they will not intersect.
275 struct fb_atomic_file *af;
276 byte *expected_max_bptr;
279 #define FB_ATOMIC(f) ((struct fb_atomic *)(f)->is_fastbuf)
282 * Open an atomic fastbuf.
283 * If you specify @master, it is used to write into it (both the master
284 * and the new one will be the same file, with separate buffers).
285 * If @master is +NULL+, a file @name is opened.
287 * You can specify @record_len, if it is known (for optimisations).
289 * The file is closed when all fastbufs using it are closed.
291 struct fastbuf *fbatomic_open(const char *name, struct fastbuf *master, uns bufsize, int record_len);
292 void fbatomic_internal_write(struct fastbuf *b);
295 * Commit the last record.
296 * It may not yet write it to the file, but it will stay together.
298 static inline void fbatomic_commit(struct fastbuf *b)
300 if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
301 fbatomic_internal_write(b);
304 /*** === Configuring stream parameters ***/
306 enum bconfig_type { /** Parameters that could be configured. **/
307 BCONFIG_IS_TEMP_FILE, /* 0=normal file, 1=temporary file, 2=shared fd */
308 BCONFIG_KEEP_BACK_BUF, /* Optimize for bi-directional access */
311 int bconfig(struct fastbuf *f, uns type, int data); /** Configure a fastbuf. Returns previous value. **/
313 /*** === Universal functions working on all fastbuf's ***/
316 * Close and free fastbuf.
317 * Can not be used for fastbufs not returned from function (initialized in a parameter, for example the one from +fbbuf_init_read+).
319 void bclose(struct fastbuf *f);
320 void bflush(struct fastbuf *f); /** Write data (if it makes any sense, do not use for in-memory buffers). **/
321 void bseek(struct fastbuf *f, ucw_off_t pos, int whence); /** Seek in the buffer. See +man fseek+ for description of @whence. Only for seekable fastbufs. **/
322 void bsetpos(struct fastbuf *f, ucw_off_t pos); /** Set position to @pos bytes from beginning. Only for seekable fastbufs. **/
323 void brewind(struct fastbuf *f); /** Go to the beginning of the fastbuf. Only for seekable ones. **/
324 ucw_off_t bfilesize(struct fastbuf *f); /** How large is the file? -1 if not seekable. **/
326 static inline ucw_off_t btell(struct fastbuf *f) /** Where am I (from the beginning)? **/
328 return f->pos + (f->bptr - f->bstop);
331 int bgetc_slow(struct fastbuf *f);
332 static inline int bgetc(struct fastbuf *f) /** Return next character from the buffer. **/
334 return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
337 int bpeekc_slow(struct fastbuf *f);
338 static inline int bpeekc(struct fastbuf *f) /** Return next character from the buffer, but keep the current position. **/
340 return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
343 static inline void bungetc(struct fastbuf *f) /** Return last read character back. Only one back is guaranteed to work. **/
348 void bputc_slow(struct fastbuf *f, uns c);
349 static inline void bputc(struct fastbuf *f, uns c) /** Write a single character. **/
351 if (f->bptr < f->bufend)
357 static inline uns bavailr(struct fastbuf *f)
359 return f->bstop - f->bptr;
362 static inline uns bavailw(struct fastbuf *f)
364 return f->bufend - f->bptr;
367 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check);
369 * Read at most @l bytes of data into @b.
370 * Returns number of bytes read.
371 * 0 means end of file.
373 static inline uns bread(struct fastbuf *f, void *b, uns l)
377 memcpy(b, f->bptr, l);
382 return bread_slow(f, b, l, 0);
386 * Reads exactly @l bytes of data into @b.
387 * If at the end of file, it returns 0.
388 * If there are data, but less than @l, it dies.
390 static inline uns breadb(struct fastbuf *f, void *b, uns l)
394 memcpy(b, f->bptr, l);
399 return bread_slow(f, b, l, 1);
402 void bwrite_slow(struct fastbuf *f, const void *b, uns l);
403 static inline void bwrite(struct fastbuf *f, const void *b, uns l) /** Writes buffer @b of length @l into fastbuf. **/
407 memcpy(f->bptr, b, l);
411 bwrite_slow(f, b, l);
415 * Reads a line into @b and strips trailing +\n+.
416 * Returns pointer to the terminating 0 or +NULL+ on EOF.
417 * Dies if the line is longer than @l.
419 char *bgets(struct fastbuf *f, char *b, uns l);
420 char *bgets0(struct fastbuf *f, char *b, uns l); /** The same as +bgets+, but for 0-terminated strings. **/
422 * Returns either length of read string (excluding the terminator) or -1 if it is too long.
423 * In such cases exactly @l bytes are read.
425 int bgets_nodie(struct fastbuf *f, char *b, uns l);
430 * Read a string, strip the trailing +\n+ and store it into growing buffer @b.
431 * Dies if the line is longer than @limit.
433 uns bgets_bb(struct fastbuf *f, struct bb_t *b, uns limit);
435 * Read a string, strip the trailing +\n+ and store it into buffer allocated from a memory pool.
437 char *bgets_mp(struct fastbuf *f, struct mempool *mp);
439 struct bgets_stk_struct {
441 byte *old_buf, *cur_buf, *src;
442 uns old_len, cur_len, src_len;
444 void bgets_stk_init(struct bgets_stk_struct *s);
445 void bgets_stk_step(struct bgets_stk_struct *s);
448 * Read a string, strip the trailing +\n+ and store it on the stack (allocated using +alloca+).
450 #define bgets_stk(fb) \
451 ({ struct bgets_stk_struct _s; _s.f = (fb); for (bgets_stk_init(&_s); _s.cur_len; _s.cur_buf = alloca(_s.cur_len), bgets_stk_step(&_s)); _s.cur_buf; })
454 * Write a string, without 0 or +\n+ at the end.
456 static inline void bputs(struct fastbuf *f, const char *b)
458 bwrite(f, b, strlen(b));
462 * Write string, including terminating 0.
464 static inline void bputs0(struct fastbuf *f, const char *b)
466 bwrite(f, b, strlen(b)+1);
470 * Write string and append a newline to the end.
472 static inline void bputsn(struct fastbuf *f, const char *b)
478 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l);
480 * Copy @l bytes of data from fastbuf @f to fastbuf @t.
482 static inline void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
484 if (bavailr(f) >= l && bavailw(t) >= l)
486 memcpy(t->bptr, f->bptr, l);
491 bbcopy_slow(f, t, l);
494 int bskip_slow(struct fastbuf *f, uns len);
495 static inline int bskip(struct fastbuf *f, uns len) /** Skip @len bytes without reading them. **/
497 if (bavailr(f) >= len)
503 return bskip_slow(f, len);
506 /*** === Direct I/O on buffers ***/
507 // TODO Documentation -- what do they do?
510 bdirect_read_prepare(struct fastbuf *f, byte **buf)
512 if (f->bptr == f->bstop && !f->refill(f))
514 *buf = NULL; // This is not needed, but it helps to get rid of spurious warnings
522 bdirect_read_commit(struct fastbuf *f, byte *pos)
528 bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
531 f->buffer = pos; /* Avoid seeking backwards in the buffer */
535 bdirect_write_prepare(struct fastbuf *f, byte **buf)
537 if (f->bptr == f->bufend)
544 bdirect_write_commit(struct fastbuf *f, byte *pos)
549 /*** === Formatted output ***/
552 * printf into a fastbuf.
554 int bprintf(struct fastbuf *b, const char *msg, ...) FORMAT_CHECK(printf,2,3);
555 int vbprintf(struct fastbuf *b, const char *msg, va_list args); /** vprintf into a fastbuf. **/