[message] update SetOffset() and MoveOffset() to clamp offset (#12522)

Updates `SetOffset()` to ensure the offset is always clamped to the
current message length. This guarantees that the offset remains valid
and does not exceed the message size.

Updates `MoveOffset()` to accept `int16_t` as the delta and ensures
the calculated new offset is clamped within `0` and
`NumericLimits<uint16_t>::kMax` before setting it.

Updates `SetLength()` to rely on the new `SetOffset()` behavior to
automatically adjust the offset when the message length is reduced.
This commit is contained in:
Abtin Keshavarzian
2026-02-23 10:26:30 -06:00
committed by GitHub
parent 404c80455a
commit d7000862e8
3 changed files with 11 additions and 14 deletions
+8 -13
View File
@@ -281,10 +281,7 @@ Error Message::SetLength(uint16_t aLength)
GetMetadata().mLength = aLength;
// Correct the offset in case shorter length is set.
if (GetOffset() > aLength)
{
SetOffset(aLength);
}
SetOffset(GetOffset());
exit:
return error;
@@ -314,18 +311,16 @@ uint8_t Message::GetBufferCount(void) const
return rval;
}
void Message::MoveOffset(int aDelta)
void Message::MoveOffset(int16_t aDelta)
{
OT_ASSERT(GetOffset() + aDelta <= GetLength());
GetMetadata().mOffset += static_cast<int16_t>(aDelta);
OT_ASSERT(GetMetadata().mOffset <= GetLength());
int32_t newOffset = static_cast<int32_t>(GetOffset()) + aDelta;
newOffset = Clamp<int32_t>(newOffset, 0, NumericLimits<uint16_t>::kMax);
SetOffset(static_cast<uint16_t>(newOffset));
}
void Message::SetOffset(uint16_t aOffset)
{
OT_ASSERT(aOffset <= GetLength());
GetMetadata().mOffset = aOffset;
}
void Message::SetOffset(uint16_t aOffset) { GetMetadata().mOffset = Min(aOffset, GetLength()); }
uint16_t Message::DetermineLengthAfterOffset(void) const
{
+1 -1
View File
@@ -528,7 +528,7 @@ public:
*
* @param[in] aDelta The number of bytes to move the current offset, which may be positive or negative.
*/
void MoveOffset(int aDelta);
void MoveOffset(int16_t aDelta);
/**
* Sets the byte offset within the message.
+2
View File
@@ -54,6 +54,8 @@
#include "common/log.hpp"
#include "common/message.hpp"
#include "common/non_copyable.hpp"
#include "common/num_utils.hpp"
#include "common/numeric_limits.hpp"
#include "common/random.hpp"
#include "common/serial_number.hpp"
#include "common/string.hpp"