]> mj.ucw.cz Git - libucw.git/blob - lib/fastbuf.h
1020427b5d80f301b4044a6dd2d79d55742f3f37
[libucw.git] / lib / 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   byte *name;                           /* File name for error messages */
67   sh_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 *, sh_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 run-time parametrization */
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 description) */
81   FB_MMAP                               /* Memory mapped files */
82 };
83
84 struct fb_params {
85   enum fb_type type;
86   uns buffer_size;
87   uns read_ahead;                       /* The next three fields are used for FB_DIRECT files */
88   uns write_back;
89   struct asio_queue *asio;
90 };
91
92 struct cf_section;
93 extern struct cf_section fbpar_cf;
94 extern struct fb_params fbpar_def;
95
96 struct fastbuf *bopen_file(byte *name, int mode, struct fb_params *params);             /* Use params==NULL for defaults */
97 struct fastbuf *bopen_file_try(byte *name, int mode, struct fb_params *params);
98 struct fastbuf *bopen_tmp_file(struct fb_params *params);
99 struct fastbuf *bopen_fd(int fd, struct fb_params *params);
100
101 /* FastIO on standard files (specify buffer size 0 to enable mmaping) */
102
103 struct fastbuf *bfdopen_internal(int fd, byte *name, uns buflen);
104 struct fastbuf *bopen(byte *name, uns mode, uns buflen);
105 struct fastbuf *bopen_try(byte *name, uns mode, uns buflen);
106 struct fastbuf *bopen_tmp(uns buflen);
107 struct fastbuf *bfdopen(int fd, uns buflen);
108 struct fastbuf *bfdopen_shared(int fd, uns buflen);
109 void bfilesync(struct fastbuf *b);
110
111 #define TEMP_FILE_NAME_LEN 256
112 void temp_file_name(byte *name);
113
114 /* Internal functions of some file back-ends */
115
116 struct fastbuf *bfmmopen_internal(int fd, byte *name, uns mode);
117
118 extern uns fbdir_cheat;
119 struct asio_queue;
120 struct fastbuf *fbdir_open_fd_internal(int fd, byte *name, struct asio_queue *io_queue, uns buffer_size, uns read_ahead, uns write_back);
121
122 /* FastIO on in-memory streams */
123
124 struct fastbuf *fbmem_create(unsigned blocksize);       /* Create stream and return its writing fastbuf */
125 struct fastbuf *fbmem_clone_read(struct fastbuf *);     /* Create reading fastbuf */
126
127 /* FastI on file descriptors with limit */
128
129 struct fastbuf *bopen_limited_fd(int fd, uns bufsize, uns limit);
130
131 /* FastIO on static buffers */
132
133 void fbbuf_init_read(struct fastbuf *f, byte *buffer, uns size, uns can_overwrite);
134 void fbbuf_init_write(struct fastbuf *f, byte *buffer, uns size);
135 static inline uns
136 fbbuf_count_written(struct fastbuf *f)
137 {
138   return f->bptr - f->bstop;
139 }
140
141 /* FastIO on recyclable growing buffers */
142
143 struct fastbuf *fbgrow_create(unsigned basic_size);
144 void fbgrow_reset(struct fastbuf *b);                   /* Reset stream and prepare for writing */
145 void fbgrow_rewind(struct fastbuf *b);                  /* Prepare for reading */
146
147 /* FastO on memory pools */
148
149 struct mempool;
150 struct fbpool {
151   struct fastbuf fb;
152   struct mempool *mp;
153 };
154
155 void fbpool_init(struct fbpool *fb);
156 void fbpool_start(struct fbpool *fb, struct mempool *mp, uns init_size);
157 void *fbpool_end(struct fbpool *fb);
158
159 /* FastO with atomic writes for multi-threaded programs */
160
161 struct fb_atomic {
162   struct fastbuf fb;
163   struct fb_atomic_file *af;
164   byte *expected_max_bptr;
165   uns slack_size;
166 };
167 #define FB_ATOMIC(f) ((struct fb_atomic *)(f)->is_fastbuf)
168
169 struct fastbuf *fbatomic_open(byte *name, struct fastbuf *master, uns bufsize, int record_len);
170 void fbatomic_internal_write(struct fastbuf *b);
171
172 static inline void
173 fbatomic_commit(struct fastbuf *b)
174 {
175   if (b->bptr >= ((struct fb_atomic *)b)->expected_max_bptr)
176     fbatomic_internal_write(b);
177 }
178
179 /* Configuring stream parameters */
180
181 enum bconfig_type {
182   BCONFIG_IS_TEMP_FILE,
183   BCONFIG_KEEP_BACK_BUF,
184 };
185
186 int bconfig(struct fastbuf *f, uns type, int data);
187
188 /* Universal functions working on all fastbuf's */
189
190 void bclose(struct fastbuf *f);
191 void bflush(struct fastbuf *f);
192 void bseek(struct fastbuf *f, sh_off_t pos, int whence);
193 void bsetpos(struct fastbuf *f, sh_off_t pos);
194 void brewind(struct fastbuf *f);
195 sh_off_t bfilesize(struct fastbuf *f);          // -1 if not seekable
196
197 static inline sh_off_t btell(struct fastbuf *f)
198 {
199   return f->pos + (f->bptr - f->bstop);
200 }
201
202 int bgetc_slow(struct fastbuf *f);
203 static inline int bgetc(struct fastbuf *f)
204 {
205   return (f->bptr < f->bstop) ? (int) *f->bptr++ : bgetc_slow(f);
206 }
207
208 int bpeekc_slow(struct fastbuf *f);
209 static inline int bpeekc(struct fastbuf *f)
210 {
211   return (f->bptr < f->bstop) ? (int) *f->bptr : bpeekc_slow(f);
212 }
213
214 static inline void bungetc(struct fastbuf *f)
215 {
216   f->bptr--;
217 }
218
219 void bputc_slow(struct fastbuf *f, uns c);
220 static inline void bputc(struct fastbuf *f, uns c)
221 {
222   if (f->bptr < f->bufend)
223     *f->bptr++ = c;
224   else
225     bputc_slow(f, c);
226 }
227
228 static inline uns
229 bavailr(struct fastbuf *f)
230 {
231   return f->bstop - f->bptr;
232 }
233
234 static inline uns
235 bavailw(struct fastbuf *f)
236 {
237   return f->bufend - f->bptr;
238 }
239
240 uns bread_slow(struct fastbuf *f, void *b, uns l, uns check);
241 static inline uns bread(struct fastbuf *f, void *b, uns l)
242 {
243   if (bavailr(f) >= l)
244     {
245       memcpy(b, f->bptr, l);
246       f->bptr += l;
247       return l;
248     }
249   else
250     return bread_slow(f, b, l, 0);
251 }
252
253 static inline uns breadb(struct fastbuf *f, void *b, uns l)
254 {
255   if (bavailr(f) >= l)
256     {
257       memcpy(b, f->bptr, l);
258       f->bptr += l;
259       return l;
260     }
261   else
262     return bread_slow(f, b, l, 1);
263 }
264
265 void bwrite_slow(struct fastbuf *f, void *b, uns l);
266 static inline void bwrite(struct fastbuf *f, void *b, uns l)
267 {
268   if (bavailw(f) >= l)
269     {
270       memcpy(f->bptr, b, l);
271       f->bptr += l;
272     }
273   else
274     bwrite_slow(f, b, l);
275 }
276
277 byte *bgets(struct fastbuf *f, byte *b, uns l); /* Non-std */
278 int bgets_nodie(struct fastbuf *f, byte *b, uns l);
279 byte *bgets0(struct fastbuf *f, byte *b, uns l);
280
281 struct mempool;
282 struct bb_t;
283 uns bgets_bb(struct fastbuf *f, struct bb_t *b, uns limit);
284 byte *bgets_mp(struct fastbuf *f, struct mempool *mp);
285
286 struct bgets_stk_struct {
287   struct fastbuf *f;
288   byte *old_buf, *cur_buf, *src;
289   uns old_len, cur_len, src_len;
290 };
291 void bgets_stk_init(struct bgets_stk_struct *s);
292 void bgets_stk_step(struct bgets_stk_struct *s);
293 #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; })
294
295 static inline void
296 bputs(struct fastbuf *f, byte *b)
297 {
298   bwrite(f, b, strlen(b));
299 }
300
301 static inline void
302 bputs0(struct fastbuf *f, byte *b)
303 {
304   bwrite(f, b, strlen(b)+1);
305 }
306
307 static inline void
308 bputsn(struct fastbuf *f, byte *b)
309 {
310   bputs(f, b);
311   bputc(f, '\n');
312 }
313
314 void bbcopy_slow(struct fastbuf *f, struct fastbuf *t, uns l);
315 static inline void
316 bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
317 {
318   if (bavailr(f) >= l && bavailw(t) >= l)
319     {
320       memcpy(t->bptr, f->bptr, l);
321       t->bptr += l;
322       f->bptr += l;
323     }
324   else
325     bbcopy_slow(f, t, l);
326 }
327
328 int bskip_slow(struct fastbuf *f, uns len);
329 static inline int bskip(struct fastbuf *f, uns len)
330 {
331   if (bavailr(f) >= len)
332     {
333       f->bptr += len;
334       return 1;
335     }
336   else
337     return bskip_slow(f, len);
338 }
339
340 /* Direct I/O on buffers */
341
342 static inline uns
343 bdirect_read_prepare(struct fastbuf *f, byte **buf)
344 {
345   if (f->bptr == f->bstop && !f->refill(f))
346     {
347       *buf = NULL;  // This is not needed, but it helps to get rid of spurious warnings
348       return 0;
349     }
350   *buf = f->bptr;
351   return bavailr(f);
352 }
353
354 static inline void
355 bdirect_read_commit(struct fastbuf *f, byte *pos)
356 {
357   f->bptr = pos;
358 }
359
360 static inline void
361 bdirect_read_commit_modified(struct fastbuf *f, byte *pos)
362 {
363   f->bptr = pos;
364   f->buffer = pos;      /* Avoid seeking backwards in the buffer */
365 }
366
367 static inline uns
368 bdirect_write_prepare(struct fastbuf *f, byte **buf)
369 {
370   if (f->bptr == f->bufend)
371     f->spout(f);
372   *buf = f->bptr;
373   return bavailw(f);
374 }
375
376 static inline void
377 bdirect_write_commit(struct fastbuf *f, byte *pos)
378 {
379   f->bptr = pos;
380 }
381
382 /* Formatted output */
383
384 int bprintf(struct fastbuf *b, char *msg, ...) FORMAT_CHECK(printf,2,3);
385 int vbprintf(struct fastbuf *b, char *msg, va_list args);
386
387 #endif