From e3f62ad82e2b88c52c34dcf6b769ba517e7e57f9 Mon Sep 17 00:00:00 2001 From: Pavel Charvat Date: Wed, 17 May 2006 10:01:20 +0200 Subject: [PATCH] simple bgets with allocation on the stack/mempool/bbuf --- lib/fastbuf.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++ lib/fastbuf.h | 9 ++++++++ 2 files changed, 72 insertions(+) diff --git a/lib/fastbuf.c b/lib/fastbuf.c index f83b4021..9a1cd4a5 100644 --- a/lib/fastbuf.c +++ b/lib/fastbuf.c @@ -9,6 +9,7 @@ #include "lib/lib.h" #include "lib/fastbuf.h" +#include "lib/mempool.h" #include @@ -282,6 +283,68 @@ bgets_nodie(struct fastbuf *f, byte *b, uns l) return -1; } +uns +bgets_bb(struct fastbuf *f, bb_t *b) +{ + for (uns l = 0;; l++) + { + int k = bgetc(f); + byte *p = bb_grow(b, l + 1) + l; + if (k == '\n' || k < 0) + { + *p = 0; + return l; + } + *p = k; + } +} + +byte * +bgets_mp(struct mempool *mp, struct fastbuf *f) +{ + uns len = 256, l = 0; + byte *buf = alloca(len); + for (;;) + { + while (l < len) + { + int k = bgetc(f); + if (k == '\n' || k < 0) + { + byte *result = mp_alloc(mp, l + 1); + memcpy(result, buf, l); + result[l] = 0; + return result; + } + buf[l++] = k; + } + byte *old_buf = buf; + uns old_len = len; + len *= 2; + buf = alloca(len); + memcpy(buf, old_buf, old_len); + } +} + +int +bgets_stk_step(struct fastbuf *f, byte *old_buf, byte *buf, uns len) +{ + if (old_buf) + { + len = len >> 1; + memcpy(buf, old_buf, len); + buf += len; + } + while (len--) + { + int k = bgetc(f); + if (k == '\n' || k < 0) + return *buf = 0; + *buf++ = k; + } + return 1; +} + byte * bgets0(struct fastbuf *f, byte *b, uns l) { diff --git a/lib/fastbuf.h b/lib/fastbuf.h index af6787ae..bc7ef7eb 100644 --- a/lib/fastbuf.h +++ b/lib/fastbuf.h @@ -16,8 +16,10 @@ #endif #include +#include #include "lib/unaligned.h" +#include "lib/bbuf.h" /* * Generic buffered I/O. You supply hooks to be called for low-level operations @@ -319,6 +321,13 @@ byte *bgets(struct fastbuf *f, byte *b, uns l); /* Non-std */ int bgets_nodie(struct fastbuf *f, byte *b, uns l); byte *bgets0(struct fastbuf *f, byte *b, uns l); +struct mempool; +uns bgets_bb(struct fastbuf *f, bb_t *b); +byte *bgets_mp(struct mempool *mp, struct fastbuf *f); +int bgets_stk_step(struct fastbuf *f, byte *old_buf, byte *buf, uns len); +#define bgets_stk(f) ({ struct fastbuf *_fb = (f); uns _l = 256; byte *_b, *_p = NULL; \ + while (bgets_stk_step(_fb, _p, _b = alloca(_l), _l)) _p = _b, _l *= 2; _b; }) + static inline void bputs(struct fastbuf *f, byte *b) { -- 2.39.2