From b3cc8ae7c2fe35cf20bd0bac211658c0ecbdbdae Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Fri, 12 Oct 2018 10:53:35 +1030 Subject: [PATCH 1/1] membuf: add membuf_added and membuf_unadd APIs. Clean up some whitespace while we're there too. Signed-off-by: Rusty Russell --- ccan/membuf/membuf.c | 2 +- ccan/membuf/membuf.h | 31 +++++++++++++++++++++++++++++-- ccan/membuf/test/run.c | 2 +- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/ccan/membuf/membuf.c b/ccan/membuf/membuf.c index b3b2f08d..39841d97 100644 --- a/ccan/membuf/membuf.c +++ b/ccan/membuf/membuf.c @@ -23,7 +23,7 @@ size_t membuf_prepare_space_(struct membuf *mb, /* Always reset in the trivial empty case. */ if (mb->start == mb->end) mb->start = mb->end = 0; - + if (membuf_num_space_(mb) >= num_extra) return 0; diff --git a/ccan/membuf/membuf.h b/ccan/membuf/membuf.h index dcb48752..aebfca27 100644 --- a/ccan/membuf/membuf.h +++ b/ccan/membuf/membuf.h @@ -133,6 +133,20 @@ static inline void *membuf_space_(struct membuf *mb, size_t elemsize) return mb->elems + mb->end * elemsize; } +/** + * membuf_added - declare that we've added this many elements. + * @mb: the MEMBUF() declared membuf. + * @n: the number of elements we added (must be < membuf_num_space()). + */ +#define membuf_added(mb, num) \ + membuf_added_(tcon_unwrap(mb), (num)) + +static inline void membuf_added_(struct membuf *mb, size_t num) +{ + assert(num <= membuf_num_space_(mb)); + mb->end += num; +} + /** * membuf_prepare_space - internal routine to make sure we've got space. * @mb: the MEMBUF() declared membuf. @@ -181,12 +195,25 @@ static inline void *membuf_add_(struct membuf *mb, size_t num, size_t elemsize) oldend = membuf_space_(mb, elemsize); /* We assume expandfn succeeded. */ - assert(num <= membuf_num_space_(mb)); - mb->end += num; + membuf_added_(mb, num); return oldend; } +/** + * membuf_unadd - remove this many added elements. + * @mb: the MEMBUF() declared membuf. + * @n: the number of elements we want to "unadd" (must be < membuf_num_elems()). + */ +#define membuf_unadd(mb, num) \ + membuf_unadd_(tcon_unwrap(mb), (num)) + +static inline void membuf_unadd_(struct membuf *mb, size_t num) +{ + assert(num <= membuf_num_elems_(mb)); + mb->end -= num; +} + /** * membuf_cleanup - reset membuf, return elems array for freeing. * @mb: the MEMBUF() declared membuf. diff --git a/ccan/membuf/test/run.c b/ccan/membuf/test/run.c index 08836e2a..4ecc24af 100644 --- a/ccan/membuf/test/run.c +++ b/ccan/membuf/test/run.c @@ -90,7 +90,7 @@ int main(void) ok1(membuf_consume(&intbuf, 1)); ok1(membuf_num_elems(&intbuf) == 0); - + /* Force it to more-than-double; make sure that works! */ memset(membuf_add(&intbuf, 300), 0, 300*sizeof(int)); ok1(membuf_num_elems(&intbuf) == 300); -- 2.39.2