Skip to content

Commit a5b868d

Browse files
kderdaMaureenHelm
authored andcommitted
net: buf: add function to match buffer's content with a given data
This commit adds a new function the net_buf's API that allow an user to match the net_buf's content with a data without copying it to a temporary buffer. Signed-off-by: Konrad Derda <[email protected]>
1 parent f4cbf40 commit a5b868d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

include/zephyr/net/buf.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2414,6 +2414,22 @@ size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
24142414
const void *value, k_timeout_t timeout,
24152415
net_buf_allocator_cb allocate_cb, void *user_data);
24162416

2417+
/**
2418+
* @brief Match data with a net_buf's content
2419+
*
2420+
* @details Compare data with a content of a net_buf. Provide information about
2421+
* the number of bytes matching between both. If needed, traverse
2422+
* through multiple buffer fragments.
2423+
*
2424+
* @param buf Network buffer
2425+
* @param offset Starting offset to compare from
2426+
* @param data Data buffer for comparison
2427+
* @param len Number of bytes to compare
2428+
*
2429+
* @return The number of bytes compared before the first difference.
2430+
*/
2431+
size_t net_buf_data_match(const struct net_buf *buf, size_t offset, const void *data, size_t len);
2432+
24172433
/**
24182434
* @brief Skip N number of bytes in a net_buf
24192435
*

subsys/net/buf.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,3 +694,39 @@ size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
694694
/* Unreachable */
695695
return 0;
696696
}
697+
698+
size_t net_buf_data_match(const struct net_buf *buf, size_t offset, const void *data, size_t len)
699+
{
700+
const uint8_t *dptr = data;
701+
const uint8_t *bptr;
702+
size_t compared = 0;
703+
size_t to_compare;
704+
705+
if (!buf || !data) {
706+
return compared;
707+
}
708+
709+
/* find the right fragment to start comparison */
710+
while (buf && offset >= buf->len) {
711+
offset -= buf->len;
712+
buf = buf->frags;
713+
}
714+
715+
while (buf && len > 0) {
716+
bptr = buf->data + offset;
717+
to_compare = MIN(len, buf->len - offset);
718+
719+
for (size_t i = 0; i < to_compare; ++i) {
720+
if (dptr[compared] != bptr[i]) {
721+
return compared;
722+
}
723+
compared++;
724+
}
725+
726+
len -= to_compare;
727+
buf = buf->frags;
728+
offset = 0;
729+
}
730+
731+
return compared;
732+
}

0 commit comments

Comments
 (0)