• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2021, The OpenThread Authors.
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *  1. Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  *  2. Redistributions in binary form must reproduce the above copyright
10  *     notice, this list of conditions and the following disclaimer in the
11  *     documentation and/or other materials provided with the distribution.
12  *  3. Neither the name of the copyright holder nor the
13  *     names of its contributors may be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  *   This file includes definitions for a `Data` and `MutableData`.
32  */
33 
34 #ifndef DATA_HPP_
35 #define DATA_HPP_
36 
37 #include "openthread-core-config.h"
38 
39 #include <stdint.h>
40 #include <string.h>
41 
42 #include "common/clearable.hpp"
43 #include "common/code_utils.hpp"
44 #include "common/const_cast.hpp"
45 #include "common/equatable.hpp"
46 #include "common/error.hpp"
47 #include "common/num_utils.hpp"
48 #include "common/type_traits.hpp"
49 
50 namespace ot {
51 
52 /**
53  * Type is used as the template parameter in `Data` and `MutableData` to indicate the `uint` type to
54  * use for the data length.
55  */
56 enum DataLengthType : uint8_t
57 {
58     kWithUint8Length,  ///< Use `uint8_t` for data length.
59     kWithUint16Length, ///< Use `uint16_t` for data length
60 };
61 
62 /**
63  * Specifies a function pointer which matches two given bytes.
64  *
65  * Such a function is used as a parameter in `Data::MatchesByteIn()` method. This can be used to relax the definition
66  * of a match when comparing data bytes, e.g., can be used for case-insensitive string comparison.
67  *
68  * @param[in] aFirst   A first byte.
69  * @param[in] aSecond  A second byte.
70  *
71  * @retval TRUE  if @p aFirst matches @p aSecond.
72  * @retval FALSE if @p aFirst does not match @p aSecond.
73  */
74 typedef bool (*ByteMatcher)(uint8_t aFirst, uint8_t aSecond);
75 
76 /**
77  * Implements common utility methods used by `Data` and `MutableData`.
78  */
79 class DataUtils
80 {
81 protected:
82     DataUtils(void) = default;
83     static bool MatchBytes(const uint8_t *aFirstBuffer,
84                            const uint8_t *aSecondBuffer,
85                            uint16_t       aLength,
86                            ByteMatcher    aMatcher);
87 };
88 
89 template <DataLengthType kDataLengthType> class MutableData;
90 
91 /**
92  * Represents a generic `Data` which is simply a wrapper over a pointer to a buffer with a given data length.
93  *
94  * The data length can be either `uint8_t` or `uint16_t` (determined by the template parameter `kDataLengthType`).
95  *
96  * While a `Data` instance itself can change (for example, it can be updated to point to another buffer), it always
97  * treats the content of the buffer as immutable.
98  *
99  * A `Data` instance MUST be initialized (using any of the `Init()` methods) before calling any other methods on the
100  * instance (e.g., `GetBytes()` or `GetLength()`), otherwise the behavior is undefined.
101  *
102  * @tparam kDataLengthType   Determines the data length type (`uint8_t` or `uint16_t`).
103  */
104 template <DataLengthType kDataLengthType>
105 class Data : public Clearable<Data<kDataLengthType>>, public Unequatable<Data<kDataLengthType>>, private DataUtils
106 {
107     friend class MutableData<kDataLengthType>;
108 
109 public:
110     /**
111      * Represents the data length type (`uint8_t` or `uint16_t`).
112      */
113     using LengthType = typename TypeTraits::Conditional<kDataLengthType == kWithUint8Length, uint8_t, uint16_t>::Type;
114 
115     /**
116      * Initializes the `Data` to point to a given buffer with a given length.
117      *
118      * @param[in] aBuffer   A pointer to a buffer containing the data.
119      * @param[in] aLength   The data length (number of bytes in @p aBuffer)
120      */
Init(const void * aBuffer,LengthType aLength)121     void Init(const void *aBuffer, LengthType aLength)
122     {
123         mBuffer = static_cast<const uint8_t *>(aBuffer);
124         mLength = aLength;
125     }
126 
127     /**
128      * Initializes the `Data` to point to a range of bytes in a given buffer.
129      *
130      * The range is specified by the pointers to its start @p aStart and its end @p aEnd. `Data` will point to the
131      * bytes in the buffer from @p aStart up to but excluding @p aEnd (i.e., `aStart <= bytes < aEnd`).
132      *
133      * @param[in] aStart  Pointer to the start of the range.
134      * @param[in] aEnd    Pointer to the end of the range.
135      */
InitFromRange(const uint8_t * aStart,const uint8_t * aEnd)136     void InitFromRange(const uint8_t *aStart, const uint8_t *aEnd)
137     {
138         Init(aStart, static_cast<LengthType>(aEnd - aStart));
139     }
140 
141     /**
142      * Initializes the `Data` to point to the content of an object.
143      *
144      * @tparm ObjectType   The object type (MUST not be a pointer type).
145      *
146      * @param[in] aObject   The object to initialize the `Data` with.
147      */
InitFrom(const ObjectType & aObject)148     template <typename ObjectType> void InitFrom(const ObjectType &aObject)
149     {
150         static_assert(!TypeTraits::IsPointer<ObjectType>::kValue, "ObjectType MUST not be a pointer");
151         Init(&aObject, sizeof(aObject));
152     }
153 
154     /**
155      * Returns a pointer to the data bytes buffer.
156      *
157      * @returns A pointer to the data bytes buffer (can be `nullptr` if `Data` is cleared).
158      */
GetBytes(void) const159     const uint8_t *GetBytes(void) const { return mBuffer; }
160 
161     /**
162      * Returns the data length.
163      *
164      * @returns The data length (number of bytes).
165      */
GetLength(void) const166     LengthType GetLength(void) const { return mLength; }
167 
168     /**
169      * Sets the data length.
170      *
171      * @param[in] aLength   The data length (number of bytes).
172      */
SetLength(LengthType aLength)173     void SetLength(LengthType aLength) { mLength = aLength; }
174 
175     /**
176      * Copies the `Data` bytes to a given buffer.
177      *
178      * It is up to the caller to ensure that @p aBuffer has enough space for the current data length.
179      *
180      * @param[out] aBuffer  The buffer to copy the bytes into.
181      */
CopyBytesTo(void * aBuffer) const182     void CopyBytesTo(void *aBuffer) const { memcpy(aBuffer, mBuffer, mLength); }
183 
184     /**
185      * Compares the `Data` content with the bytes from a given buffer.
186      *
187      * It is up to the caller to ensure that @p aBuffer has enough bytes to compare with the current data length.
188      *
189      * @param[in] aBuffer   A pointer to a buffer to compare with the data.
190      *
191      * @retval TRUE   The `Data` content matches the bytes in @p aBuffer.
192      * @retval FALSE  The `Data` content does not match the byes in @p aBuffer.
193      */
MatchesBytesIn(const void * aBuffer) const194     bool MatchesBytesIn(const void *aBuffer) const { return memcmp(mBuffer, aBuffer, mLength) == 0; }
195 
196     /**
197      * Compares the `Data` content with the bytes from a given buffer using a given `Matcher` function.
198      *
199      * It is up to the caller to ensure that @p aBuffer has enough bytes to compare with the current data length.
200      *
201      * @param[in] aBuffer   A pointer to a buffer to compare with the data.
202      * @param[in] aMatcher  A `ByteMatcher` function to match the bytes. If `nullptr`, bytes are compared directly.
203      *
204      * @retval TRUE   The `Data` content matches the bytes in @p aBuffer.
205      * @retval FALSE  The `Data` content does not match the byes in @p aBuffer.
206      */
MatchesBytesIn(const void * aBuffer,ByteMatcher aMatcher)207     bool MatchesBytesIn(const void *aBuffer, ByteMatcher aMatcher)
208     {
209         return MatchBytes(mBuffer, static_cast<const uint8_t *>(aBuffer), mLength, aMatcher);
210     }
211 
212     /**
213      * Overloads operator `==` to compare the `Data` content with the content from another one.
214      *
215      * @param[in] aOtherData   The other `Data` to compare with.
216      *
217      * @retval TRUE   The two `Data` instances have matching content (same length and same bytes).
218      * @retval FALSE  The two `Data` instances do not have matching content.
219      */
operator ==(const Data & aOtherData) const220     bool operator==(const Data &aOtherData) const
221     {
222         return (mLength == aOtherData.mLength) && MatchesBytesIn(aOtherData.mBuffer);
223     }
224 
225     /**
226      * Checks whether the `Data` starts with the same byte content as from another `Data` instance.
227      *
228      * Checks that the `Data` instance contains the same bytes as @p aOtherData but allows it to have
229      * additional bytes at the end.
230      *
231      * @param[in] aOtherData  The other `Data` to compare with.
232      *
233      * @retval TRUE   This `Data` starts with the same byte content as in @p aOtherData.
234      * @retval FALSE  This `Data` does not start with the same byte content as in @p aOtherData.
235      */
StartsWith(const Data & aOtherData) const236     bool StartsWith(const Data &aOtherData) const
237     {
238         return (mLength >= aOtherData.mLength) && aOtherData.MatchesBytesIn(mBuffer);
239     }
240 
241 private:
242     const uint8_t *mBuffer;
243     LengthType     mLength;
244 };
245 
246 /**
247  * Represents a generic `MutableData` which is simply a wrapper over a pointer to a buffer with a given data
248  * length.
249  *
250  * It inherits from `Data` but unlike `Data` which treats its buffer content as immutable, `MutableData` allows its
251  * data buffer content to be changed.
252  *
253  * A `MutableData` instance MUST be initialized (using any of the `Init()` methods) before calling any other methods
254  * (e.g., `GetBytes()` or `GetLength()`), otherwise the behavior is undefined.
255 
256  */
257 template <DataLengthType kDataLengthType> class MutableData : public Data<kDataLengthType>
258 {
259     using Base = Data<kDataLengthType>;
260     using Base::mBuffer;
261     using Base::mLength;
262 
263 public:
264     /**
265      * Represents the data length type (`uint8_t` or `uint16_t`).
266      */
267     using LengthType = typename Base::LengthType;
268 
269     /**
270      * Initializes the `MutableData` to point to a given buffer with a given length.
271      *
272      * @param[in] aBuffer   A pointer to a buffer containing the data.
273      * @param[in] aLength   The data length (number of bytes in @p aBuffer)
274      */
Init(void * aBuffer,LengthType aLength)275     void Init(void *aBuffer, LengthType aLength) { Base::Init(aBuffer, aLength); }
276 
277     /**
278      * Initializes the `MutableData` to point to a range of bytes in a given buffer.
279      *
280      * The range is specified by the pointers to its start @p aStart and its end @p aEnd. `Data` will point to the
281      * bytes in the buffer from @p aStart up to but excluding @p aEnd (i.e., `aStart <= bytes < aEnd`).
282      *
283      * @param[in] aStart  Pointer to the start of the range.
284      * @param[in] aEnd    Pointer to the end of the range.
285      */
InitFormRange(uint8_t * aStart,uint8_t * aEnd)286     void InitFormRange(uint8_t *aStart, uint8_t *aEnd) { Base::InitFormRange(aStart, aEnd); }
287 
288     /**
289      * Initializes the `MutableData` to point to the content of an object.
290      *
291      * @tparm ObjectType   The object type (MUST not be a pointer type).
292      *
293      * @param[in] aObject   The object to initialize the `MutableData` with.
294      */
InitFrom(ObjectType & aObject)295     template <typename ObjectType> void InitFrom(ObjectType &aObject)
296     {
297         static_assert(!TypeTraits::IsPointer<ObjectType>::kValue, "ObjectType MUST not be a pointer");
298         Init(&aObject, sizeof(aObject));
299     }
300 
301     /**
302      * Returns a pointer to the data bytes buffer.
303      *
304      * @returns A pointer to the data bytes buffer (can be `nullptr` if `Data` is empty or uninitialized).
305      */
GetBytes(void)306     uint8_t *GetBytes(void) { return AsNonConst(Base::GetBytes()); }
307 
308     /**
309      * Returns a pointer to the data bytes buffer.
310      *
311      * @returns A pointer to the data bytes buffer (can be `nullptr` if `Data` is empty or uninitialized).
312      */
GetBytes(void) const313     const uint8_t *GetBytes(void) const { return Base::GetBytes(); }
314 
315     /**
316      * Clears all the bytes (sets them to zero) in the buffer pointed by the `MutableData`.
317      */
ClearBytes(void)318     void ClearBytes(void) { memset(GetBytes(), 0, mLength); }
319 
320     /**
321      * Copies the bytes from a given buffer into the `MutableData` buffer.
322      *
323      * If the current `MutableData` length is larger than or equal to @p aLength, then all the bytes are copied
324      * from @p aBuffer into the buffer of `MutableData` and the `MutableData`'s length is changed to @p aLength.
325      *
326      * If the current `MutableData` length is smaller than @p aLength, then the method returns `kErrorNoBufs` but still
327      * copies as many bytes as can fit.
328      *
329      * @param[in] aBuffer  A pointer to a buffer to copy from.
330      * @param[in] aLength  The length of @p aBuffer (number of bytes).
331      *
332      * @retval kErrorNone    Successfully copied the bytes into `MutableData` buffer and adjusted its length.
333      * @retval kErrorNoBufs  `MutableData` buffer cannot fit the given @p aLength bytes.
334      */
CopyBytesFrom(const uint8_t * aBuffer,LengthType aLength)335     Error CopyBytesFrom(const uint8_t *aBuffer, LengthType aLength)
336     {
337         Error error = (mLength >= aLength) ? kErrorNone : kErrorNoBufs;
338 
339         mLength = Min(mLength, aLength);
340         memcpy(AsNonConst(mBuffer), aBuffer, mLength);
341 
342         return error;
343     }
344 
345     /**
346      * Copies the bytes from an given `Data` instance into the `MutableData` buffer.
347      *
348      * If the current `MutableData` length is larger than or equal to the @p aData length, then all the bytes are copied
349      * from @p aData into the buffer of `MutableData` and the `MutableData`'s length is adjusted accordingly.
350      *
351      * If the current `MutableData` length is smaller than @p aData length, then as many bytes as can fit are copied
352      * and the method returns `kErrorNoBufs`.
353      *
354      * @param[in] aData      A `Data` instance to copy the content from.
355      *
356      * @retval kErrorNone    Successfully copied the bytes into `MutableData` buffer and adjusted its length.
357      * @retval kErrorNoBufs  `MutableData` buffer cannot fit the given @p aData bytes.
358      */
CopyBytesFrom(const Data<kDataLengthType> & aData)359     Error CopyBytesFrom(const Data<kDataLengthType> &aData)
360     {
361         return CopyBytesFrom(aData.GetBytes(), aData.GetLength());
362     }
363 };
364 
365 } // namespace ot
366 
367 #endif // DATA_HPP_
368