From b2221b10f80dfbe6c42d9c02aff925841fdbd7b7 Mon Sep 17 00:00:00 2001 From: Amaury Denoyelle Date: Tue, 14 Oct 2025 16:17:14 +0200 Subject: [PATCH] MINOR: ncbuf2: implement add --- include/haproxy/ncbuf2-t.h | 1 + include/haproxy/ncbuf2.h | 4 ++++ src/ncbuf2.c | 36 ++++++++++++++++++++++++++++++++---- 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/include/haproxy/ncbuf2-t.h b/include/haproxy/ncbuf2-t.h index 31411dd9b..7e1aedc3f 100644 --- a/include/haproxy/ncbuf2-t.h +++ b/include/haproxy/ncbuf2-t.h @@ -11,6 +11,7 @@ struct ncbuf2 { char *area; char *bitmap; ncb2_sz_t size; + ncb2_sz_t bitmap_sz; ncb2_sz_t head; }; diff --git a/include/haproxy/ncbuf2.h b/include/haproxy/ncbuf2.h index e837187e8..f7ead782f 100644 --- a/include/haproxy/ncbuf2.h +++ b/include/haproxy/ncbuf2.h @@ -6,4 +6,8 @@ struct ncbuf2 ncb2_make(char *area, ncb2_sz_t size, ncb2_sz_t head); + +enum ncb_ret ncb2_add(struct ncbuf2 *buf, ncb2_sz_t off, + const char *data, ncb2_sz_t len, enum ncb_add_mode mode); + #endif /* _HAPROXY_NCBUF2_H */ diff --git a/src/ncbuf2.c b/src/ncbuf2.c index 0cea43d01..448fbd9a2 100644 --- a/src/ncbuf2.c +++ b/src/ncbuf2.c @@ -2,6 +2,8 @@ #include +#include + /* ******** internal API ******** */ struct itbmap { @@ -89,9 +91,10 @@ struct ncbuf2 ncb2_make(char *area, ncb2_sz_t size, ncb2_sz_t head) ncb2_sz_t bitmap_sz; bitmap_sz = (size + 8) / 9; + buf.bitmap_sz = bitmap_sz; buf.area = area; - buf.bitmap = area + size - bitmap_sz; + buf.bitmap = area + (size - bitmap_sz); buf.size = size - bitmap_sz; buf.head = head; @@ -131,10 +134,35 @@ ncb2_sz_t ncb2_data(const struct ncbuf2 *buf, ncb2_sz_t off) } enum ncb_ret ncb2_add(struct ncbuf2 *buf, ncb2_sz_t off, - const char *data, ncb2_sz_t len, enum ncb_add_mode mode) + const char *data, ncb2_sz_t len, enum ncb_add_mode mode) { - /* TODO */ - return NCB_RET_OK; + char *b; + + BUG_ON_HOT(off + len > buf->size); + /* first copy data into buffer */ + memcpy(&buf->area[off], data, len); + + /* adjust bitmap to reflect newly filled content */ + b = buf->bitmap + (off / 8); + if (off % 8) { + size_t to_copy = len < 8 - (off % 8) ? len : 8 - (off % 8); + /* adjust first bitmap byte relative shifted by offset */ + *b++ |= ((unsigned char)(0xff << (8 - to_copy))) >> (off % 8); + len -= to_copy; + } + + if (len) { + size_t to_copy = len / 8; + /* bulk set bitmap as many as possible */ + memset(b, 0xff, to_copy); + len -= 8 * to_copy; + b += to_copy; + + if (len) { + /* adjust last bitmap byte shifted by remaining len */ + *b |= 0xff << (8 - len); + } + } } enum ncb_ret ncb2_advance(struct ncbuf2 *buf, ncb2_sz_t adv) -- 2.47.3