Matter SDK Coverage Report
Current view: top level - system - SystemPacketBuffer.h (source / functions) Coverage Total Hit
Test: SHA:b879ecb8e99e175eea0a293a888bda853da2b19c Lines: 85.9 % 78 67
Test Date: 2025-01-17 19:00:11 Functions: 90.6 % 32 29

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2020-2021 Project CHIP Authors
       4              :  *    Copyright (c) 2016-2017 Nest Labs, Inc.
       5              :  *
       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
       9              :  *
      10              :  *        http://www.apache.org/licenses/LICENSE-2.0
      11              :  *
      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.
      17              :  */
      18              : 
      19              : /**
      20              :  *    @file
      21              :  *      This file defines the chip::System::PacketBuffer class,
      22              :  *      which provides the mechanisms for manipulating packets of *
      23              :  *      octet-serialized data.
      24              :  */
      25              : 
      26              : #pragma once
      27              : 
      28              : // Include configuration header
      29              : #include <system/SystemPacketBufferInternal.h>
      30              : 
      31              : // Include dependent headers
      32              : #include <lib/support/BufferWriter.h>
      33              : #include <lib/support/CodeUtils.h>
      34              : #include <lib/support/DLLUtil.h>
      35              : #include <system/SystemAlignSize.h>
      36              : #include <system/SystemError.h>
      37              : 
      38              : #include <stddef.h>
      39              : #include <utility>
      40              : 
      41              : #if CHIP_SYSTEM_CONFIG_USE_LWIP
      42              : #include <lwip/mem.h>
      43              : #include <lwip/memp.h>
      44              : #include <lwip/pbuf.h>
      45              : #endif // CHIP_SYSTEM_CONFIG_USE_LWIP
      46              : 
      47              : namespace chip {
      48              : namespace System {
      49              : 
      50              : class PacketBufferHandle;
      51              : 
      52              : #if !CHIP_SYSTEM_CONFIG_USE_LWIP
      53              : struct pbuf
      54              : {
      55              :     struct pbuf * next;
      56              :     void * payload;
      57              :     size_t tot_len;
      58              :     size_t len;
      59              :     uint16_t ref;
      60              : #if CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP
      61              :     size_t alloc_size;
      62              : #endif
      63              : };
      64              : #endif // !CHIP_SYSTEM_CONFIG_USE_LWIP
      65              : 
      66              : /**    @class PacketBuffer
      67              :  *
      68              :  *     @brief
      69              :  *      The packet buffer class is the core structure used for manipulating packets of octet-serialized data, usually in the
      70              :  *      context of a data communications network, like Bluetooth or the Internet protocol.
      71              :  *
      72              :  *      In LwIP-based environments, this class is built on top of the pbuf structure defined in that library. In the absence of
      73              :  *      LwIP, chip provides either a malloc-based implementation, or a pool-based implementation that closely approximates the
      74              :  *      memory challenges of deeply embedded devices.
      75              :  *
      76              :  *      The PacketBuffer class, like many similar structures used in layered network stacks, provide a mechanism to reserve space
      77              :  *      for protocol headers at each layer of a configurable communication stack.  For details, see `PacketBufferHandle::New()`
      78              :  *      as well as LwIP documentation.
      79              :  *
      80              :  *      PacketBuffer objects are reference-counted, and normally held and used through a PacketBufferHandle that owns one of the
      81              :  *      counted references. When a PacketBufferHandle goes out of scope, its reference is released. To take ownership, a function
      82              :  *      takes a PacketBufferHandle by value. To borrow ownership, a function takes a `const PacketBufferHandle &`.
      83              :  *
      84              :  *      New objects of PacketBuffer class are initialized at the beginning of an allocation of memory obtained from the underlying
      85              :  *      environment, e.g. from LwIP pbuf target pools, from the standard C library heap, from an internal buffer pool. In the
      86              :  *      simple pool case, the size of the data buffer is PacketBuffer::kBlockSize.
      87              :  *
      88              :  *      PacketBuffer objects may be chained to accommodate larger payloads.  Chaining, however, is not transparent, and users of the
      89              :  *      class must explicitly decide to support chaining.  Examples of classes written with chaining support are as follows:
      90              :  *
      91              :  *          @ref chip::TLVReader
      92              :  *          @ref chip::TLVWriter
      93              :  *
      94              :  * ### PacketBuffer format
      95              :  *
      96              :  * <pre>
      97              :  *           ┌────────────────────────────────────┐
      98              :  *           │       ┌────────────────────┐       │
      99              :  *           │       │                    │◁──────┴───────▷│
     100              :  *  ┏━━━━━━━━┿━━━━━━━┿━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┓
     101              :  *  ┃ pbuf len payload ┃ reserve          ┃ data           ┃ unused                  ┃
     102              :  *  ┗━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━┛
     103              :  *  │                  │← ReservedSize() →│← DataLength() →│← AvailableDataLength() →│
     104              :  *  │                  │                  │← MaxDataLength() → · · · · · · · · · · ·→│
     105              :  *  │                  │                  Start()                                    │
     106              :  *  │← kStructureSize →│← AllocSize() → · · · · · · · · · · · · · · · · · · · · · · →│
     107              :  * </pre>
     108              :  *
     109              :  */
     110              : class DLL_EXPORT PacketBuffer : private pbuf
     111              : {
     112              : private:
     113              :     // The effective size of the packet buffer structure.
     114              : #if CHIP_SYSTEM_CONFIG_USE_LWIP
     115              :     static constexpr size_t kStructureSize = LWIP_MEM_ALIGN_SIZE(sizeof(struct ::pbuf));
     116              : #else  // CHIP_SYSTEM_CONFIG_USE_LWIP
     117              :     static constexpr size_t kStructureSize         = CHIP_SYSTEM_ALIGN_SIZE(sizeof(::chip::System::pbuf), 4u);
     118              : #endif // CHIP_SYSTEM_CONFIG_USE_LWIP
     119              : 
     120              : public:
     121              :     /**
     122              :      * The maximum size of a regular buffer an application can allocate with no protocol header reserve.
     123              :      */
     124              : #if CHIP_SYSTEM_CONFIG_USE_LWIP
     125              :     static constexpr size_t kMaxSizeWithoutReserve = LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE);
     126              : #else
     127              :     static constexpr size_t kMaxSizeWithoutReserve = CHIP_SYSTEM_CONFIG_PACKETBUFFER_CAPACITY_MAX;
     128              : #endif
     129              : 
     130              :     /**
     131              :      * The number of bytes to reserve in a network packet buffer to contain all the possible protocol encapsulation headers
     132              :      * before the application data.
     133              :      */
     134              :     static constexpr uint16_t kDefaultHeaderReserve = CHIP_SYSTEM_CONFIG_HEADER_RESERVE_SIZE;
     135              : 
     136              :     /**
     137              :      * The maximum size of a regular buffer an application can allocate with the default protocol header reserve.
     138              :      */
     139              :     static constexpr size_t kMaxSize = kMaxSizeWithoutReserve - kDefaultHeaderReserve;
     140              : 
     141              :     /**
     142              :      * The maximum size of a large buffer(> IPv6 MTU) that an application can allocate with no protocol header reserve.
     143              :      */
     144              :     static constexpr size_t kLargeBufMaxSizeWithoutReserve = CHIP_SYSTEM_CONFIG_MAX_LARGE_BUFFER_SIZE_BYTES;
     145              : 
     146              :     /**
     147              :      * The maximum size of a large buffer(> IPv6 MTU) that an application can allocate with the default protocol header reserve.
     148              :      */
     149              :     static constexpr size_t kLargeBufMaxSize = kLargeBufMaxSizeWithoutReserve - kDefaultHeaderReserve;
     150              : 
     151              :     /**
     152              :      * Unified constant(both regular and large buffers) for the maximum size that an application can allocate with no
     153              :      * protocol header reserve.
     154              :      */
     155              : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
     156              :     static constexpr size_t kMaxAllocSize = kLargeBufMaxSizeWithoutReserve;
     157              : #else
     158              :     static constexpr size_t kMaxAllocSize          = kMaxSizeWithoutReserve;
     159              : #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
     160              : 
     161              :     /**
     162              :      * Return the size of the allocation including the reserved and payload data spaces but not including space
     163              :      * allocated for the PacketBuffer structure.
     164              :      *
     165              :      *  @note    The allocation size is equal to or greater than the \c aAllocSize parameter to the \c Create method).
     166              :      *
     167              :      *  @return     size of the allocation
     168              :      */
     169       128034 :     size_t AllocSize() const
     170              :     {
     171              : #if CHIP_SYSTEM_PACKETBUFFER_FROM_LWIP_STANDARD_POOL || CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_POOL
     172              :         return kMaxSizeWithoutReserve;
     173              : #elif CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP
     174       128034 :         return this->alloc_size;
     175              : #elif CHIP_SYSTEM_PACKETBUFFER_FROM_LWIP_CUSTOM_POOL
     176              :         // Temporary workaround for custom pbufs by assuming size to be PBUF_POOL_BUFSIZE
     177              :         if (this->flags & PBUF_FLAG_IS_CUSTOM)
     178              :             return LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE) - kStructureSize;
     179              :         else
     180              :             return LWIP_MEM_ALIGN_SIZE(memp_sizes[this->pool]) - kStructureSize;
     181              : #else
     182              : #error "Unimplemented PacketBuffer storage case"
     183              : #endif
     184              :     }
     185              : 
     186              :     /**
     187              :      * Get a pointer to the start of data in a buffer.
     188              :      *
     189              :      *  @return pointer to the start of data.
     190              :      */
     191       369031 :     uint8_t * Start() const { return static_cast<uint8_t *>(this->payload); }
     192              : 
     193              :     /**
     194              :      *  Set the the start of data in a buffer, adjusting length and total length accordingly.
     195              :      *
     196              :      *  @note The data within the buffer is not moved, only accounting information is changed.  The function is commonly used to
     197              :      *      either strip or prepend protocol headers in a zero-copy way.
     198              :      *
     199              :      *  @note This call should not be used on any buffer that is not the head of a buffer chain, as it only alters the current
     200              :      *      buffer.
     201              :      *
     202              :      *  @param[in] aNewStart - A pointer to where the new payload should start.  newStart will be adjusted internally to fall within
     203              :      *      the boundaries of the first buffer in the PacketBuffer chain.
     204              :      */
     205              :     void SetStart(uint8_t * aNewStart);
     206              : 
     207              :     /**
     208              :      * Get the length, in bytes, of data in a packet buffer.
     209              :      *
     210              :      *  @return length, in bytes (current payload length).
     211              :      */
     212       163364 :     size_t DataLength() const { return this->len; }
     213              : 
     214              :     /**
     215              :      * Set the length, in bytes, of data in a packet buffer, adjusting total length accordingly.
     216              :      *
     217              :      *  The function sets the length, in bytes, of the data in the buffer, adjusting the total length appropriately. When the buffer
     218              :      *  is not the head of the buffer chain (common case: the caller adds data to the last buffer in the PacketBuffer chain prior to
     219              :      *  calling higher layers), the aChainHead __must__ be passed in to properly adjust the total lengths of each buffer ahead of
     220              :      *  the current buffer.
     221              :      *
     222              :      *  @param[in] aNewLen - new length, in bytes, of this buffer.
     223              :      *
     224              :      *  @param[in,out] aChainHead - the head of the buffer chain the current buffer belongs to.  May be \c nullptr if the current
     225              :      *      buffer is the head of the buffer chain.
     226              :      */
     227              :     void SetDataLength(size_t aNewLen, const PacketBufferHandle & aChainHead);
     228        19912 :     void SetDataLength(size_t aNewLen) { SetDataLength(aNewLen, nullptr); }
     229              : 
     230              :     /**
     231              :      * Get the total length of packet data in the buffer chain.
     232              :      *
     233              :      *  @return total length, in octets.
     234              :      */
     235        53841 :     size_t TotalLength() const { return this->tot_len; }
     236              : 
     237              :     /**
     238              :      * Get the maximum amount, in bytes, of data that will fit in the buffer given the current start position and buffer size.
     239              :      *
     240              :      *  @return number of bytes that fits in the buffer given the current start position.
     241              :      */
     242              :     size_t MaxDataLength() const;
     243              : 
     244              :     /**
     245              :      * Get the number of bytes of data that can be added to the current buffer given the current start position and data length.
     246              :      *
     247              :      *  @return the length, in bytes, of data that will fit in the current buffer given the current start position and data length.
     248              :      */
     249              :     size_t AvailableDataLength() const;
     250              : 
     251              :     /**
     252              :      * Get the number of bytes within the current buffer between the start of the buffer and the current data start position.
     253              :      *
     254              :      *  @return the amount, in bytes, of space between the start of the buffer and the current data start position.
     255              :      */
     256              :     uint16_t ReservedSize() const;
     257              : 
     258              :     /**
     259              :      * Determine whether there are any additional buffers chained to the current buffer.
     260              :      *
     261              :      *  @return \c true if there is a chained buffer.
     262              :      */
     263        41060 :     bool HasChainedBuffer() const { return ChainedBuffer() != nullptr; }
     264              : 
     265              :     /**
     266              :      * Add the given packet buffer to the end of the buffer chain, adjusting the total length of each buffer in the chain
     267              :      * accordingly.
     268              :      *
     269              :      *  @note The current packet buffer must be the head of the buffer chain for the lengths to be adjusted properly.
     270              :      *
     271              :      *  @note Ownership is transferred from the argument to the `next` link at the end of the current chain.
     272              :      *
     273              :      *  @param[in] aPacket - the packet buffer to be added to the end of the current chain.
     274              :      */
     275              :     void AddToEnd(PacketBufferHandle && aPacket);
     276              : 
     277              :     /**
     278              :      * Move data from subsequent buffers in the chain into the current buffer until it is full.
     279              :      *
     280              :      *  Only the current buffer is compacted: the data within the current buffer is moved to the front of the buffer, eliminating
     281              :      *  any reserved space. The remaining available space is filled with data moved from subsequent buffers in the chain, until the
     282              :      *  current buffer is full. If a subsequent buffer in the chain is moved into the current buffer in its entirety, it is removed
     283              :      *  from the chain and freed. The method takes no parameters, returns no results and cannot fail.
     284              :      */
     285              :     void CompactHead();
     286              : 
     287              :     /**
     288              :      * Adjust the current buffer to indicate the amount of data consumed.
     289              :      *
     290              :      *  Advance the data start position in the current buffer by the specified amount, in bytes, up to the length of data in the
     291              :      *  buffer. Decrease the length and total length by the amount consumed.
     292              :      *
     293              :      *  @param[in] aConsumeLength - number of bytes to consume from the current buffer.
     294              :      */
     295              :     void ConsumeHead(size_t aConsumeLength);
     296              : 
     297              :     /**
     298              :      * Ensure the buffer has at least the specified amount of reserved space.
     299              :      *
     300              :      *  Ensure the buffer has at least the specified amount of reserved space, moving the data in the buffer forward to make room if
     301              :      *  necessary.
     302              :      *
     303              :      *  @param[in] aReservedSize - number of bytes desired for the headers.
     304              :      *
     305              :      *  @return \c true if the requested reserved size is available, \c false if there's not enough room in the buffer.
     306              :      */
     307              :     CHECK_RETURN_VALUE bool EnsureReservedSize(uint16_t aReservedSize);
     308              : 
     309              :     /**
     310              :      * Align the buffer payload on the specified bytes boundary.
     311              :      *
     312              :      *  Moving the payload in the buffer forward if necessary.
     313              :      *
     314              :      *  @param[in] aAlignBytes - specifies number of bytes alignment for the payload start pointer.
     315              :      *
     316              :      *  @return \c true if alignment is successful, \c false if there's not enough room in the buffer.
     317              :      */
     318              :     bool AlignPayload(uint16_t aAlignBytes);
     319              : 
     320              :     /**
     321              :      * Return the next buffer in a buffer chain.
     322              :      *
     323              :      *  If there is no next buffer, the handle will have \c IsNull() \c true.
     324              :      *
     325              :      *  @return a handle to the next buffer in the buffer chain.
     326              :      */
     327              :     CHECK_RETURN_VALUE PacketBufferHandle Next();
     328              : 
     329              :     /**
     330              :      * Return the last buffer in a buffer chain.
     331              :      *
     332              :      *  @return a handle to the last buffer in the buffer chain.
     333              :      */
     334              :     CHECK_RETURN_VALUE PacketBufferHandle Last();
     335              : 
     336              :     /**
     337              :      * Copies data from the payloads of a chain of packet buffers until a given amount of data has been copied.
     338              :      *
     339              :      * @param[in]  buf             Destination buffer; must be at least @a length bytes.
     340              :      * @param[in]  length          Destination buffer length.
     341              :      *
     342              :      * @retval #CHIP_ERROR_BUFFER_TOO_SMALL If the total length of the payloads in the chain is less than the requested @a length.
     343              :      * @retval #CHIP_ERROR_INTERNAL         In case of an inconsistency in the buffer chain.
     344              :      * @retval #CHIP_NO_ERROR               If the requested payload has been copied.
     345              :      */
     346              :     CHIP_ERROR Read(uint8_t * buf, size_t length) const;
     347              :     template <size_t N>
     348           13 :     inline CHIP_ERROR Read(uint8_t (&buf)[N]) const
     349              :     {
     350           13 :         return Read(buf, N);
     351              :     }
     352              : 
     353              :     /**
     354              :      * Perform an implementation-defined check on the validity of a PacketBuffer pointer.
     355              :      *
     356              :      * Unless enabled by #CHIP_CONFIG_MEMORY_DEBUG_CHECKS == 1, this function does nothing.
     357              :      *
     358              :      * When enabled, it performs an implementation- and configuration-defined check on
     359              :      * the validity of the packet buffer. It MAY log an error and/or abort the program
     360              :      * if the packet buffer or the implementation-defined memory management system is in
     361              :      * a faulty state. (Some configurations may not actually perform any check.)
     362              :      *
     363              :      * @note  A null pointer is not considered faulty.
     364              :      *
     365              :      *  @param[in] buffer - the packet buffer to check.
     366              :      */
     367        45816 :     static void Check(const PacketBuffer * buffer)
     368              :     {
     369              : #if CHIP_SYSTEM_PACKETBUFFER_HAS_CHECK
     370              :         InternalCheck(buffer);
     371              : #endif
     372        45816 :     }
     373              : 
     374              : private:
     375              :     // Memory required for a maximum-size PacketBuffer.
     376              :     static constexpr uint16_t kBlockSize = PacketBuffer::kStructureSize + PacketBuffer::kMaxSizeWithoutReserve;
     377              : 
     378              :     // Note: this condition includes DOXYGEN to work around a Doxygen error. DOXYGEN is never defined in any actual build.
     379              : #if CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_POOL || defined(DOXYGEN)
     380              :     typedef union
     381              :     {
     382              :         pbuf Header;
     383              :         uint8_t Block[PacketBuffer::kBlockSize];
     384              :     } BufferPoolElement;
     385              :     static BufferPoolElement sBufferPool[CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE];
     386              :     static PacketBuffer * sFreeList;
     387              :     static PacketBuffer * BuildFreeList();
     388              : #endif // CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_POOL || defined(DOXYGEN)
     389              : 
     390              : #if CHIP_SYSTEM_PACKETBUFFER_HAS_CHECK
     391              :     static void InternalCheck(const PacketBuffer * buffer);
     392              : #endif
     393              : 
     394              :     void AddRef();
     395              :     bool HasSoleOwnership() const { return (this->ref == 1); }
     396              :     static void Free(PacketBuffer * aPacket);
     397              :     static PacketBuffer * FreeHead(PacketBuffer * aPacket);
     398              : 
     399       122090 :     PacketBuffer * ChainedBuffer() const { return static_cast<PacketBuffer *>(this->next); }
     400              :     PacketBuffer * Consume(size_t aConsumeLength);
     401              :     void Clear();
     402              :     void SetDataLength(size_t aNewLen, PacketBuffer * aChainHead);
     403              : 
     404              :     /**
     405              :      * Get a pointer to the start of the reserved space (which comes before the
     406              :      * payload).  The actual reserved space is the ReservedSize() bytes starting
     407              :      * at this pointer.
     408              :      */
     409              :     uint8_t * ReserveStart();
     410              :     const uint8_t * ReserveStart() const;
     411              : 
     412              :     friend class PacketBufferHandle;
     413              :     friend class TestSystemPacketBuffer;
     414              : };
     415              : 
     416              : static_assert(sizeof(pbuf) == sizeof(PacketBuffer), "PacketBuffer must not have additional members");
     417              : 
     418              : /**
     419              :  * @class PacketBufferHandle
     420              :  *
     421              :  * @brief
     422              :  *  Tracks ownership of a PacketBuffer.
     423              :  *
     424              :  *  PacketBuffer objects are reference-counted, and normally held and used through a PacketBufferHandle that owns one of the
     425              :  *  counted references. When a PacketBufferHandle goes out of scope, its reference is released. To take ownership, a function
     426              :  *  takes a PacketBufferHandle by value. To borrow ownership, a function takes a `const PacketBufferHandle &`.
     427              :  */
     428              : class DLL_EXPORT PacketBufferHandle
     429              : {
     430              : public:
     431              :     /**
     432              :      * Construct an empty PacketBufferHandle.
     433              :      */
     434            1 :     PacketBufferHandle() : mBuffer(nullptr) {}
     435        22264 :     PacketBufferHandle(decltype(nullptr)) : mBuffer(nullptr) {}
     436              : 
     437              :     /**
     438              :      * Construct a PacketBufferHandle that takes ownership of a PacketBuffer from another.
     439              :      */
     440        68876 :     PacketBufferHandle(PacketBufferHandle && aOther)
     441        68876 :     {
     442        68876 :         mBuffer        = aOther.mBuffer;
     443        68876 :         aOther.mBuffer = nullptr;
     444        68876 :     }
     445              : 
     446            1 :     ~PacketBufferHandle() { *this = nullptr; }
     447              : 
     448              :     /**
     449              :      * Take ownership of a PacketBuffer from another PacketBufferHandle, freeing any existing owned buffer.
     450              :      */
     451        79661 :     PacketBufferHandle & operator=(PacketBufferHandle && aOther)
     452              :     {
     453        79661 :         if (mBuffer != nullptr)
     454              :         {
     455           30 :             PacketBuffer::Free(mBuffer);
     456              :         }
     457        79661 :         mBuffer        = aOther.mBuffer;
     458        79661 :         aOther.mBuffer = nullptr;
     459        79661 :         return *this;
     460              :     }
     461              : 
     462              :     /**
     463              :      * Free any buffer owned by this handle.
     464              :      */
     465            1 :     PacketBufferHandle & operator=(decltype(nullptr))
     466              :     {
     467            1 :         if (mBuffer != nullptr)
     468              :         {
     469            0 :             PacketBuffer::Free(mBuffer);
     470              :         }
     471            1 :         mBuffer = nullptr;
     472            1 :         return *this;
     473              :     }
     474              : 
     475              :     /**
     476              :      * Get a new handle to an existing buffer.
     477              :      *
     478              :      * @return a PacketBufferHandle that shares ownership with this.
     479              :      */
     480        23916 :     PacketBufferHandle Retain() const
     481              :     {
     482        23916 :         mBuffer->AddRef();
     483        23916 :         return PacketBufferHandle(mBuffer);
     484              :     }
     485              : 
     486              :     /**
     487              :      * Access a PackerBuffer's public methods.
     488              :      */
     489       471813 :     PacketBuffer * operator->() const { return mBuffer; }
     490              : 
     491              :     /**
     492              :      * Test whether this PacketBufferHandle is empty, or conversely owns a PacketBuffer.
     493              :      *
     494              :      * @return \c true if this PacketBufferHandle is empty; return \c false if it owns a PacketBuffer.
     495              :      */
     496        86969 :     bool IsNull() const { return mBuffer == nullptr; }
     497              : 
     498              :     /**
     499              :      * Test whether the PacketBuffer owned by this PacketBufferHandle has unique ownership.
     500              :      *
     501              :      * @return \c true if the PacketBuffer owned by this PacketBufferHandle is solely owned; return \c false if
     502              :      * it has more than one ownership.
     503              :      */
     504              :     bool HasSoleOwnership() const { return mBuffer->HasSoleOwnership(); }
     505              : 
     506              :     /**
     507              :      *  Detach and return the head of a buffer chain while updating this handle to point to the remaining buffers.
     508              :      *  The current buffer must be the head of the chain.
     509              :      *
     510              :      *  This PacketBufferHandle now holds the ownership formerly held by the head of the chain.
     511              :      *  The returned PacketBufferHandle holds the ownership formerly held by this.
     512              :      *
     513              :      *  @return the detached buffer formerly at the head of the buffer chain.
     514              :      */
     515              :     CHECK_RETURN_VALUE PacketBufferHandle PopHead();
     516              : 
     517              :     /**
     518              :      * Free the first buffer in a chain.
     519              :      *
     520              :      *  @note When the buffer chain is referenced by multiple handles, `FreeHead()` will detach the head, but will not forcibly
     521              :      *  deallocate the head buffer.
     522              :      */
     523            7 :     void FreeHead()
     524              :     {
     525              :         // `PacketBuffer::FreeHead()` frees the current head; this takes ownership from the `next` link.
     526            7 :         mBuffer = PacketBuffer::FreeHead(mBuffer);
     527            7 :     }
     528              : 
     529              :     /**
     530              :      * Add the given packet buffer to the end of the buffer chain, adjusting the total length of each buffer in the chain
     531              :      * accordingly.
     532              :      *
     533              :      *  @note The current packet buffer handle must either be the head of the buffer chain for the lengths to be adjusted properly,
     534              :      *        or be null (in which case it becomes the head).
     535              :      *
     536              :      *  @note Ownership is transferred from the argument to the `next` link at the end of the current chain,
     537              :      *        or to the handle if it's currently null.
     538              :      *
     539              :      *  @param[in] aPacket - the packet buffer to be added to the end of the current chain.
     540              :      */
     541         1805 :     void AddToEnd(PacketBufferHandle && aPacket)
     542              :     {
     543         1805 :         if (IsNull())
     544              :         {
     545          493 :             mBuffer         = aPacket.mBuffer;
     546          493 :             aPacket.mBuffer = nullptr;
     547              :         }
     548              :         else
     549              :         {
     550         1312 :             mBuffer->AddToEnd(std::move(aPacket));
     551              :         }
     552         1805 :     }
     553              : 
     554              :     /**
     555              :      * Consume data in a chain of buffers.
     556              :      *
     557              :      *  Consume data in a chain of buffers starting with the current buffer and proceeding through the remaining buffers in the
     558              :      *  chain. Each buffer that is completely consumed is freed and the handle holds the first buffer (if any) containing the
     559              :      *  remaining data. The current buffer must be the head of the buffer chain.
     560              :      *
     561              :      *  @param[in] aConsumeLength - number of bytes to consume from the current chain.
     562              :      */
     563           15 :     void Consume(size_t aConsumeLength) { mBuffer = mBuffer->Consume(aConsumeLength); }
     564              : 
     565              :     /**
     566              :      * Copy the given buffer to a right-sized buffer if applicable.
     567              :      *
     568              :      * Only operates on single buffers (for chains, use \c CompactHead() and RightSize the tail).
     569              :      * Requires that this handle be the only reference to the underlying buffer.
     570              :      */
     571         7709 :     void RightSize()
     572              :     {
     573              : #if CHIP_SYSTEM_PACKETBUFFER_HAS_RIGHTSIZE
     574         7709 :         InternalRightSize();
     575              : #endif
     576         7709 :     }
     577              : 
     578              :     /**
     579              :      * Get a new handle to a raw PacketBuffer pointer.
     580              :      *
     581              :      * @brief The caller's ownership is transferred to this.
     582              :      *
     583              :      * @note This should only be used in low-level code, e.g. to import buffers from LwIP or a similar stack.
     584              :      */
     585              :     static PacketBufferHandle Adopt(PacketBuffer * buffer) { return PacketBufferHandle(buffer); }
     586              : #if CHIP_SYSTEM_CONFIG_USE_LWIP
     587              :     static PacketBufferHandle Adopt(pbuf * buffer) { return Adopt(reinterpret_cast<PacketBuffer *>(buffer)); }
     588              : #endif // CHIP_SYSTEM_CONFIG_USE_LWIP
     589              : 
     590              :     /**
     591              :      * Advance this PacketBufferHandle to the next buffer in a chain.
     592              :      *
     593              :      *  @note This differs from `FreeHead()` in that it does not touch any content in the currently referenced packet buffer;
     594              :      *      it only changes which buffer this handle owns. (Note that this could result in the previous buffer being freed,
     595              :      *      if there is no other owner.) `Advance()` is designed to be used with an additional handle to traverse a buffer chain,
     596              :      *      whereas `FreeHead()` modifies a chain.
     597              :      */
     598            0 :     void Advance() { *this = Hold(mBuffer->ChainedBuffer()); }
     599              : 
     600              :     /**
     601              :      * Export a raw PacketBuffer pointer.
     602              :      *
     603              :      * @brief The PacketBufferHandle's ownership is transferred to the caller.
     604              :      *
     605              :      * @note This should only be used in low-level code. The caller owns one counted reference to the \c PacketBuffer
     606              :      *       and is responsible for managing it safely.
     607              :      *
     608              :      * @note The ref-qualifier `&&` requires the caller to use `std::move` to emphasize that ownership is
     609              :      *       moved out of this handle.
     610              :      */
     611         1709 :     CHECK_RETURN_VALUE PacketBuffer * UnsafeRelease() &&
     612              :     {
     613         1709 :         PacketBuffer::Check(mBuffer);
     614         1709 :         PacketBuffer * buffer = mBuffer;
     615         1709 :         mBuffer               = nullptr;
     616         1709 :         return buffer;
     617              :     }
     618              : 
     619              :     /**
     620              :      * Allocates a packet buffer.
     621              :      *
     622              :      *  A packet buffer is conceptually divided into two parts:
     623              :      *  @li  Space reserved for network protocol headers. The size of this space normally defaults to a value determined
     624              :      *       by the network layer configuration, but can be given explicity by \c aReservedSize for special cases.
     625              :      *  @li  Space for application data. The minimum size of this space is given by \c aAvailableSize, and then \c Start()
     626              :      *       provides a pointer to the start of this space.
     627              :      *
     628              :      *  Fails and returns \c nullptr if no memory is available, or if the size requested is too large.
     629              :      *  When the sum of \a aAvailableSize and \a aReservedSize is no greater than \c PacketBuffer::kMaxSizeWithoutReserve,
     630              :      *  that is guaranteed not to be too large.
     631              :      *
     632              :      *  On success, it is guaranteed that \c AvailableDataSize() is no less than \a aAvailableSize.
     633              :      *
     634              :      *  @param[in]  aAvailableSize  Minimum number of octets to for application data (at `Start()`).
     635              :      *  @param[in]  aReservedSize   Number of octets to reserve for protocol headers (before `Start()`).
     636              :      *
     637              :      *  @return     On success, a PacketBufferHandle to the allocated buffer. On fail, \c nullptr.
     638              :      */
     639              :     static PacketBufferHandle New(size_t aAvailableSize, uint16_t aReservedSize = PacketBuffer::kDefaultHeaderReserve);
     640              : 
     641              :     /**
     642              :      * Allocates a packet buffer with initial contents.
     643              :      *
     644              :      *  @param[in]  aData           Initial buffer contents.
     645              :      *  @param[in]  aDataSize       Size of initial buffer contents.
     646              :      *  @param[in]  aAdditionalSize Size of additional application data space after the initial contents.
     647              :      *  @param[in]  aReservedSize   Number of octets to reserve for protocol headers.
     648              :      *
     649              :      *  @return     On success, a PacketBufferHandle to the allocated buffer. On fail, \c nullptr.
     650              :      */
     651              :     static PacketBufferHandle NewWithData(const void * aData, size_t aDataSize, size_t aAdditionalSize = 0,
     652              :                                           uint16_t aReservedSize = PacketBuffer::kDefaultHeaderReserve);
     653              : 
     654              :     /**
     655              :      * Creates a copy of a packet buffer (or chain).
     656              :      *
     657              :      * @returns empty handle on allocation failure. Otherwise, the returned buffer has the same sizes and contents as the original.
     658              :      */
     659              :     PacketBufferHandle CloneData() const;
     660              : 
     661              :     /**
     662              :      * Perform an implementation-defined check on the validity of a PacketBufferHandle.
     663              :      *
     664              :      * Unless enabled by #CHIP_CONFIG_MEMORY_DEBUG_CHECKS == 1, this function does nothing.
     665              :      *
     666              :      * When enabled, it performs an implementation- and configuration-defined check on
     667              :      * the validity of the packet buffer. It MAY log an error and/or abort the program
     668              :      * if the packet buffer or the implementation-defined memory management system is in
     669              :      * a faulty state. (Some configurations may not actually perform any check.)
     670              :      *
     671              :      * @note  A null handle is not considered faulty.
     672              :      */
     673              :     void Check() const
     674              :     {
     675              : #if CHIP_SYSTEM_PACKETBUFFER_HAS_CHECK
     676              :         PacketBuffer::Check(mBuffer);
     677              : #endif
     678              :     }
     679              : 
     680              :     bool operator==(const PacketBufferHandle & aOther) const { return mBuffer == aOther.mBuffer; }
     681              : 
     682              : protected:
     683              : #if CHIP_SYSTEM_CONFIG_USE_LWIP
     684              :     // For use via LwIPPacketBufferView only.
     685              :     static struct pbuf * GetLwIPpbuf(const PacketBufferHandle & handle)
     686              :     {
     687              :         PacketBuffer::Check(handle.mBuffer);
     688              :         return static_cast<struct pbuf *>(handle.mBuffer);
     689              :     }
     690              : #endif // CHIP_SYSTEM_CONFIG_USE_LWIP
     691              : 
     692              : private:
     693              :     PacketBufferHandle(const PacketBufferHandle &)             = delete;
     694              :     PacketBufferHandle & operator=(const PacketBufferHandle &) = delete;
     695              : 
     696              :     // The caller's ownership is transferred to this.
     697        50394 :     explicit PacketBufferHandle(PacketBuffer * buffer) : mBuffer(buffer) {}
     698              : 
     699            0 :     static PacketBufferHandle Hold(PacketBuffer * buffer)
     700              :     {
     701            0 :         if (buffer != nullptr)
     702              :         {
     703            0 :             buffer->AddRef();
     704              :         }
     705            0 :         return PacketBufferHandle(buffer);
     706              :     }
     707              : 
     708              :     PacketBuffer * Get() const { return mBuffer; }
     709              :     PacketBuffer * GetNext() const { return static_cast<PacketBuffer *>(mBuffer->next); }
     710              : 
     711              : #if CHIP_SYSTEM_PACKETBUFFER_HAS_RIGHTSIZE
     712              :     void InternalRightSize();
     713              : #endif
     714              : 
     715              :     PacketBuffer * mBuffer;
     716              : 
     717              :     friend class PacketBuffer;
     718              :     friend class TestSystemPacketBuffer;
     719              : };
     720              : 
     721        23252 : inline void PacketBuffer::SetDataLength(size_t aNewLen, const PacketBufferHandle & aChainHead)
     722              : {
     723        23252 :     SetDataLength(aNewLen, aChainHead.mBuffer);
     724        23252 : }
     725              : 
     726              : inline PacketBufferHandle PacketBuffer::Next()
     727              : {
     728              :     return PacketBufferHandle::Hold(ChainedBuffer());
     729              : }
     730              : 
     731            0 : inline PacketBufferHandle PacketBuffer::Last()
     732              : {
     733            0 :     PacketBuffer * p = this;
     734            0 :     while (p->HasChainedBuffer())
     735            0 :         p = p->ChainedBuffer();
     736            0 :     return PacketBufferHandle::Hold(p);
     737              : }
     738              : 
     739              : } // namespace System
     740              : 
     741              : namespace Encoding {
     742              : 
     743              : class PacketBufferWriterUtil
     744              : {
     745              : private:
     746              :     template <typename>
     747              :     friend class PacketBufferWriterBase;
     748              :     static System::PacketBufferHandle Finalize(BufferWriter & aBufferWriter, System::PacketBufferHandle & aPacket);
     749              : };
     750              : 
     751              : /**
     752              :  * BufferWriter backed by packet buffer.
     753              :  *
     754              :  * Typical use:
     755              :  *  @code
     756              :  *      PacketBufferWriter buf(maximumLength);
     757              :  *      if (buf.IsNull()) { return CHIP_ERROR_NO_MEMORY; }
     758              :  *      buf.Put(...);
     759              :  *      ...
     760              :  *      PacketBufferHandle handle = buf.Finalize();
     761              :  *      if (buf.IsNull()) { return CHIP_ERROR_BUFFER_TOO_SMALL; }
     762              :  *      // valid data
     763              :  *  @endcode
     764              :  */
     765              : template <class Writer>
     766              : class PacketBufferWriterBase : public Writer
     767              : {
     768              : public:
     769              :     /**
     770              :      * Constructs a BufferWriter that writes into a packet buffer, using all available space.
     771              :      *
     772              :      *  @param[in]  aPacket  A handle to PacketBuffer, to be used as backing store for the BufferWriter.
     773              :      */
     774           17 :     PacketBufferWriterBase(System::PacketBufferHandle && aPacket) :
     775           17 :         Writer(aPacket->Start() + aPacket->DataLength(), aPacket->AvailableDataLength())
     776              :     {
     777           17 :         mPacket = std::move(aPacket);
     778           17 :     }
     779              : 
     780              :     /**
     781              :      * Constructs a BufferWriter that writes into a packet buffer, using no more than the requested space.
     782              :      *
     783              :      *  @param[in]  aPacket A handle to PacketBuffer, to be used as backing store for the BufferWriter.
     784              :      *  @param[in]  aSize   Maximum number of octects to write into the packet buffer.
     785              :      */
     786           44 :     PacketBufferWriterBase(System::PacketBufferHandle && aPacket, size_t aSize) :
     787           44 :         Writer(aPacket->Start() + aPacket->DataLength(), std::min(aSize, static_cast<size_t>(aPacket->AvailableDataLength())))
     788              :     {
     789           44 :         mPacket = std::move(aPacket);
     790           44 :     }
     791              : 
     792              :     /**
     793              :      * Test whether this PacketBufferWriter is null, or conversely owns a PacketBuffer.
     794              :      *
     795              :      * @retval true     The PacketBufferWriter is null; it does not own a PacketBuffer. This implies either that
     796              :      *                  construction failed, or that \c Finalize() has previously been called to release the buffer.
     797              :      * @retval false    The PacketBufferWriter owns a PacketBuffer, which can be written using BufferWriter \c Put() methods,
     798              :      *                  and (assuming no overflow) obtained by calling \c Finalize().
     799              :      */
     800           44 :     bool IsNull() const { return mPacket.IsNull(); }
     801              : 
     802              :     /**
     803              :      * Obtain the backing packet buffer, if it is valid.
     804              :      *
     805              :      *  If construction succeeded, \c Finalize() has not already been called, and \c BufferWriter::Fit() is true,
     806              :      *  the caller takes ownership of a buffer containing the desired data. Otherwise, the returned handle tests null,
     807              :      *  and any underlying storage has been released.
     808              :      *
     809              :      *  @return     A packet buffer handle.
     810              :      */
     811           61 :     System::PacketBufferHandle Finalize() { return PacketBufferWriterUtil::Finalize(*this, mPacket); }
     812              : 
     813              : private:
     814              :     System::PacketBufferHandle mPacket;
     815              : };
     816              : 
     817              : using PacketBufferWriter = PacketBufferWriterBase<chip::Encoding::BufferWriter>;
     818              : 
     819              : namespace LittleEndian {
     820              : using PacketBufferWriter = PacketBufferWriterBase<chip::Encoding::LittleEndian::BufferWriter>;
     821              : } // namespace LittleEndian
     822              : 
     823              : namespace BigEndian {
     824              : using PacketBufferWriter = PacketBufferWriterBase<chip::Encoding::BigEndian::BufferWriter>;
     825              : } // namespace BigEndian
     826              : 
     827              : } // namespace Encoding
     828              : 
     829              : } // namespace chip
     830              : 
     831              : #if CHIP_SYSTEM_CONFIG_USE_LWIP
     832              : 
     833              : namespace chip {
     834              : 
     835              : namespace Inet {
     836              : class UDPEndPointImplLwIP;
     837              : } // namespace Inet
     838              : 
     839              : namespace System {
     840              : 
     841              : /**
     842              :  * Provide low-level access to a raw `pbuf *`, limited to specific classes that interface with LwIP.
     843              :  */
     844              : class LwIPPacketBufferView : public PacketBufferHandle
     845              : {
     846              : private:
     847              :     /**
     848              :      * Borrow a raw LwIP `pbuf *`.
     849              :      *
     850              :      * @brief The caller has access but no ownership.
     851              :      *
     852              :      * @note This should be used ONLY by low-level code interfacing with LwIP.
     853              :      */
     854              :     static struct pbuf * UnsafeGetLwIPpbuf(const PacketBufferHandle & handle) { return PacketBufferHandle::GetLwIPpbuf(handle); }
     855              :     friend class Inet::UDPEndPointImplLwIP;
     856              : };
     857              : 
     858              : } // namespace System
     859              : } // namespace chip
     860              : 
     861              : #endif // CHIP_SYSTEM_CONFIG_USE_LWIP
        

Generated by: LCOV version 2.0-1