Skip to content

Commit

Permalink
Use EnsureReservedSize()
Browse files Browse the repository at this point in the history
  • Loading branch information
kpschoedel committed Jun 6, 2022
1 parent 81c8754 commit d4fa0ab
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
21 changes: 9 additions & 12 deletions src/system/SystemPacketBuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -414,33 +414,30 @@ uint8_t * PacketBuffer::GetReserve(uint16_t aSize, uint16_t aAlignmentMask)
return nullptr;
}

uintptr_t requestStart = (reserveStart + aAlignmentMask) & ~aAlignmentMask;
const uintptr_t requestStart = (reserveStart + aAlignmentMask) & ~aAlignmentMask;
if (requestStart < reserveStart)
{
// Overflow here means the request can't be satisfied because the alignment is too large.
return nullptr;
}

const uintptr_t requestEnd = requestStart + aSize;
if (requestEnd < requestStart)
// This cast is safe because the difference is at most `aAlignmentMask`.
const uint16_t reserveAlignmentOffset = static_cast<uint16_t>(requestStart - reserveStart);

// This cast is not safe in itself, but the result is checked.
const uint16_t requestSize = static_cast<uint16_t>(reserveAlignmentOffset + aSize);
if (requestSize < aSize)
{
// Overflow here means the requested size can't possibly fit.
return nullptr;
}
if (requestEnd <= reinterpret_cast<uintptr_t>(payload))
{
// The request fits without moving payload data.
return reinterpret_cast<uint8_t *>(requestStart);
}

if (requestEnd - reserveStart + len > AllocSize())
if (!EnsureReservedSize(requestSize))
{
// Not enough space to move the payload.
// The requested size is too large for the available space.
return nullptr;
}

memmove(reinterpret_cast<void *>(requestEnd), payload, len);
payload = reinterpret_cast<uint8_t *>(requestEnd);
return reinterpret_cast<uint8_t *>(requestStart);
}

Expand Down
3 changes: 2 additions & 1 deletion src/system/tests/TestSystemPacketBuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1219,7 +1219,8 @@ void PacketBufferTest::CheckGetReserve(nlTestSuite * inSuite, void * inContext)
NL_TEST_ASSERT(inSuite, config.handle->ReservedSize() == instance.init.reserve_length);
NL_TEST_ASSERT(inSuite, config.handle->TotalLength() == instance.init.payload_length);

const uint8_t * const reserve = config.handle->GetReserve(instance.request.length, instance.request.alignment - 1);
const uint8_t * const reserve =
config.handle->GetReserve(instance.request.length, static_cast<uint16_t>(instance.request.alignment - 1));
if (instance.expect.success)
{
NL_TEST_ASSERT(inSuite, reserve != nullptr);
Expand Down

0 comments on commit d4fa0ab

Please sign in to comment.