From 45282a41c17b04f7d376fa75d411961b1252d13e Mon Sep 17 00:00:00 2001 From: Pisit Sawangvonganan Date: Thu, 18 Jul 2024 18:42:22 +0700 Subject: [PATCH] net: mqtt: improve encoder buffer handling Improve buffer handling logic to use local variables extensively. This change reduces the number of pointer dereferences, which leads to more efficient runtime and helps reduce the code size. Signed-off-by: Pisit Sawangvonganan --- subsys/net/lib/mqtt/mqtt_encoder.c | 39 ++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/subsys/net/lib/mqtt/mqtt_encoder.c b/subsys/net/lib/mqtt/mqtt_encoder.c index e2abc0ab9e5f5b..7297e8226ff5ac 100644 --- a/subsys/net/lib/mqtt/mqtt_encoder.c +++ b/subsys/net/lib/mqtt/mqtt_encoder.c @@ -45,14 +45,18 @@ static const uint8_t disc_packet[MQTT_FIXED_HEADER_MIN_SIZE] = { */ static int pack_uint8(uint8_t val, struct buf_ctx *buf) { - if ((buf->end - buf->cur) < sizeof(uint8_t)) { + uint8_t *cur = buf->cur; + uint8_t *end = buf->end; + + if ((end - cur) < sizeof(uint8_t)) { return -ENOMEM; } - NET_DBG(">> val:%02x cur:%p, end:%p", val, (void *)buf->cur, (void *)buf->end); + NET_DBG(">> val:%02x cur:%p, end:%p", val, (void *)cur, (void *)end); /* Pack value. */ - *(buf->cur++) = val; + cur[0] = val; + buf->cur = (cur + sizeof(uint8_t)); return 0; } @@ -69,15 +73,18 @@ static int pack_uint8(uint8_t val, struct buf_ctx *buf) */ static int pack_uint16(uint16_t val, struct buf_ctx *buf) { - if ((buf->end - buf->cur) < sizeof(uint16_t)) { + uint8_t *cur = buf->cur; + uint8_t *end = buf->end; + + if ((end - cur) < sizeof(uint16_t)) { return -ENOMEM; } - NET_DBG(">> val:%04x cur:%p, end:%p", val, (void *)buf->cur, (void *)buf->end); + NET_DBG(">> val:%04x cur:%p, end:%p", val, (void *)cur, (void *)end); /* Pack value. */ - *(buf->cur++) = (val >> 8) & 0xFF; - *(buf->cur++) = val & 0xFF; + sys_put_be16(val, cur); + buf->cur = (cur + sizeof(uint16_t)); return 0; } @@ -470,12 +477,15 @@ int publish_complete_encode(const struct mqtt_pubcomp_param *param, int disconnect_encode(struct buf_ctx *buf) { - if (buf->end - buf->cur < sizeof(disc_packet)) { + uint8_t *cur = buf->cur; + uint8_t *end = buf->end; + + if ((end - cur) < sizeof(disc_packet)) { return -ENOMEM; } - memcpy(buf->cur, disc_packet, sizeof(disc_packet)); - buf->end = buf->cur + sizeof(disc_packet); + memcpy(cur, disc_packet, sizeof(disc_packet)); + buf->end = (cur + sizeof(disc_packet)); return 0; } @@ -546,12 +556,15 @@ int unsubscribe_encode(const struct mqtt_subscription_list *param, int ping_request_encode(struct buf_ctx *buf) { - if (buf->end - buf->cur < sizeof(ping_packet)) { + uint8_t *cur = buf->cur; + uint8_t *end = buf->end; + + if ((end - cur) < sizeof(ping_packet)) { return -ENOMEM; } - memcpy(buf->cur, ping_packet, sizeof(ping_packet)); - buf->end = buf->cur + sizeof(ping_packet); + memcpy(cur, ping_packet, sizeof(ping_packet)); + buf->end = (cur + sizeof(ping_packet)); return 0; }