Add helper to truncate the buffer to certain size which might be
useful if some earlier part of the buffer can be reused multiple
times without copying the whole buffer.

Signed-off-by: Ales Musil <[email protected]>
---
v2: Rebase on top of current main.
    Add comment what the function does and test case.
    Fix the wrong move of data pointer.
---
 include/openvswitch/ofpbuf.h | 7 +++++++
 tests/test-ofpbuf.c          | 9 +++++++++
 2 files changed, 16 insertions(+)

diff --git a/include/openvswitch/ofpbuf.h b/include/openvswitch/ofpbuf.h
index 1fc4a3a7f..f16e3d697 100644
--- a/include/openvswitch/ofpbuf.h
+++ b/include/openvswitch/ofpbuf.h
@@ -292,6 +292,13 @@ static inline bool ofpbuf_oversized(const struct ofpbuf 
*ofpacts)
     return (char *)ofpbuf_tail(ofpacts) - (char *)ofpacts->header > UINT16_MAX;
 }
 
+/* Removes 'size' bytes from the tail end of 'b'. */
+static inline void ofpbuf_truncate(struct ofpbuf *b, size_t size)
+{
+    ovs_assert(b->size >= size);
+    b->size = b->size - size;
+}
+
 #ifdef  __cplusplus
 }
 #endif
diff --git a/tests/test-ofpbuf.c b/tests/test-ofpbuf.c
index 3d7fab90f..47b905f6f 100644
--- a/tests/test-ofpbuf.c
+++ b/tests/test-ofpbuf.c
@@ -24,6 +24,7 @@
 #define BUF_SIZE 100
 #define HDR_OFS 10
 #define MSG_OFS 50
+#define DATA_SIZE 16
 
 static void
 test_ofpbuf_main(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
@@ -59,6 +60,14 @@ test_ofpbuf_main(int argc OVS_UNUSED, char *argv[] 
OVS_UNUSED)
     ovs_assert(buf->header == (char *) buf->base + BUF_SIZE + HDR_OFS);
     ovs_assert(buf->msg == (char *) buf->base + BUF_SIZE + MSG_OFS);
 
+    ofpbuf_put_uninit(buf, DATA_SIZE);
+    ofpbuf_truncate(buf, DATA_SIZE);
+    /* Check that everything else is unchanged after truncate. */
+    ovs_assert(!buf->size);
+    ovs_assert((char *) buf->base + BUF_SIZE == buf->data);
+    ovs_assert(buf->header == (char *) buf->base + BUF_SIZE + HDR_OFS);
+    ovs_assert(buf->msg == (char *) buf->base + BUF_SIZE + MSG_OFS);
+
     ofpbuf_delete(buf);
     exit(exit_code);
 }
-- 
2.47.0

_______________________________________________
dev mailing list
[email protected]
https://mail.openvswitch.org/mailman/listinfo/ovs-dev

Reply via email to