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