]> mj.ucw.cz Git - libucw.git/blob - ucw/fastbuf.h
4fb02bb6b9ac3b6658992ee42aa2cf6645ab2183
[libucw.git] / ucw / fastbuf.h
1 /*
2  *      UCW Library -- Fast Buffered I/O
3  *
4  *      (c) 1997--2007 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  *  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.
20  *
21  *  Buffer layout when reading:
22  *
23  *  +----------------+---------------------------+
24  *  | read data      | free space                |
25  *  +----------------+---------------------------+
26  *  ^        ^        ^                           ^
27  *  buffer   bptr     bstop                       bufend
28  *
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().
32  *
33  *  When writing:
34  *
35  *  +--------+--------------+--------------------+
36  *  | unused | written data | free space         |
37  *  +--------+--------------+--------------------+
38  *  ^         ^              ^                    ^
39  *  buffer    bstop          bptr                 bufend
40  *
41  *  Dirty tricks:
42  *
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
55  *                   fastbuf operation
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.
60  */
61
62 struct fastbuf {
63   byte is_fastbuf[0];                   /* Dummy field for checking of type casts */
64   byte *bptr, *bstop;                   /* Access pointers */
65   byte *buffer, *bufend;                /* Start and end of the buffer */
66   char *name;                           /* File name for error messages */
67   ucw_off_t pos;                                /* Position of bstop in the file */
68   int (*refill)(struct fastbuf *);      /* Get a buffer with new data */
69   void (*spout)(struct fastbuf *);      /* Write buffer data to the file */
70   int (*seek)(struct fastbuf *, ucw_off_t, int);  /* Slow path for bseek(), buffer already flushed; returns success */
71   void (*close)(struct fastbuf *);      /* Close the stream */
72   int (*config)(struct fastbuf *, uns, int);    /* Configure the stream */
73   int can_overwrite_buffer;             /* Can the buffer be altered? (see discussion above) 0=never, 1=temporarily, 2=permanently */
74 };
75
76 /* FastIO on files with several configurable back-ends */
77
78 enum fb_type {                          /* Which back-end you want to use */
79   FB_STD,                               /* Standard buffered I/O */
80   FB_DIRECT,                            /* Direct I/O bypassing system caches (see fb-direct.c for a description) */
81   FB_MMAP                               /* Memory mapped files */
82 };
83
84 struct fb_params {
85   enum fb_type type;
86   uns buffer_size;                      /* 0 for default size */
87   uns keep_back_buf;                    /* FB_STD: optimize for bi-directional access */
88   uns read_ahead;                       /* FB_DIRECT options */
89   uns write_back;
90   struct asio_queue *asio;
91 };
92
93 struct cf_section;
94 extern struct cf_section fbpar_cf;
95 extern struct fb_params fbpar_def;
96
97 /*DOC
98  * Opens a file.
99  */
100 struct fastbuf *bopen_file(const char *name, int mode, struct fb_params *params);       /* Use params==NULL for defaults */
101 /*DOC
102  * Tries to open a file (does not die, if it isn't sucessful).
103  */
104 struct fastbuf /*BLAXLA*/ *bopen_file_try(const /*BAX*/ char *name, int mode, struct fb_params *params);
105 /*DOC
106  * Opens a temporary file.
107  * It is placed with other temp filenames and deleted when closed.
108  */
109 struct fastbuf *bopen_tmp_file(struct fb_params *params);
110 struct fastbuf *bopen_fd_name(int fd, struct fb_params *params, const char *name);
111 static inline struct fastbuf *bopen_fd(int fd, struct fb_params *params)
112 {
113   return bopen_fd_name(fd, params, NULL);
114 }
115
116 /* FastIO on standard files (shortcuts for FB_STD) */
117
118 struct fastbuf *bopen(const char *name, uns mode, uns buflen);
119 struct fastbuf *bopen_try(const char *name, uns mode, uns buflen);
120 struct fastbuf *bopen_tmp(uns buflen);
121 struct fastbuf *bfdopen(int fd, uns buflen);
122 struct fastbuf *bfdopen_shared(int fd, uns buflen);
123 void bfilesync(struct fastbuf *b);
124
125 /* Temporary files */
126
127 #define TEMP_FILE_NAME_LEN 256
128 void temp_file_name(char *name_buf, int *open_flags);
129 void bfix_tmp_file(struct fastbuf *fb, const char *name);
130 int open_tmp(char *name_buf, int open_flags, int mode);
131
132 /* Internal functions of some file back-ends */
133
134 struct fastbuf *bfdopen_internal(int fd, const char *name, uns buflen);
135 struct fastbuf *bfmmopen_internal(int fd, const char *name, uns mode);
136
137 extern uns fbdir_cheat;
138 struct asio_queue;
139 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);
140
141 void bclose_file_helper(struct fastbuf *f, int fd, int is_temp_file);
142
143 /* FastIO on in-memory streams */
144
145 struct fastbuf *fbmem_create(uns blocksize);            /* Create stream and return its writing fastbuf */
146 struct fastbuf *fbmem_clone_read(struct fastbuf *);     /* Create reading fastbuf */
147
148 /* FastI on file descriptors with limit */
149
150 struct fastbuf *bopen_limited_fd(int fd, uns bufsize, uns limit);
151
152 /* FastIO on static buffers */
153
154 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uns size, uns can_overwrite);
155 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uns size);
156 static inline uns
157 fbbuf_count_written(struct fastbuf *f)
158 {
159   return f->bptr - f->bstop;
160 }
161
162 /* FastIO on recyclable growing buffers */
163
164 struct fastbuf *fbgrow_create(unsigned basic_size);
165 void fbgrow_reset(struct fastbuf *b);                   /* Reset stream and prepare for writing */
166 void fbgrow_rewind(struct fastbuf *b);                  /* Prepare for reading */
167
168 /* FastO on memory pools */
169
170 struct mempool;
171 struct fbpool {
172   struct fastbuf fb;
173   struct mempool *mp;
174 };
175
176 void fbpool_init(struct fbpool *fb);    /* Initialize a new fastbuf */
177 void fbpool_start(struct fbpool *fb, struct mempool *mp, uns init_size);
178                                         /* Start a new continuous block and prepare for writing (see mp_start()) */
179 void *fbpool_end(struct fbpool *fb);    /* Close the block and return its address (see mp_end()).
180                                            The length can be determined with mp_size(mp, ptr). */
181
182 /* FastO with atomic writes for multi-threaded programs */
183
184 struct fb_atomic {
185   struct fastbuf fb;
186   struct fb_atomic_file *af;
187   byte *expected_max_bptr;
188   uns slack_size;
189 };
190 #define FB_ATOMIC(f) ((struct fb_atomic *)(f)->is_fastbuf)
191
192 struct fastbuf *fbatomic_open(const char *name, struct fastbuf *master, uns bufsize, int record_len);
193 void fbatomic_internal_write(struct fastbuf *b);
194
195 static inline void
196 fbatomic_commit(struct fastbuf *b)
197 {
198   if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
199     fbatomic_internal_write(b);
200 }
201
202 /* Configuring stream parameters */
203
204 enum bconfig_type {
205   BCONFIG_IS_TEMP_FILE,                 /* 0=normal file, 1=temporary file, 2=shared fd */
206   BCONFIG_KEEP_BACK_BUF,                /* Optimize for bi-directional access */
207 };
208
209 int bconfig(struct fastbuf *f, uns type, int data);
210
211 /* Universal functions working on all fastbuf's */
212
213 void bclose(struct fastbuf *f);
214 void bflush(struct fastbuf *f);
215 void bseek(struct fastbuf *f, ucw_off_t pos, int whence);
216 void bsetpos(struct fastbuf *f, ucw_off_t pos);
217 void brewind(struct fastbuf *f);
218 ucw_off_t bfilesize(struct fastbuf *f);         /* -1 if not seekable */
219
220 static inline ucw_off_t btell(struct fastbuf *f)
221 {
222   return f->pos + (f->bptr - f->bstop);
223 }
224
225 int bgetc_slow(struct fastbuf *f);
226 static inline int bgetc(struct fastbuf *f)
227 {
228   return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
229 }
230
231 int bpeekc_slow(struct fastbuf *f);
232 static inline int bpeekc(struct fastbuf *f)
233 {
234   return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
235 }
236
237 static inline void bungetc(struct fastbuf *f)
238 {
239   f->bptr--;
240 }
241
242 void bputc_slow(struct fastbuf *f, uns c);
243 static inline void bputc(struct fastbuf *f, uns c)
244 {
245   if (f->bptr < f->bufend)
246     *f->bptr++ = c;
247   else
248     bputc_slow(f, c);
249 }
250
251 static inline uns
252 bavailr(struct fastbuf *f)
253 {
254   return f->bstop - f->bptr;
255 }
256
257 static inline uns
258 bavailw(struct fastbuf *f)
259 {
260   return f->bufend - f->bptr;
261 }
262
263 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check);
264 static inline uns bread(struct fastbuf *f, void *b, uns l)
265 {
266   if (bavailr(f) >= l)
267     {
268       memcpy(b, f->bptr, l);
269       f->bptr += l;
270       return l;
271     }
272   else
273     return bread_slow(f, b, l, 0);
274 }
275
276 static inline uns breadb(struct fastbuf *f, void *b, uns l)
277 {
278   if (bavailr(f) >= l)
279     {
280       memcpy(b, f->bptr, l);
281       f->bptr += l;
282       return l;
283     }
284   else
285     return bread_slow(f, b, l, 1);
286 }
287
288 void bwrite_slow(struct fastbuf *f, const void *b, uns l);
289 static inline void bwrite(struct fastbuf *f, const void *b, uns l)
290 {
291   if (bavailw(f) >= l)
292     {
293       memcpy(f->bptr, b, l);
294       f->bptr += l;
295     }
296   else
297     bwrite_slow(f, b, l);
298 }
299
300 /*
301  *  Functions for reading of strings:
302  *
303  *     bgets()          reads a line, strip the trailing '\n' and return a pointer
304  *                      to the terminating 0 or NULL on EOF. Dies if the line is too long.
305  *     bgets0()         does the same for 0-terminated strings.
306  *     bgets_nodie()    a variant of bgets() which returns either the length of the
307  *                      string (excluding the terminator) or -1 if the line does not fit
308  *                      in the buffer. In such cases, it returns after reading exactly `l'
309  *                      bytes of input.
310  *     bgets_bb()       a variant of bgets() which allocates the string in a growing buffer
311  *     bgets_mp()       the same, but in a mempool
312  *     bgets_stk()      the same, but on the stack by alloca()
313  */
314
315 char *bgets(struct fastbuf *f, char *b, uns l);
316 char *bgets0(struct fastbuf *f, char *b, uns l);
317 int bgets_nodie(struct fastbuf *f, char *b, uns l);
318
319 struct mempool;
320 struct bb_t;
321 uns bgets_bb(struct fastbuf *f, struct bb_t *b, uns limit);
322 char *bgets_mp(struct fastbuf *f, struct mempool *mp);
323
324 struct bgets_stk_struct {
325   struct fastbuf *f;
326   byte *old_buf, *cur_buf, *src;
327   uns old_len, cur_len, src_len;
328 };
329 void bgets_stk_init(struct bgets_stk_struct *s);
330 void bgets_stk_step(struct bgets_stk_struct *s);
331 #define bgets_stk(fb) ({ 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; })
332
333 static inline void
334 bputs(struct fastbuf *f, const char *b)
335 {
336   bwrite(f, b, strlen(b));
337 }
338
339 static inline void
340 bputs0(struct fastbuf *f, const char *b)
341 {
342   bwrite(f, b, strlen(b)+1);
343 }
344
345 static inline void
346 bputsn(struct fastbuf *f, const char *b)
347 {
348   bputs(f, b);
349   bputc(f, '\n');
350 }
351
352 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l);
353 static inline void
354 bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
355 {
356   if (bavailr(f) >= l && bavailw(t) >= l)
357     {
358       memcpy(t->bptr, f->bptr, l);
359       t->bptr += l;
360       f->bptr += l;
361     }
362   else
363     bbcopy_slow(f, t, l);
364 }
365
366 int bskip_slow(struct fastbuf *f, uns len);
367 static inline int bskip(struct fastbuf *f, uns len)
368 {
369   if (bavailr(f) >= len)
370     {
371       f->bptr += len;
372       return 1;
373     }
374   else
375     return bskip_slow(f, len);
376 }
377
378 /* Direct I/O on buffers */
379
380 static inline uns
381 bdirect_read_prepare(struct fastbuf *f, byte **buf)
382 {
383   if (f->bptr == f->bstop && !f->refill(f))
384     {
385       *buf = NULL;  // This is not needed, but it helps to get rid of spurious warnings
386       return 0;
387     }
388   *buf = f->bptr;
389   return bavailr(f);
390 }
391
392 static inline void
393 bdirect_read_commit(struct fastbuf *f, byte *pos)
394 {
395   f->bptr = pos;
396 }
397
398 static inline void
399 bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
400 {
401   f->bptr = pos;
402   f->buffer = pos;      /* Avoid seeking backwards in the buffer */
403 }
404
405 static inline uns
406 bdirect_write_prepare(struct fastbuf *f, byte **buf)
407 {
408   if (f->bptr == f->bufend)
409     f->spout(f);
410   *buf = f->bptr;
411   return bavailw(f);
412 }
413
414 static inline void
415 bdirect_write_commit(struct fastbuf *f, byte *pos)
416 {
417   f->bptr = pos;
418 }
419
420 /* Formatted output */
421
422 int bprintf(struct fastbuf *b, const char *msg, ...) FORMAT_CHECK(printf,2,3);
423 int vbprintf(struct fastbuf *b, const char *msg, va_list args);
424
425 #endif