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