3 * Copyright (c) 2021 Project CHIP Authors
4 * Copyright (c) 2013-2017 Nest Labs, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
21 * This file contains an implementation of TLVBackingStore using PacketBuffers.
24 #include <system/TLVPacketBufferBackingStore.h>
26 #include <support/SafeInt.h>
31 CHIP_ERROR TLVPacketBufferBackingStore::OnInit(chip::TLV::TLVReader & reader, const uint8_t *& bufStart, uint32_t & bufLen)
33 bufStart = mHeadBuffer->Start();
34 bufLen = mHeadBuffer->DataLength();
38 CHIP_ERROR TLVPacketBufferBackingStore::GetNextBuffer(chip::TLV::TLVReader & reader, const uint8_t *& bufStart, uint32_t & bufLen)
40 if (mUseChainedBuffers)
42 mCurrentBuffer.Advance();
46 mCurrentBuffer = nullptr;
49 if (mCurrentBuffer.IsNull())
56 bufStart = mCurrentBuffer->Start();
57 bufLen = mCurrentBuffer->DataLength();
63 CHIP_ERROR TLVPacketBufferBackingStore::OnInit(chip::TLV::TLVWriter & writer, uint8_t *& bufStart, uint32_t & bufLen)
65 bufStart = mHeadBuffer->Start() + mHeadBuffer->DataLength();
66 bufLen = mHeadBuffer->AvailableDataLength();
70 CHIP_ERROR TLVPacketBufferBackingStore::FinalizeBuffer(chip::TLV::TLVWriter & writer, uint8_t * bufStart, uint32_t dataLen)
72 uint8_t * endPtr = bufStart + dataLen;
74 intptr_t length = endPtr - mCurrentBuffer->Start();
75 if (!CanCastTo<uint16_t>(length))
77 return CHIP_ERROR_INVALID_ARGUMENT;
79 mCurrentBuffer->SetDataLength(static_cast<uint16_t>(length));
84 CHIP_ERROR TLVPacketBufferBackingStore::GetNewBuffer(chip::TLV::TLVWriter & writer, uint8_t *& bufStart, uint32_t & bufLen)
86 if (!mUseChainedBuffers)
88 return CHIP_ERROR_NO_MEMORY;
91 mCurrentBuffer.Advance();
92 if (mCurrentBuffer.IsNull())
94 mCurrentBuffer = PacketBufferHandle::New(System::PacketBuffer::kMaxSizeWithoutReserve, 0);
95 if (mCurrentBuffer.IsNull())
97 return CHIP_ERROR_NO_MEMORY;
99 mHeadBuffer->AddToEnd(mCurrentBuffer.Retain());
102 if (mCurrentBuffer.IsNull())
109 bufStart = mCurrentBuffer->Start();
110 bufLen = mCurrentBuffer->MaxDataLength();
113 return CHIP_NO_ERROR;
116 } // namespace System