Skip to content

Commit

Permalink
ofpbuf: Add helper method to truncate the buffer.
Browse files Browse the repository at this point in the history
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]>
Signed-off-by: Ilya Maximets <[email protected]>
  • Loading branch information
almusil authored and igsilya committed Dec 13, 2024
1 parent 4d09d6b commit 7b1ce8e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
7 changes: 7 additions & 0 deletions include/openvswitch/ofpbuf.h
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,13 @@ static inline bool ofpbuf_oversized(const struct ofpbuf *ofpacts)
return (char *)ofpbuf_tail(ofpacts) - (char *)ofpacts->header > UINT16_MAX;
}

/* Truncates the buffer to 'new_size' bytes from the tail end of 'b'. */
static inline void ofpbuf_truncate(struct ofpbuf *b, size_t new_size)
{
ovs_assert(b->size >= new_size);
b->size = new_size;
}

#ifdef __cplusplus
}
#endif
Expand Down
2 changes: 1 addition & 1 deletion lib/ofp-actions.c
Original file line number Diff line number Diff line change
Expand Up @@ -9674,7 +9674,7 @@ ofpacts_parse(char *str, const struct ofpact_parse_params *pp,
uint32_t orig_size = pp->ofpacts->size;
char *error = ofpacts_parse__(str, pp, allow_instructions, outer_action);
if (error) {
pp->ofpacts->size = orig_size;
ofpbuf_truncate(pp->ofpacts, orig_size);
}
CONST_CAST(struct ofpact_parse_params *, pp)->depth--;
return error;
Expand Down
10 changes: 10 additions & 0 deletions tests/test-ofpbuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -59,6 +60,15 @@ 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);

size_t prev_size = buf->size;
ofpbuf_put_uninit(buf, DATA_SIZE);
ofpbuf_truncate(buf, prev_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);
}
Expand Down

0 comments on commit 7b1ce8e

Please sign in to comment.