blob: aa245070299a6dcfb1a06160a8f250d8e2b94648 [file] [log] [blame]
Michael Eckel5c531332020-03-02 01:35:30 +01001/*============================================================================
2 Copyright (c) 2016-2018, The Linux Foundation.
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06003 Copyright (c) 2018-2022, Laurence Lundblade.
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02004 Copyright (c) 2021, Arm Limited. All rights reserved.
Michael Eckel5c531332020-03-02 01:35:30 +01005
6Redistribution and use in source and binary forms, with or without
7modification, are permitted provided that the following conditions are
8met:
9 * Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 * Redistributions in binary form must reproduce the above
12 copyright notice, this list of conditions and the following
13 disclaimer in the documentation and/or other materials provided
14 with the distribution.
15 * Neither the name of The Linux Foundation nor the names of its
16 contributors, nor the name "Laurence Lundblade" may be used to
17 endorse or promote products derived from this software without
18 specific prior written permission.
19
20THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
21WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
23ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
24BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
30IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 =============================================================================*/
32
33/*============================================================================
34 FILE: UsefulBuf.h
35
36 DESCRIPTION: General purpose input and output buffers
37
38 EDIT HISTORY FOR FILE:
39
40 This section contains comments describing changes made to the module.
41 Notice that changes are listed in reverse chronological order.
42
43 when who what, where, why
44 -------- ---- --------------------------------------------------
Laurence Lundblade5a6fec52022-12-25 11:28:43 -070045 19/12/2022 llundblade Document that adding empty data is allowed.
Laurence Lundbladeb24faef2022-04-26 11:03:08 -060046 4/11/2022 llundblade Add GetOutPlace and Advance to UsefulOutBuf.
Laurence Lundblade8ece3732021-09-21 21:47:23 -070047 9/21/2021 llundbla Clarify UsefulOutBuf size calculation mode
Laurence Lundblade48d8ace2021-08-19 22:00:26 -070048 8/8/2021 dthaler/llundbla Work with C++ without compiler extensions
Laurence Lundbladedabaffe2021-05-11 10:47:46 -070049 5/11/2021 llundblade Improve comments and comment formatting.
Laurence Lundbladeb9702452021-03-08 21:02:57 -080050 3/6/2021 mcr/llundblade Fix warnings related to --Wcast-qual
Laurence Lundbladecf41c522021-02-20 10:19:07 -070051 2/17/2021 llundblade Add method to go from a pointer to an offset.
Michael Eckel5c531332020-03-02 01:35:30 +010052 1/25/2020 llundblade Add some casts so static anlyzers don't complain.
53 5/21/2019 llundblade #define configs for efficient endianness handling.
54 5/16/2019 llundblade Add UsefulOutBuf_IsBufferNULL().
55 3/23/2019 llundblade Big documentation & style update. No interface
56 change.
57 3/6/2019 llundblade Add UsefulBuf_IsValue()
58 12/17/2018 llundblade Remove const from UsefulBuf and UsefulBufC .len
59 12/13/2018 llundblade Documentation improvements
60 09/18/2018 llundblade Cleaner distinction between UsefulBuf and
61 UsefulBufC.
62 02/02/18 llundbla Full support for integers in and out; fix pointer
63 alignment bug. Incompatible change: integers
64 in/out are now in network byte order.
65 08/12/17 llundbla Added UsefulOutBuf_AtStart and UsefulBuf_Find
66 06/27/17 llundbla Fix UsefulBuf_Compare() bug. Only affected
67 comparison for < or > for unequal length buffers.
68 Added UsefulBuf_Set() function.
69 05/30/17 llundbla Functions for NULL UsefulBufs and const / unconst
70 11/13/16 llundbla Initial Version.
71
72 =============================================================================*/
73
74#ifndef _UsefulBuf_h
75#define _UsefulBuf_h
76
77
78/*
Laurence Lundbladedabaffe2021-05-11 10:47:46 -070079 * Endianness Configuration
80 *
81 * This code is written so it will work correctly on big- and
82 * little-endian CPUs without configuration or any auto-detection of
83 * endianness. All code here will run correctly regardless of the
84 * endianness of the CPU it is running on.
85 *
86 * There are four C preprocessor macros that can be set with #define
87 * to explicitly configure endianness handling. Setting them can
88 * reduce code size a little and improve efficiency a little.
89 *
90 * Note that most of QCBOR is unaffected by this configuration. Its
91 * endianness handling is integrated with the code that handles
92 * alignment and preferred serialization. This configuration does
93 * affect QCBOR's (planned) implementation of integer arrays (tagged
94 * arrays) and use of the functions here to serialize or deserialize
95 * integers and floating-point values.
96 *
97 * Following is the recipe for configuring the endianness-related
98 * #defines.
99 *
100 * The first option is to not define anything. This will work fine
101 * with all CPUs, OS's and compilers. The code for encoding integers
102 * may be a little larger and slower.
103 *
104 * If your CPU is big-endian then define
105 * USEFULBUF_CONFIG_BIG_ENDIAN. This will give the most efficient code
106 * for big-endian CPUs. It will be small and efficient because there
107 * will be no byte swapping.
108 *
109 * Try defining USEFULBUF_CONFIG_HTON. This will work on most CPUs,
110 * OS's and compilers, but not all. On big-endian CPUs this should
111 * give the most efficient code, the same as
112 * USEFULBUF_CONFIG_BIG_ENDIAN does. On little-endian CPUs it should
113 * call the system-defined byte swapping method which is presumably
114 * implemented efficiently. In some cases, this will be a dedicated
115 * byte swap instruction like Intel's bswap.
116 *
117 * If USEFULBUF_CONFIG_HTON works and you know your CPU is
118 * little-endian, it is also good to define
119 * USEFULBUF_CONFIG_LITTLE_ENDIAN.
120 *
121 * if USEFULBUF_CONFIG_HTON doesn't work and you know your system is
122 * little-endian, try defining both USEFULBUF_CONFIG_LITTLE_ENDIAN and
123 * USEFULBUF_CONFIG_BSWAP. This should call the most efficient
124 * system-defined byte swap method. However, note
125 * https://hardwarebug.org/2010/01/14/beware-the-builtins/. Perhaps
126 * this is fixed now. Often hton() and ntoh() will call the built-in
127 * __builtin_bswapXX()() function, so this size issue could affect
128 * USEFULBUF_CONFIG_HTON.
129 *
130 * Last, run the tests. They must all pass.
131 *
132 * These #define config options affect the inline implementation of
133 * UsefulOutBuf_InsertUint64() and UsefulInputBuf_GetUint64(). They
134 * also affect the 16-, 32-bit, float and double versions of these
135 * functions. Since they are inline, the size effect is not in the
136 * UsefulBuf object code, but in the calling code.
137 *
138 * Summary:
139 * USEFULBUF_CONFIG_BIG_ENDIAN -- Force configuration to big-endian.
140 * USEFULBUF_CONFIG_LITTLE_ENDIAN -- Force to little-endian.
141 * USEFULBUF_CONFIG_HTON -- Use hton(), htonl(), ntohl()... to
142 * handle big and little-endian with system option.
143 * USEFULBUF_CONFIG_BSWAP -- With USEFULBUF_CONFIG_LITTLE_ENDIAN,
144 * use __builtin_bswapXX().
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200145 *
146 * It is possible to run this code in environments where using floating point is
147 * not allowed. Defining USEFULBUF_DISABLE_ALL_FLOAT will disable all the code
148 * that is related to handling floating point types, along with related
149 * interfaces. This makes it possible to compile the code with the compile
150 * option -mgeneral-regs-only.
Michael Eckel5c531332020-03-02 01:35:30 +0100151 */
152
153#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) && defined(USEFULBUF_CONFIG_LITTLE_ENDIAN)
154#error "Cannot define both USEFULBUF_CONFIG_BIG_ENDIAN and USEFULBUF_CONFIG_LITTLE_ENDIAN"
155#endif
156
157
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700158#include <stdint.h> /* for uint8_t, uint16_t.... */
159#include <string.h> /* for strlen, memcpy, memmove, memset */
160#include <stddef.h> /* for size_t */
Michael Eckel5c531332020-03-02 01:35:30 +0100161
162
163#ifdef USEFULBUF_CONFIG_HTON
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700164#include <arpa/inet.h> /* for htons, htonl, htonll, ntohs... */
Michael Eckel5c531332020-03-02 01:35:30 +0100165#endif
166
167#ifdef __cplusplus
168extern "C" {
Laurence Lundblade24d509a2020-06-06 18:43:15 -0700169#if 0
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700170} /* Keep editor indention formatting happy */
Laurence Lundblade24d509a2020-06-06 18:43:15 -0700171#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100172#endif
173
174/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700175 * @file UsefulBuf.h
176 *
177 * The goal of this code is to make buffer and pointer manipulation
178 * easier and safer when working with binary data.
179 *
180 * The @ref UsefulBuf, @ref UsefulOutBuf and @ref UsefulInputBuf
181 * structures are used to represent buffers rather than ad hoc
182 * pointers and lengths.
183 *
184 * With these it is possible to write code that does little or no
185 * direct pointer manipulation for copying and formatting data. For
186 * example, the QCBOR encoder was written using these and has less
187 * pointer manipulation.
188 *
189 * While it is true that object code using these functions will be a
190 * little larger and slower than a white-knuckle clever use of
191 * pointers might be, but not by that much or enough to have an effect
192 * for most use cases. For security-oriented code this is highly
193 * worthwhile. Clarity, simplicity, reviewability and are more
194 * important.
195 *
196 * There are some extra sanity and double checks in this code to help
197 * catch coding errors and simple memory corruption. They are helpful,
198 * but not a substitute for proper code review, input validation and
199 * such.
200 *
201 * This code consists of a lot of inline functions and a few that are
202 * not. It should not generate very much object code, especially with
203 * the optimizer turned up to @c -Os or @c -O3.
Michael Eckel5c531332020-03-02 01:35:30 +0100204 */
205
206
207/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700208 * @ref UsefulBufC and @ref UsefulBuf are simple data structures to
209 * hold a pointer and length for binary data. In C99 this data
210 * structure can be passed on the stack making a lot of code cleaner
211 * than carrying around a pointer and length as two parameters.
212 *
213 * This is also conducive to secure coding practice as the length is
214 * always carried with the pointer and the convention for handling a
215 * pointer and a length is clear.
216 *
217 * While it might be possible to write buffer and pointer code more
218 * efficiently in some use cases, the thought is that unless there is
219 * an extreme need for performance (e.g., you are building a
220 * gigabit-per-second IP router), it is probably better to have
221 * cleaner code you can be most certain about the security of.
222 *
223 * The non-const @ref UsefulBuf is usually used to refer an empty
224 * buffer to be filled in. The length is the size of the buffer.
225 *
226 * The const @ref UsefulBufC is usually used to refer to some data
227 * that has been filled in. The length is amount of valid data pointed
228 * to.
229 *
230 * A common use mode is to pass a @ref UsefulBuf to a function, the
231 * function puts some data in it, then the function returns a @ref
232 * UsefulBufC refering to the data. The @ref UsefulBuf is a non-const
233 * "in" parameter and the @ref UsefulBufC is a const "out" parameter
234 * so the constness stays correct. There is no single "in,out"
235 * parameter (if there was, it would have to be non-const). Note that
236 * the pointer returned in the @ref UsefulBufC usually ends up being
237 * the same pointer passed in as a @ref UsefulBuf, though this is not
238 * striclty required.
239 *
240 * A @ref UsefulBuf is null, it has no value, when @c ptr in it is
241 * @c NULL.
242 *
243 * There are functions and macros for the following:
244 * - Initializing
245 * - Create initialized const @ref UsefulBufC from compiler literals
246 * - Create initialized const @ref UsefulBufC from NULL-terminated string
247 * - Make an empty @ref UsefulBuf on the stack
248 * - Checking whether a @ref UsefulBuf is null, empty or both
249 * - Copying, copying with offset, copying head or tail
250 * - Comparing and finding substrings
251 *
252 * See also @ref UsefulOutBuf. It is a richer structure that has both
253 * the size of the valid data and the size of the buffer.
254 *
255 * @ref UsefulBuf is only 16 or 8 bytes on a 64- or 32-bit machine so
256 * it can go on the stack and be a function parameter or return value.
257 *
258 * Another way to look at it is this. C has the NULL-terminated string
259 * as a means for handling text strings, but no means or convention
260 * for binary strings. Other languages do have such means, Rust, an
261 * efficient compiled language, for example.
262 *
263 * @ref UsefulBuf is kind of like the Useful Pot Pooh gave Eeyore on
264 * his birthday. Eeyore's balloon fits beautifully, "it goes in and
265 * out like anything".
266 */
Michael Eckel5c531332020-03-02 01:35:30 +0100267typedef struct q_useful_buf_c {
268 const void *ptr;
269 size_t len;
270} UsefulBufC;
271
272
273/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700274 * This non-const @ref UsefulBuf is typically used for some allocated
275 * memory that is to be filled in. The @c len is the amount of memory,
276 * not the length of the valid data in the buffer.
Michael Eckel5c531332020-03-02 01:35:30 +0100277 */
278typedef struct q_useful_buf {
279 void *ptr;
280 size_t len;
281} UsefulBuf;
282
283
284/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700285 * A null @ref UsefulBufC is one that has no value in the same way a
286 * @c NULL pointer has no value. A @ref UsefulBufC is @c NULL when
287 * the @c ptr field is @c NULL. It doesn't matter what @c len is. See
288 * UsefulBuf_IsEmpty() for the distinction between null and empty.
Michael Eckel5c531332020-03-02 01:35:30 +0100289 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700290/*
291 * NULLUsefulBufC and few other macros have to be
292 * definied differently in C than C++ because there
293 * is no common construct for a literal structure.
294 *
295 * In C compound literals are used.
296 *
297 * In C++ list initalization is used. This only works
298 * in C++11 and later.
299 *
300 * Note that some popular C++ compilers can handle compound
301 * literals with on-by-default extensions, however
302 * this code aims for full correctness with strict
303 * compilers so they are not used.
304 */
305#ifdef __cplusplus
306#define NULLUsefulBufC {NULL, 0}
307#else
308#define NULLUsefulBufC ((UsefulBufC) {NULL, 0})
309#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100310
311/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700312 * A null @ref UsefulBuf is one that has no memory associated the same
313 * way @c NULL points to nothing. It does not matter what @c len is.
314 **/
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700315#ifdef __cplusplus
316#define NULLUsefulBuf {NULL, 0}
317#else
318#define NULLUsefulBuf ((UsefulBuf) {NULL, 0})
319#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100320
321
322/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700323 * @brief Check if a @ref UsefulBuf is @ref NULLUsefulBuf or not.
324 *
325 * @param[in] UB The UsefulBuf to check.
326 *
327 * @return 1 if it is @ref NULLUsefulBuf, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100328 */
329static inline int UsefulBuf_IsNULL(UsefulBuf UB);
330
331
332/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700333 * @brief Check if a @ref UsefulBufC is @ref NULLUsefulBufC or not.
334 *
335 * @param[in] UB The @ref UsefulBufC to check.
336 *
337 * @return 1 if it is @c NULLUsefulBufC, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100338 */
339static inline int UsefulBuf_IsNULLC(UsefulBufC UB);
340
341
342/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700343 * @brief Check if a @ref UsefulBuf is empty or not.
344 *
345 * @param[in] UB The @ref UsefulBuf to check.
346 *
347 * @return 1 if it is empty, 0 if not.
348 *
349 * An "empty" @ref UsefulBuf is one that has a value and can be
350 * considered to be set, but that value is of zero length. It is
351 * empty when @c len is zero. It doesn't matter what the @c ptr is.
352 *
353 * Many uses will not need to clearly distinguish a @c NULL @ref
354 * UsefulBuf from an empty one and can have the @c ptr @c NULL and the
355 * @c len 0. However if a use of @ref UsefulBuf needs to make a
356 * distinction then @c ptr should not be @c NULL when the @ref
357 * UsefulBuf is considered empty, but not @c NULL.
Michael Eckel5c531332020-03-02 01:35:30 +0100358 */
359static inline int UsefulBuf_IsEmpty(UsefulBuf UB);
360
361
362/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700363 * @brief Check if a @ref UsefulBufC is empty or not.
364 *
365 * @param[in] UB The @ref UsefulBufC to check.
366 *
367 * @return 1 if it is empty, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100368 */
369static inline int UsefulBuf_IsEmptyC(UsefulBufC UB);
370
371
372/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700373 * @brief Check if a @ref UsefulBuf is @ref NULLUsefulBuf or empty.
374 *
375 * @param[in] UB The @ref UsefulBuf to check.
376 *
377 * @return 1 if it is either @ref NULLUsefulBuf or empty, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100378 */
379static inline int UsefulBuf_IsNULLOrEmpty(UsefulBuf UB);
380
381
382/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700383 * @brief Check if a @ref UsefulBufC is @ref NULLUsefulBufC or empty.
384 *
385 * @param[in] UB The @ref UsefulBufC to check.
386 *
387 * @return 1 if it is either @ref NULLUsefulBufC or empty, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100388 */
389static inline int UsefulBuf_IsNULLOrEmptyC(UsefulBufC UB);
390
391
392/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700393 * @brief Convert a non-const @ref UsefulBuf to a const @ref UsefulBufC.
394 *
395 * @param[in] UB The @ref UsefulBuf to convert.
396 *
397 * @return A @ref UsefulBufC struct.
Michael Eckel5c531332020-03-02 01:35:30 +0100398 */
399static inline UsefulBufC UsefulBuf_Const(const UsefulBuf UB);
400
401
402/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700403 * @brief Convert a const @ref UsefulBufC to a non-const @ref UsefulBuf.
404 *
405 * @param[in] UBC The @ref UsefulBuf to convert.
406 *
407 * @return A non-const @ref UsefulBuf struct.
408 *
409 * Use of this is not necessary for the intended use mode of @ref
410 * UsefulBufC and @ref UsefulBuf. In that mode, the @ref UsefulBuf is
411 * created to describe a buffer that has not had any data put in
412 * it. Then the data is put in it. Then a @ref UsefulBufC is create
413 * to describe the part with the data in it. This goes from non-const
414 * to const, so this function is not needed.
415 *
416 * If the -Wcast-qual warning is enabled, this function can be used to
417 * avoid that warning.
Michael Eckel5c531332020-03-02 01:35:30 +0100418 */
419static inline UsefulBuf UsefulBuf_Unconst(const UsefulBufC UBC);
420
421
422/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700423 * Convert a literal string to a @ref UsefulBufC.
424 *
425 * @c szString must be a literal string that @c sizeof() works on.
426 * This is better for literal strings than UsefulBuf_FromSZ() because
427 * it generates less code. It will not work on non-literal strings.
428 *
429 * The terminating \0 (NULL) is NOT included in the length!
Michael Eckel5c531332020-03-02 01:35:30 +0100430 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700431#ifdef __cplusplus
432#define UsefulBuf_FROM_SZ_LITERAL(szString) {(szString), sizeof(szString)-1}
433#else
Michael Eckel5c531332020-03-02 01:35:30 +0100434#define UsefulBuf_FROM_SZ_LITERAL(szString) \
435 ((UsefulBufC) {(szString), sizeof(szString)-1})
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700436#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100437
438
439/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700440 * Convert a literal byte array to a @ref UsefulBufC.
441 *
442 * @c pBytes must be a literal string that @c sizeof() works on. It
443 * will not work on non-literal arrays.
Michael Eckel5c531332020-03-02 01:35:30 +0100444 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700445#ifdef __cplusplus
446#define UsefulBuf_FROM_BYTE_ARRAY_LITERAL(pBytes) {(pBytes), sizeof(pBytes)}
447#else
Michael Eckel5c531332020-03-02 01:35:30 +0100448#define UsefulBuf_FROM_BYTE_ARRAY_LITERAL(pBytes) \
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700449 ((UsefulBufC) {(pBytes), sizeof(pBytes)})
450#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100451
452/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700453 * Make an automatic variable named @c name of type @ref UsefulBuf and
454 * point it to a stack variable of the given @c size.
Michael Eckel5c531332020-03-02 01:35:30 +0100455 */
456#define UsefulBuf_MAKE_STACK_UB(name, size) \
457 uint8_t __pBuf##name[(size)];\
458 UsefulBuf name = {__pBuf##name , sizeof( __pBuf##name )}
459
460
461/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700462 * Make a byte array in to a @ref UsefulBuf. This is usually used on
463 * stack variables or static variables. Also see @ref
464 * UsefulBuf_MAKE_STACK_UB.
Michael Eckel5c531332020-03-02 01:35:30 +0100465 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700466#ifdef __cplusplus
467#define UsefulBuf_FROM_BYTE_ARRAY(pBytes) {(pBytes), sizeof(pBytes)}
468#else
Michael Eckel5c531332020-03-02 01:35:30 +0100469#define UsefulBuf_FROM_BYTE_ARRAY(pBytes) \
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700470 ((UsefulBuf) {(pBytes), sizeof(pBytes)})
471#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100472
473
474/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700475 * @brief Convert a NULL-terminated string to a @ref UsefulBufC.
476 *
477 * @param[in] szString The string to convert.
478 *
479 * @return A @ref UsefulBufC struct.
480 *
481 * @c UsefulBufC.ptr points to the string so its lifetime must be
482 * maintained.
483 *
484 * The terminating \0 (NULL) is NOT included in the length.
Michael Eckel5c531332020-03-02 01:35:30 +0100485 */
486static inline UsefulBufC UsefulBuf_FromSZ(const char *szString);
487
488
489/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700490 * @brief Copy one @ref UsefulBuf into another at an offset.
491 *
492 * @param[in] Dest Destination buffer to copy into.
493 * @param[in] uOffset The byte offset in @c Dest at which to copy to.
494 * @param[in] Src The bytes to copy.
495 *
496 * @return Pointer and length of the copy or @ref NULLUsefulBufC.
497 *
498 * This fails and returns @ref NULLUsefulBufC if @c offset is beyond the
499 * size of @c Dest.
500 *
501 * This fails and returns @ref NULLUsefulBufC if the @c Src length
502 * plus @c uOffset is greater than the length of @c Dest.
503 *
504 * The results are undefined if @c Dest and @c Src overlap.
505 *
506 * This assumes that there is valid data in @c Dest up to @c
507 * uOffset. The @ref UsefulBufC returned starts at the beginning of @c
508 * Dest and goes to @c Src.len @c + @c uOffset.
Michael Eckel5c531332020-03-02 01:35:30 +0100509 */
510UsefulBufC UsefulBuf_CopyOffset(UsefulBuf Dest, size_t uOffset, const UsefulBufC Src);
511
512
513/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700514 * @brief Copy one @ref UsefulBuf into another.
515 *
516 * @param[in] Dest The destination buffer to copy into.
517 * @param[out] Src The source to copy from.
518 *
519 * @return Filled in @ref UsefulBufC on success, @ref NULLUsefulBufC
520 * on failure.
521 *
522 * This fails if @c Src.len is greater than @c Dest.len.
523 *
524 * Note that like @c memcpy(), the pointers are not checked and this
525 * will crash rather than return @ref NULLUsefulBufC if they are @c
526 * NULL or invalid.
527 *
528 * The results are undefined if @c Dest and @c Src overlap.
Michael Eckel5c531332020-03-02 01:35:30 +0100529 */
530static inline UsefulBufC UsefulBuf_Copy(UsefulBuf Dest, const UsefulBufC Src);
531
532
533/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700534 * @brief Set all bytes in a @ref UsefulBuf to a value, for example to 0.
535 *
536 * @param[in] pDest The destination buffer to copy into.
537 * @param[in] value The value to set the bytes to.
538 *
539 * Note that like @c memset(), the pointer in @c pDest is not checked
540 * and this will crash if @c NULL or invalid.
Michael Eckel5c531332020-03-02 01:35:30 +0100541 */
542static inline UsefulBufC UsefulBuf_Set(UsefulBuf pDest, uint8_t value);
543
544
545/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700546 * @brief Copy a pointer into a @ref UsefulBuf.
547 *
548 * @param[in,out] Dest The destination buffer to copy into.
549 * @param[in] ptr The source to copy from.
550 * @param[in] uLen Length of the source; amount to copy.
551 *
552 * @return Filled in @ref UsefulBufC on success, @ref NULLUsefulBufC
553 * on failure.
554 *
555 * This fails and returns @ref NULLUsefulBufC if @c uLen is greater
556 * than @c pDest->len.
557 *
558 * Note that like @c memcpy(), the pointers are not checked and this
559 * will crash, rather than return 1 if they are @c NULL or invalid.
Michael Eckel5c531332020-03-02 01:35:30 +0100560 */
561static inline UsefulBufC UsefulBuf_CopyPtr(UsefulBuf Dest,
562 const void *ptr,
563 size_t uLen);
564
565
566/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700567 * @brief Returns a truncation of a @ref UsefulBufC.
568 *
569 * @param[in] UB The buffer to get the head of.
570 * @param[in] uAmount The number of bytes in the head.
571 *
572 * @return A @ref UsefulBufC that is the head of UB.
Michael Eckel5c531332020-03-02 01:35:30 +0100573 */
574static inline UsefulBufC UsefulBuf_Head(UsefulBufC UB, size_t uAmount);
575
576
577/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700578 * @brief Returns bytes from the end of a @ref UsefulBufC.
579 *
580 * @param[in] UB The buffer to get the tail of.
581 * @param[in] uAmount The offset from the start where the tail is to begin.
582 *
583 * @return A @ref UsefulBufC that is the tail of @c UB or @ref NULLUsefulBufC
584 * if @c uAmount is greater than the length of the @ref UsefulBufC.
585 *
586 * If @c UB.ptr is @c NULL, but @c UB.len is not zero, then the result will
587 * be a @ref UsefulBufC with a @c NULL @c ptr and @c len with the length
588 * of the tail.
Michael Eckel5c531332020-03-02 01:35:30 +0100589 */
590static inline UsefulBufC UsefulBuf_Tail(UsefulBufC UB, size_t uAmount);
591
592
593/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700594 * @brief Compare one @ref UsefulBufC to another.
595 *
596 * @param[in] UB1 The first buffer to compare.
597 * @param[in] UB2 The second buffer to compare.
598 *
599 * @return 0, positive or negative value.
600 *
601 * Returns a negative value if @c UB1 if is less than @c UB2. @c UB1 is
602 * less than @c UB2 if it is shorter or the first byte that is not the
603 * same is less.
604 *
605 * Returns 0 if the inputs are the same.
606 *
607 * Returns a positive value if @c UB2 is less than @c UB1.
608 *
609 * All that is of significance is that the result is positive, negative
610 * or 0. (This doesn't return the difference between the first
611 * non-matching byte like @c memcmp() ).
Michael Eckel5c531332020-03-02 01:35:30 +0100612 */
613int UsefulBuf_Compare(const UsefulBufC UB1, const UsefulBufC UB2);
614
615
616/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700617 * @brief Find first byte that is not a particular byte value.
618 *
619 * @param[in] UB The destination buffer for byte comparison.
620 * @param[in] uValue The byte value to compare to.
621 *
622 * @return Offset of first byte that isn't @c uValue or
623 * @c SIZE_MAX if all bytes are @c uValue.
624 *
625 * Note that unlike most comparison functions, 0
626 * does not indicate a successful comparison, so the
627 * test for match is:
628 *
629 * UsefulBuf_IsValue(...) == SIZE_MAX
630 *
631 * If @c UB is null or empty, there is no match
632 * and 0 is returned.
Michael Eckel5c531332020-03-02 01:35:30 +0100633 */
634size_t UsefulBuf_IsValue(const UsefulBufC UB, uint8_t uValue);
635
636
637/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700638 * @brief Find one @ref UsefulBufC in another.
639 *
640 * @param[in] BytesToSearch Buffer to search through.
641 * @param[in] BytesToFind Buffer with bytes to be found.
642 *
643 * @return Position of found bytes or @c SIZE_MAX if not found.
Michael Eckel5c531332020-03-02 01:35:30 +0100644 */
645size_t UsefulBuf_FindBytes(UsefulBufC BytesToSearch, UsefulBufC BytesToFind);
646
647
Laurence Lundbladecf41c522021-02-20 10:19:07 -0700648/**
649 @brief Convert a pointer to an offset with bounds checking.
650
651 @param[in] UB Pointer to the UsefulInputBuf.
652 @param[in] p Pointer to convert to offset.
653
654 @return SIZE_MAX if @c p is out of range, the byte offset if not.
655*/
656static inline size_t UsefulBuf_PointerToOffset(UsefulBufC UB, const void *p);
657
658
Laurence Lundbladeb9702452021-03-08 21:02:57 -0800659#ifndef USEFULBUF_DISABLE_DEPRECATED
Michael Eckel5c531332020-03-02 01:35:30 +0100660/** Deprecated macro; use @ref UsefulBuf_FROM_SZ_LITERAL instead */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700661#define SZLiteralToUsefulBufC(szString) UsefulBuf_FROM_SZ_LITERAL(szString)
Michael Eckel5c531332020-03-02 01:35:30 +0100662
663/** Deprecated macro; use UsefulBuf_MAKE_STACK_UB instead */
664#define MakeUsefulBufOnStack(name, size) \
665 uint8_t __pBuf##name[(size)];\
666 UsefulBuf name = {__pBuf##name , sizeof( __pBuf##name )}
667
668/** Deprecated macro; use @ref UsefulBuf_FROM_BYTE_ARRAY_LITERAL instead */
669#define ByteArrayLiteralToUsefulBufC(pBytes) \
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700670 UsefulBuf_FROM_BYTE_ARRAY_LITERAL(pBytes)
Michael Eckel5c531332020-03-02 01:35:30 +0100671
672/** Deprecated function; use UsefulBuf_Unconst() instead */
673static inline UsefulBuf UsefulBufC_Unconst(const UsefulBufC UBC)
674{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700675 UsefulBuf UB;
676
Maxim Zhukovd538f0a2022-12-20 20:40:38 +0300677 // See UsefulBuf_Unconst() implementation for comment
678 UB.ptr = (void *)(uintptr_t)UBC.ptr;
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700679
680 UB.len = UBC.len;
681
682 return UB;
Michael Eckel5c531332020-03-02 01:35:30 +0100683}
Laurence Lundbladeb9702452021-03-08 21:02:57 -0800684#endif /* USEFULBUF_DISABLE_DEPRECATED */
Michael Eckel5c531332020-03-02 01:35:30 +0100685
686
687
688
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200689#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +0100690/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700691 * @brief Copy a @c float to a @c uint32_t.
692 *
693 * @param[in] f Float value to copy.
694 *
695 * @return A @c uint32_t with the float bits.
696 *
697 * Convenience function to avoid type punning, compiler warnings and
698 * such. The optimizer usually reduces this to a simple assignment. This
699 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100700 */
701static inline uint32_t UsefulBufUtil_CopyFloatToUint32(float f);
702
703
704/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700705 * @brief Copy a @c double to a @c uint64_t.
706 *
707 * @param[in] d Double value to copy.
708 *
709 * @return A @c uint64_t with the double bits.
710 *
711 * Convenience function to avoid type punning, compiler warnings and
712 * such. The optimizer usually reduces this to a simple assignment. This
713 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100714 */
715static inline uint64_t UsefulBufUtil_CopyDoubleToUint64(double d);
716
717
718/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700719 * @brief Copy a @c uint32_t to a @c float.
720 *
721 * @param[in] u32 Integer value to copy.
722 *
723 * @return The value as a @c float.
724 *
725 * Convenience function to avoid type punning, compiler warnings and
726 * such. The optimizer usually reduces this to a simple assignment. This
727 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100728 */
729static inline float UsefulBufUtil_CopyUint32ToFloat(uint32_t u32);
730
731
732/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700733 * @brief Copy a @c uint64_t to a @c double.
734 *
735 * @param[in] u64 Integer value to copy.
736 *
737 * @return The value as a @c double.
738 *
739 * Convenience function to avoid type punning, compiler warnings and
740 * such. The optimizer usually reduces this to a simple assignment. This
741 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100742 */
743static inline double UsefulBufUtil_CopyUint64ToDouble(uint64_t u64);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200744#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +0100745
746
747
748
749/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700750 * UsefulOutBuf is a structure and functions (an object) for
751 * serializing data into a buffer to encode for a network protocol or
752 * write data to a file.
753 *
754 * The main idea is that all the pointer manipulation is performed by
755 * @ref UsefulOutBuf functions so the caller doesn't have to do any
756 * pointer manipulation. The pointer manipulation is centralized.
757 * This code has been reviewed and written carefully so it
758 * spares the caller of much of this work and results in safer code
759 * with less effort.
760 *
761 * The @ref UsefulOutBuf methods that add data to the output buffer
762 * always check the length and will never write off the end of the
763 * output buffer. If an attempt to add data that will not fit is made,
764 * an internal error flag will be set and further attempts to add data
765 * will not do anything.
766 *
767 * There is no way to ever write off the end of that buffer when
768 * calling the @c UsefulOutBuf_AddXxx() and
769 * @c UsefulOutBuf_InsertXxx() functions.
770 *
771 * The functions to add data do not report success of failure. The
772 * caller only needs to check for an error in the final call, either
773 * UsefulOutBuf_OutUBuf() or UsefulOutBuf_CopyOut() to get the
774 * result. This makes the calling code cleaner.
775 *
776 * There is a utility function to get the error status anytime along
777 * the way for a special circumstance. There are functions to see how
778 * much room is left and see if some data will fit too, but their use
779 * is generally unnecessary.
780 *
781 * The general call flow is:
782 *
783 * - Initialize by calling @ref UsefulOutBuf_Init(). The output
784 * buffer given to it can be from the heap, stack or
785 * otherwise. @ref UsefulOutBuf_MakeOnStack is a convenience
786 * macro that makes a buffer on the stack and initializes it.
787 *
788 * - Call methods like UsefulOutBuf_InsertString(),
789 * UsefulOutBuf_AppendUint32() and UsefulOutBuf_InsertUsefulBuf()
790 * to output data. The append calls add data to the end of the
791 * valid data. The insert calls take a position argument.
792 *
793 * - Call UsefulOutBuf_OutUBuf() or UsefulOutBuf_CopyOut() to see
794 * there were no errors and to get the serialized output bytes.
795 *
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700796 * @ref UsefulOutBuf can be used in a mode to calculate the size of
797 * what would be output without actually outputting anything. This is
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700798 * useful to calculate the size of a buffer that is to be allocated to
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700799 * hold the output. See @ref SizeCalculateUsefulBuf.
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700800 *
801 * Methods like UsefulOutBuf_InsertUint64() always output in network
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700802 * byte order (big endian).
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700803 *
804 * The possible errors are:
805 *
806 * - The @ref UsefulOutBuf was not initialized or was corrupted.
807 *
808 * - An attempt was made to add data that will not fit.
809 *
810 * - An attempt was made to insert data at a position beyond the end of
811 * the buffer.
812 *
813 * - An attempt was made to insert data at a position beyond the valid
814 * data in the buffer.
815 *
816 * Some inexpensive simple sanity checks are performed before every
817 * data addition to guard against use of an uninitialized or corrupted
818 * UsefulOutBuf.
819 *
820 * @ref UsefulOutBuf has been used to create a CBOR encoder. The CBOR
821 * encoder has almost no pointer manipulation in it, is easier to
822 * read, and easier to review.
823 *
824 * A @ref UsefulOutBuf is small and can go on the stack:
825 * - 32 bytes (27 bytes plus alignment padding) on a 64-bit CPU
826 * - 16 bytes (15 bytes plus alignment padding) on a 32-bit CPU
Michael Eckel5c531332020-03-02 01:35:30 +0100827 */
828typedef struct useful_out_buf {
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700829 /* PRIVATE DATA STRUCTURE */
830 UsefulBuf UB; /* Memory that is being output to */
831 size_t data_len; /* length of the valid data, the insertion point */
832 uint16_t magic; /* Used to detect corruption and lack
833 * of initialization */
Michael Eckel5c531332020-03-02 01:35:30 +0100834 uint8_t err;
835} UsefulOutBuf;
836
837
838/**
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700839 * This is a @ref UsefulBuf value that can be passed to
840 * UsefulOutBuf_Init() to have it calculate the size of the output
841 * buffer needed. Pass this for @c Storage, call all the append and
842 * insert functions normally, then call UsefulOutBuf_OutUBuf(). The
843 * returned @ref UsefulBufC has the size.
844 *
845 * As one can see, this is just a NULL pointer and very large size.
846 * The NULL pointer tells UsefulOutputBuf to not copy any data.
847 */
848#ifdef __cplusplus
849#define SizeCalculateUsefulBuf {NULL, SIZE_MAX}
850#else
851#define SizeCalculateUsefulBuf ((UsefulBuf) {NULL, SIZE_MAX})
852#endif
853
854
855/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700856 * @brief Initialize and supply the actual output buffer.
857 *
858 * @param[out] pUOutBuf The @ref UsefulOutBuf to initialize.
859 * @param[in] Storage Buffer to output into.
860 *
861 * This initializes the @ref UsefulOutBuf with storage, sets the
862 * current position to the beginning of the buffer and clears the
863 * error state.
864 *
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700865 * See @ref SizeCalculateUsefulBuf for instructions on how to
866 * initialize a @ref UsefulOutBuf to calculate the size that would be
867 * output without actually outputting.
868 *
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700869 * This must be called before the @ref UsefulOutBuf is used.
Michael Eckel5c531332020-03-02 01:35:30 +0100870 */
871void UsefulOutBuf_Init(UsefulOutBuf *pUOutBuf, UsefulBuf Storage);
872
873
874/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700875 * Convenience macro to make a @ref UsefulOutBuf on the stack and
876 * initialize it with a stack buffer of the given size. The variable
877 * will be named @c name.
Michael Eckel5c531332020-03-02 01:35:30 +0100878 */
879#define UsefulOutBuf_MakeOnStack(name, size) \
880 uint8_t __pBuf##name[(size)];\
881 UsefulOutBuf name;\
882 UsefulOutBuf_Init(&(name), (UsefulBuf){__pBuf##name, (size)});
883
884
885/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700886 * @brief Reset a @ref UsefulOutBuf for re use.
887 *
888 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf
889 *
890 * This sets the amount of data in the output buffer to none and
891 * clears the error state.
892 *
893 * The output buffer is still the same one and size as from the
894 * UsefulOutBuf_Init() call.
895 *
896 * This doesn't zero the data, just resets to 0 bytes of valid data.
Michael Eckel5c531332020-03-02 01:35:30 +0100897 */
898static inline void UsefulOutBuf_Reset(UsefulOutBuf *pUOutBuf);
899
900
901/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700902 * @brief Returns position of end of data in the @ref UsefulOutBuf.
903 *
904 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
905 *
906 * @return position of end of data.
907 *
908 * On a freshly initialized @ref UsefulOutBuf with no data added, this
909 * will return 0. After 10 bytes have been added, it will return 10
910 * and so on.
911 *
912 * Generally, there is no need to call this for most uses of @ref
913 * UsefulOutBuf.
Michael Eckel5c531332020-03-02 01:35:30 +0100914 */
915static inline size_t UsefulOutBuf_GetEndPosition(UsefulOutBuf *pUOutBuf);
916
917
918/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700919 * @brief Returns whether any data has been added to the @ref UsefulOutBuf.
920 *
921 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
922 *
923 * @return 1 if output position is at start, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100924 */
925static inline int UsefulOutBuf_AtStart(UsefulOutBuf *pUOutBuf);
926
927
928/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700929 * @brief Inserts bytes into the @ref UsefulOutBuf.
930 *
931 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
932 * @param[in] NewData The bytes to insert.
933 * @param[in] uPos Index in output buffer at which to insert.
934 *
935 * @c NewData is the pointer and length for the bytes to be added to
936 * the output buffer. There must be room in the output buffer for all
937 * of @c NewData or an error will occur.
938 *
939 * The insertion point must be between 0 and the current valid
940 * data. If not, an error will occur. Appending data to the output
941 * buffer is achieved by inserting at the end of the valid data. This
942 * can be retrieved by calling UsefulOutBuf_GetEndPosition().
943 *
944 * When insertion is performed, the bytes between the insertion point
945 * and the end of data previously added to the output buffer are slid
946 * to the right to make room for the new data.
947 *
948 * Overlapping buffers are OK. @c NewData can point to data in the
949 * output buffer.
950 *
Laurence Lundblade5a6fec52022-12-25 11:28:43 -0700951 * NewData.len may be 0 in which case nothing will be inserted.
952 *
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700953 * If an error occurs, an error state is set in the @ref
954 * UsefulOutBuf. No error is returned. All subsequent attempts to add
955 * data will do nothing.
956 *
957 * The intended use is that all additions are made without checking
958 * for an error. The error will be taken into account when
959 * UsefulOutBuf_OutUBuf() returns @c NullUsefulBufC.
960 * UsefulOutBuf_GetError() can also be called to check for an error.
Michael Eckel5c531332020-03-02 01:35:30 +0100961 */
962void UsefulOutBuf_InsertUsefulBuf(UsefulOutBuf *pUOutBuf,
963 UsefulBufC NewData,
964 size_t uPos);
965
966
967/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700968 * @brief Insert a data buffer into the @ref UsefulOutBuf.
969 *
970 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
971 * @param[in] pBytes Pointer to the bytes to insert
972 * @param[in] uLen Length of the bytes to insert
973 * @param[in] uPos Index in output buffer at which to insert
974 *
975 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
976 * the difference being a pointer and length is passed in rather than an
977 * @ref UsefulBufC.
Michael Eckel5c531332020-03-02 01:35:30 +0100978 */
979static inline void UsefulOutBuf_InsertData(UsefulOutBuf *pUOutBuf,
980 const void *pBytes,
981 size_t uLen,
982 size_t uPos);
983
984
985/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700986 * @brief Insert a NULL-terminated string into the UsefulOutBuf.
987 *
988 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
989 * @param[in] szString NULL-terminated string to insert.
990 * @param[in] uPos Index in output buffer at which to insert.
Michael Eckel5c531332020-03-02 01:35:30 +0100991 */
992static inline void UsefulOutBuf_InsertString(UsefulOutBuf *pUOutBuf,
993 const char *szString,
994 size_t uPos);
995
996
997/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700998 * @brief Insert a byte into the @ref UsefulOutBuf.
999 *
1000 * @param[in] pUOutBuf Pointer to the UsefulOutBuf.
1001 * @param[in] byte Bytes to insert.
1002 * @param[in] uPos Index in output buffer at which to insert.
1003 *
1004 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1005 * with the difference being a single byte is to be inserted.
Michael Eckel5c531332020-03-02 01:35:30 +01001006 */
1007static inline void UsefulOutBuf_InsertByte(UsefulOutBuf *pUOutBuf,
1008 uint8_t byte,
1009 size_t uPos);
1010
1011
1012/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001013 * @brief Insert a 16-bit integer into the @ref UsefulOutBuf.
1014 *
1015 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1016 * @param[in] uInteger16 Integer to insert.
1017 * @param[in] uPos Index in output buffer at which to insert.
1018 *
1019 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1020 * with the difference being a two-byte integer is to be inserted.
1021 *
1022 * The integer will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001023 */
1024static inline void UsefulOutBuf_InsertUint16(UsefulOutBuf *pUOutBuf,
1025 uint16_t uInteger16,
1026 size_t uPos);
1027
1028
1029/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001030 * @brief Insert a 32-bit integer into the @ref UsefulOutBuf.
1031 *
1032 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1033 * @param[in] uInteger32 Integer to insert.
1034 * @param[in] uPos Index in output buffer at which to insert.
1035 *
1036 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1037 * with the difference being a four-byte integer is to be inserted.
1038 *
1039 * The integer will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001040 */
1041static inline void UsefulOutBuf_InsertUint32(UsefulOutBuf *pUOutBuf,
1042 uint32_t uInteger32,
1043 size_t uPos);
1044
1045
1046/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001047 * @brief Insert a 64-bit integer into the @ref UsefulOutBuf.
1048 *
1049 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1050 * @param[in] uInteger64 Integer to insert.
1051 * @param[in] uPos Index in output buffer at which to insert.
1052 *
1053 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1054 * with the difference being an eight-byte integer is to be inserted.
1055 *
1056 * The integer will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001057 */
1058static inline void UsefulOutBuf_InsertUint64(UsefulOutBuf *pUOutBuf,
1059 uint64_t uInteger64,
1060 size_t uPos);
1061
1062
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001063#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001064/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001065 * @brief Insert a @c float into the @ref UsefulOutBuf.
1066 *
1067 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1068 * @param[in] f @c float to insert.
1069 * @param[in] uPos Index in output buffer at which to insert.
1070 *
1071 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1072 * with the difference being a @c float is to be inserted.
1073 *
1074 * The @c float will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001075 */
1076static inline void UsefulOutBuf_InsertFloat(UsefulOutBuf *pUOutBuf,
1077 float f,
1078 size_t uPos);
1079
1080
1081/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001082 * @brief Insert a @c double into the @ref UsefulOutBuf.
1083 *
1084 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1085 * @param[in] d @c double to insert.
1086 * @param[in] uPos Index in output buffer at which to insert.
1087 *
1088 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1089 * with the difference being a @c double is to be inserted.
1090 *
1091 * The @c double will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001092 */
1093static inline void UsefulOutBuf_InsertDouble(UsefulOutBuf *pUOutBuf,
1094 double d,
1095 size_t uPos);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001096#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001097
1098
1099/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001100 * @brief Append a @ref UsefulBuf into the @ref UsefulOutBuf.
1101 *
1102 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1103 * @param[in] NewData The @ref UsefulBuf with the bytes to append.
1104 *
1105 * See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
1106 * with the insertion point at the end of the valid data.
1107 */
Michael Eckel5c531332020-03-02 01:35:30 +01001108static inline void UsefulOutBuf_AppendUsefulBuf(UsefulOutBuf *pUOutBuf,
1109 UsefulBufC NewData);
1110
1111
1112/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001113 * @brief Append bytes to the @ref UsefulOutBuf.
1114 *
1115 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1116 * @param[in] pBytes Pointer to bytes to append.
1117 * @param[in] uLen Length of @c pBytes to append.
1118 *
1119 * See UsefulOutBuf_InsertData() for details. This does the same with
1120 * the insertion point at the end of the valid data.
Michael Eckel5c531332020-03-02 01:35:30 +01001121 */
1122static inline void UsefulOutBuf_AppendData(UsefulOutBuf *pUOutBuf,
1123 const void *pBytes,
1124 size_t uLen);
1125
1126
1127/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001128 * @brief Append a NULL-terminated string to the @ref UsefulOutBuf
1129 *
1130 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1131 * @param[in] szString NULL-terminated string to append.
Michael Eckel5c531332020-03-02 01:35:30 +01001132 */
1133static inline void UsefulOutBuf_AppendString(UsefulOutBuf *pUOutBuf,
1134 const char *szString);
1135
1136
1137/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001138 * @brief Append a byte to the @ref UsefulOutBuf
1139 *
1140 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1141 * @param[in] byte Bytes to append.
1142 *
1143 * See UsefulOutBuf_InsertByte() for details. This does the same
1144 * with the insertion point at the end of the valid data.
Michael Eckel5c531332020-03-02 01:35:30 +01001145 */
1146static inline void UsefulOutBuf_AppendByte(UsefulOutBuf *pUOutBuf,
1147 uint8_t byte);
1148
1149
1150/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001151 * @brief Append an integer to the @ref UsefulOutBuf
1152 *
1153 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1154 * @param[in] uInteger16 Integer to append.
1155 *
1156 * See UsefulOutBuf_InsertUint16() for details. This does the same
1157 * with the insertion point at the end of the valid data.
1158 *
1159 * The integer will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001160 */
1161static inline void UsefulOutBuf_AppendUint16(UsefulOutBuf *pUOutBuf,
1162 uint16_t uInteger16);
1163
1164
1165/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001166 * @brief Append an integer to the @ref UsefulOutBuf
1167 *
1168 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1169 * @param[in] uInteger32 Integer to append.
1170 *
1171 * See UsefulOutBuf_InsertUint32() for details. This does the same
1172 * with the insertion point at the end of the valid data.
1173 *
1174 * The integer will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001175 */
1176static inline void UsefulOutBuf_AppendUint32(UsefulOutBuf *pUOutBuf,
1177 uint32_t uInteger32);
1178
1179
1180/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001181 * @brief Append an integer to the @ref UsefulOutBuf
1182 *
1183 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1184 * @param[in] uInteger64 Integer to append.
1185 *
1186 * See UsefulOutBuf_InsertUint64() for details. This does the same
1187 * with the insertion point at the end of the valid data.
1188 *
1189 * The integer will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001190 */
1191static inline void UsefulOutBuf_AppendUint64(UsefulOutBuf *pUOutBuf,
1192 uint64_t uInteger64);
1193
1194
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001195#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001196/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001197 * @brief Append a @c float to the @ref UsefulOutBuf
1198 *
1199 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1200 * @param[in] f @c float to append.
1201 *
1202 * See UsefulOutBuf_InsertFloat() for details. This does the same with
1203 * the insertion point at the end of the valid data.
1204 *
1205 * The float will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001206 */
1207static inline void UsefulOutBuf_AppendFloat(UsefulOutBuf *pUOutBuf,
1208 float f);
1209
1210
1211/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001212 * @brief Append a @c double to the @ref UsefulOutBuf
1213 *
1214 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1215 * @param[in] d @c double to append.
1216 *
1217 * See UsefulOutBuf_InsertDouble() for details. This does the same
1218 * with the insertion point at the end of the valid data.
1219 *
1220 * The double will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001221 */
1222static inline void UsefulOutBuf_AppendDouble(UsefulOutBuf *pUOutBuf,
1223 double d);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001224#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001225
1226
1227/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001228 * @brief Returns the current error status.
1229 *
1230 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1231 *
1232 * @return 0 if all OK, 1 on error.
1233 *
1234 * This returns the error status since a call to either
1235 * UsefulOutBuf_Reset() of UsefulOutBuf_Init(). Once a @ref UsefulOutBuf
1236 * goes into the error state, it will stay until one of those
1237 * functions is called.
1238 *
1239 * Possible error conditions are:
1240 * - bytes to be inserted will not fit
1241 * - insertion point is out of buffer or past valid data
1242 * - current position is off end of buffer (probably corrupted or uninitialized)
1243 * - detect corruption / uninitialized by bad magic number
Michael Eckel5c531332020-03-02 01:35:30 +01001244 */
1245static inline int UsefulOutBuf_GetError(UsefulOutBuf *pUOutBuf);
1246
1247
1248/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001249 * @brief Returns number of bytes unused used in the output buffer.
1250 *
1251 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1252 *
1253 * @return Number of unused bytes or zero.
1254 *
1255 * Because of the error handling strategy and checks in
1256 * UsefulOutBuf_InsertUsefulBuf() it is usually not necessary to use
1257 * this.
Michael Eckel5c531332020-03-02 01:35:30 +01001258 */
1259static inline size_t UsefulOutBuf_RoomLeft(UsefulOutBuf *pUOutBuf);
1260
1261
1262/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001263 *@brief Returns 1 if some number of bytes will fit in the @ref UsefulOutBuf.
1264 *
1265 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf
1266 * @param[in] uLen Number of bytes for which to check
1267 *
1268 * @return 1 if @c uLen bytes will fit, 0 if not.
1269 *
1270 * Because of the error handling strategy and checks in
1271 * UsefulOutBuf_InsertUsefulBuf() it is usually not necessary to use
1272 * this.
Michael Eckel5c531332020-03-02 01:35:30 +01001273 */
1274static inline int UsefulOutBuf_WillItFit(UsefulOutBuf *pUOutBuf, size_t uLen);
1275
1276
1277 /**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001278 * @brief Returns 1 if buffer given to UsefulOutBuf_Init() was @c NULL.
1279 *
1280 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf
1281 *
1282 * @return 1 if buffer given to UsefulOutBuf_Init() was @c NULL.
1283 *
1284 * Giving a @c NULL output buffer to UsefulOutBuf_Init() is used when
1285 * just calculating the length of the encoded data.
1286 */
Michael Eckel5c531332020-03-02 01:35:30 +01001287static inline int UsefulOutBuf_IsBufferNULL(UsefulOutBuf *pUOutBuf);
1288
1289
1290/**
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001291 * @brief Returns pointer and length of the output buffer not yet used.
1292 *
1293 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1294 *
1295 * @return pointer and length of output buffer not used.
1296 *
1297 * This is an escape that allows the caller to write directly
1298 * to the output buffer without any checks. This doesn't
1299 * change the output buffer or state. It just returns a pointer
1300 * and length of the bytes remaining.
1301 *
1302 * This is useful to avoid having the bytes to be added all
1303 * in a contiguous buffer. Its use can save memory. A good
1304 * example is in the COSE encrypt implementation where
1305 * the output of the symmetric cipher can go directly
1306 * into the output buffer, rather than having to go into
1307 * an intermediate buffer.
1308 *
1309 * See UsefulOutBuf_Advance() which is used to tell
1310 * UsefulOutBuf how much was written.
1311 *
1312 * Warning: this bypasses the buffer safety provided by
1313 * UsefulOutBuf!
1314 */
1315static inline UsefulBuf
1316UsefulOutBuf_GetOutPlace(UsefulOutBuf *pUOutBuf);
1317
1318
1319/**
1320 * @brief Advance the amount output assuming it was written by the caller.
1321 *
1322 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1323 * @param[in] uAmount The amount to advance.
1324 *
1325 * This advances the position in the output buffer
1326 * by \c uAmount. This assumes that the
1327 * caller has written \c uAmount to the pointer obtained
1328 * with UsefulOutBuf_GetOutPlace().
1329 *
1330 * Warning: this bypasses the buffer safety provided by
1331 * UsefulOutBuf!
1332 */
1333void
1334UsefulOutBuf_Advance(UsefulOutBuf *pUOutBuf, size_t uAmount);
1335
1336
1337/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001338 * @brief Returns the resulting valid data in a UsefulOutBuf
1339 *
1340 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1341 *
1342 * @return The valid data in @ref UsefulOutBuf or
1343 * @ref NULLUsefulBufC if there was an error adding data.
1344 *
1345 * The storage for the returned data is the @c Storage parameter
1346 * passed to UsefulOutBuf_Init(). See also UsefulOutBuf_CopyOut().
1347 *
1348 * This can be called anytime and many times to get intermediate
1349 * results. It doesn't change the data or reset the current position,
1350 * so further data can be added.
Michael Eckel5c531332020-03-02 01:35:30 +01001351 */
1352UsefulBufC UsefulOutBuf_OutUBuf(UsefulOutBuf *pUOutBuf);
1353
1354
1355/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001356 * @brief Copies the valid data into a supplied buffer
1357 *
1358 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1359 * @param[out] Dest The destination buffer to copy into.
1360 *
1361 * @return Pointer and length of copied data or @c NULLUsefulBufC
1362 * if it will not fit in the @c Dest buffer or the error
1363 * state was entered.
1364 *
1365 * This is the same as UsefulOutBuf_OutUBuf() except it copies the
1366 * data to @c Dest.
1367 */
Michael Eckel5c531332020-03-02 01:35:30 +01001368UsefulBufC UsefulOutBuf_CopyOut(UsefulOutBuf *pUOutBuf, UsefulBuf Dest);
1369
1370
1371
1372
1373/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001374 * @ref UsefulInputBuf is the counterpart to @ref UsefulOutBuf. It is
1375 * for parsing data received. Initialize it with the data from the
1376 * network. Then use the functions like UsefulInputBuf_GetBytes() to
1377 * get data chunks of various types. A position cursor is maintained
1378 * internally.
1379 *
1380 * As long as the functions here are used, there will never be any
1381 * reference off the end of the given buffer (except
1382 * UsefulInputBuf_SetBufferLength()). This is true even if they are
1383 * called incorrectly, an attempt is made to seek off the end of the
1384 * buffer or such. This makes it easier to write safe and correct
1385 * code. For example, the QCBOR decoder implementation is safer and
1386 * easier to review through its use of @ref UsefulInputBuf.
1387 *
1388 * @ref UsefulInputBuf maintains an internal error state. The
1389 * intended use is fetching data chunks without any error checks until
1390 * the end. If there was any error, such as an attempt to fetch data
1391 * off the end, the error state is entered and no further data will be
1392 * returned. In the error state the @c UsefulInputBuf_GetXxxx()
1393 * functions return 0, or @c NULL or @ref NULLUsefulBufC. As long as
1394 * null is not dereferenced, the error check can be put off until the
1395 * end, simplifying the calling code.
1396 *
1397 * The integer and float parsing expects network byte order (big
1398 * endian). Network byte order is what is used by TCP/IP, CBOR and
1399 * most internet protocols.
1400 *
1401 * Lots of inline functions are used to keep code size down. The
1402 * optimizer, particularly with the @c -Os or @c -O3, also reduces
1403 * code size a lot. The only non-inline code is
1404 * UsefulInputBuf_GetBytes(). It is less than 100 bytes so use of
1405 * @ref UsefulInputBuf doesn't add much code for all the messy
1406 * hard-to-get right issues with parsing binary protocols in C that it
1407 * solves.
1408 *
1409 * The parse context size is:
1410 * - 64-bit machine: 16 + 8 + 2 + 1 (+ 5 bytes padding to align) = 32 bytes
1411 * - 32-bit machine: 8 + 4 + 2 + 1 (+ 1 byte padding to align) = 16 bytes
Michael Eckel5c531332020-03-02 01:35:30 +01001412 */
1413typedef struct useful_input_buf {
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001414 /* PRIVATE DATA STRUCTURE */
1415 UsefulBufC UB; /* Data being parsed */
1416 size_t cursor; /* Current offset in data being parse */
1417 uint16_t magic; /* Check for corrupted or uninitialized UsefulInputBuf */
1418 uint8_t err; /* Set request goes off end or magic number is bad */
Michael Eckel5c531332020-03-02 01:35:30 +01001419} UsefulInputBuf;
1420
1421#define UIB_MAGIC (0xB00F)
1422
1423
1424/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001425 * @brief Initialize the @ref UsefulInputBuf structure before use.
1426 *
1427 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1428 * @param[in] UB The data to parse.
Michael Eckel5c531332020-03-02 01:35:30 +01001429 */
1430static inline void UsefulInputBuf_Init(UsefulInputBuf *pUInBuf, UsefulBufC UB);
1431
1432
1433/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001434 * @brief Returns current position in input buffer.
1435 *
1436 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1437 *
1438 * @return Integer position of the cursor.
1439 *
1440 * The position that the next bytes will be returned from.
Michael Eckel5c531332020-03-02 01:35:30 +01001441 */
1442static size_t UsefulInputBuf_Tell(UsefulInputBuf *pUInBuf);
1443
1444
1445/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001446 * @brief Sets the current position in input buffer.
1447 *
1448 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1449 * @param[in] uPos Position to set to.
1450 *
1451 * If the position is off the end of the input buffer, the error state
1452 * is entered.
1453 *
1454 * Seeking to a valid position in the buffer will not reset the error
1455 * state. Only re-initialization will do that.
Michael Eckel5c531332020-03-02 01:35:30 +01001456 */
1457static void UsefulInputBuf_Seek(UsefulInputBuf *pUInBuf, size_t uPos);
1458
1459
1460/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001461 * @brief Returns the number of bytes from the cursor to the end of the buffer,
1462 * the unconsumed bytes.
1463 *
1464 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1465 *
1466 * @return Number of bytes unconsumed or 0 on error.
1467 *
1468 * Returns 0 if the cursor is invalid or corruption of the
1469 * @ref UsefulInputBuf structure is detected.
Michael Eckel5c531332020-03-02 01:35:30 +01001470 */
1471static size_t UsefulInputBuf_BytesUnconsumed(UsefulInputBuf *pUInBuf);
1472
1473
1474/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001475 * @brief Check if there are unconsumed bytes.
1476 *
1477 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1478 * @param[in] uLen Number of bytes to check availability for.
1479 *
1480 * @return 1 if @c uLen bytes are available after the cursor, and 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +01001481 */
1482static int UsefulInputBuf_BytesAvailable(UsefulInputBuf *pUInBuf, size_t uLen);
1483
1484
1485/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001486 * @brief Convert a pointer to an offset with bounds checking.
1487 *
1488 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1489 * @param[in] p Pointer to convert to offset.
1490 *
1491 * @return SIZE_MAX if @c p is out of range, the byte offset if not.
1492 */
Laurence Lundbladecf41c522021-02-20 10:19:07 -07001493static inline size_t UsefulInputBuf_PointerToOffset(UsefulInputBuf *pUInBuf, const void *p);
1494
1495
1496/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001497 * @brief Get pointer to bytes out of the input buffer.
1498 *
1499 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1500 * @param[in] uNum Number of bytes to get.
1501 *
1502 * @return Pointer to bytes.
1503 *
1504 * This consumes @c uNum bytes from the input buffer. This returns a
1505 * pointer to the start of the @c uNum bytes.
1506 *
1507 * If there are not @c uNum bytes in the input buffer, @c NULL will be
1508 * returned and the error state is entered.
1509 *
1510 * This advances the position cursor by @c uNum bytes.
Michael Eckel5c531332020-03-02 01:35:30 +01001511 */
1512const void * UsefulInputBuf_GetBytes(UsefulInputBuf *pUInBuf, size_t uNum);
1513
1514
1515/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001516 * @brief Get @ref UsefulBuf out of the input buffer.
1517 *
1518 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1519 * @param[in] uNum Number of bytes to get.
1520 *
1521 * @return A @ref UsefulBufC with ptr and length of bytes consumed.
1522 *
1523 * This consumes @c uNum bytes from the input buffer and returns the
1524 * pointer and length for them as a @ref UsefulBufC. The length
1525 * returned will always be @c uNum. The position cursor is advanced by
1526 * @c uNum bytes.
1527 *
1528 * If there are not @c uNum bytes in the input buffer, @ref
1529 * NULLUsefulBufC will be returned and the error state is entered.
Michael Eckel5c531332020-03-02 01:35:30 +01001530 */
1531static inline UsefulBufC UsefulInputBuf_GetUsefulBuf(UsefulInputBuf *pUInBuf, size_t uNum);
1532
1533
1534/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001535 * @brief Get a byte out of the input buffer.
1536 *
1537 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1538 *
1539 * @return The byte.
1540 *
1541 * This consumes 1 byte from the input buffer, returns it and advances
1542 * the position cursor by 1.
1543 *
1544 * If there is not 1 byte in the buffer, 0 will be returned for the
1545 * byte and the error state is entered. To know if the 0 returned was
1546 * in error or the real value, the error state must be checked. If
1547 * possible, put this off until all values are retrieved to have
1548 * smaller and simpler code, but if not possible
1549 * UsefulInputBuf_GetError() can be called. Also, in the error state
1550 * UsefulInputBuf_GetBytes() returns @c NULL *or the @c ptr from
1551 * UsefulInputBuf_GetUsefulBuf() is @c NULL.
Michael Eckel5c531332020-03-02 01:35:30 +01001552 */
1553static inline uint8_t UsefulInputBuf_GetByte(UsefulInputBuf *pUInBuf);
1554
1555
1556/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001557 * @brief Get a @c uint16_t out of the input buffer.
1558 *
1559 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1560 *
1561 * @return The @c uint16_t.
1562 *
1563 * See UsefulInputBuf_GetByte(). This works the same, except it returns
1564 * a @c uint16_t and two bytes are consumed.
1565 *
1566 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001567 */
1568static inline uint16_t UsefulInputBuf_GetUint16(UsefulInputBuf *pUInBuf);
1569
1570
1571/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001572 * @brief Get a @c uint32_t out of the input buffer.
1573 *
1574 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1575 *
1576 * @return The @c uint32_t.
1577 *
1578 * See UsefulInputBuf_GetByte(). This works the same, except it
1579 * returns a @c uint32_t and four bytes are consumed.
1580 *
1581 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001582 */
1583static uint32_t UsefulInputBuf_GetUint32(UsefulInputBuf *pUInBuf);
1584
1585
1586/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001587 * @brief Get a @c uint64_t out of the input buffer.
1588 *
1589 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1590 *
1591 * @return The uint64_t.
1592 *
1593 * See UsefulInputBuf_GetByte(). This works the same, except it returns
1594 * a @c uint64_t and eight bytes are consumed.
1595 *
1596 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001597 */
1598static uint64_t UsefulInputBuf_GetUint64(UsefulInputBuf *pUInBuf);
1599
1600
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001601#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001602/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001603 * @brief Get a float out of the input buffer.
1604 *
1605 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1606 *
1607 * @return The float.
1608 *
1609 * See UsefulInputBuf_GetByte(). This works the same, except it
1610 * returns a float and four bytes are consumed.
1611 *
1612 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001613 */
1614static float UsefulInputBuf_GetFloat(UsefulInputBuf *pUInBuf);
1615
1616
1617/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001618 * @brief Get a double out of the input buffer.
1619 *
1620 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1621 *
1622 * @return The double.
1623 *
1624 * See UsefulInputBuf_GetByte(). This works the same, except it
1625 * returns a double and eight bytes are consumed.
1626 *
1627 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001628 */
1629static double UsefulInputBuf_GetDouble(UsefulInputBuf *pUInBuf);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001630#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001631
1632
1633/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001634 * @brief Get the error status.
1635 *
1636 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1637 *
1638 * @return 0 if not in the error state, 1 if in the error state.
1639 *
1640 * This returns whether the @ref UsefulInputBuf is in the
1641 * error state or not.
1642 *
1643 * The error state is entered for one of these reasons:
1644 * - Attempt to fetch data past the end of the buffer
1645 * - Attempt to seek to a position past the end of the buffer
1646 * - Attempt to get data from an uninitialized or corrupt instance
1647 * of @ref UsefulInputBuf
1648 *
1649 * Once in the error state, it can only be cleared by calling
1650 * UsefulInputBuf_Init().
1651 *
1652 * For many use cases, it is possible to only call this once after all
1653 * the @c UsefulInputBuf_GetXxxx() calls have been made. This is
1654 * possible if no reference to the data returned are needed before the
1655 * error state is checked.
1656 *
1657 * In some cases UsefulInputBuf_GetUsefulBuf() or
1658 * UsefulInputBuf_GetBytes() can stand in for this because they return
1659 * @c NULL if the error state has been entered. (The others can't stand
1660 * in because they don't return a clearly distinct error value.)
Michael Eckel5c531332020-03-02 01:35:30 +01001661 */
1662static int UsefulInputBuf_GetError(UsefulInputBuf *pUInBuf);
1663
1664
Laurence Lundblade24d509a2020-06-06 18:43:15 -07001665/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001666 * @brief Gets the input buffer length.
1667 *
1668 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1669 *
1670 * @return The length of the input buffer.
1671 *
1672 * This returns the length of the input buffer set by
1673 * UsefulInputBuf_Init() or UsefulInputBuf_SetBufferLength().
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07001674 */
1675static inline size_t UsefulInputBuf_GetBufferLength(UsefulInputBuf *pUInBuf);
1676
1677
1678/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001679 * @brief Alters the input buffer length (use with caution).
1680 *
1681 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1682 * @param[in] uNewLen The new length of the input buffer.
1683 *
1684 * This alters the internal remembered length of the input buffer set
1685 * when UsefulInputBuf_Init() was called.
1686 *
1687 * The new length given here should always be equal to or less than
1688 * the length given when UsefulInputBuf_Init() was called. Making it
1689 * larger allows @ref UsefulInputBuf to run off the input buffer.
1690 *
1691 * The typical use is to set a length shorter than that when
1692 * initialized to constrain parsing. If
1693 * UsefulInputBuf_GetBufferLength() was called before this, then the
1694 * original length can be restored with another call to this.
1695 *
1696 * This should be used with caution. It is the only
1697 * @ref UsefulInputBuf method that can violate the safety of input
1698 * buffer parsing.
Laurence Lundblade24d509a2020-06-06 18:43:15 -07001699 */
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07001700static void UsefulInputBuf_SetBufferLength(UsefulInputBuf *pUInBuf, size_t uNewLen);
Michael Eckel5c531332020-03-02 01:35:30 +01001701
1702
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001703
1704
Michael Eckel5c531332020-03-02 01:35:30 +01001705/*----------------------------------------------------------
1706 Inline implementations.
1707 */
1708static inline int UsefulBuf_IsNULL(UsefulBuf UB)
1709{
1710 return !UB.ptr;
1711}
1712
1713
1714static inline int UsefulBuf_IsNULLC(UsefulBufC UB)
1715{
1716 return !UB.ptr;
1717}
1718
1719
1720static inline int UsefulBuf_IsEmpty(UsefulBuf UB)
1721{
1722 return !UB.len;
1723}
1724
1725
1726static inline int UsefulBuf_IsEmptyC(UsefulBufC UB)
1727{
1728 return !UB.len;
1729}
1730
1731
1732static inline int UsefulBuf_IsNULLOrEmpty(UsefulBuf UB)
1733{
1734 return UsefulBuf_IsEmpty(UB) || UsefulBuf_IsNULL(UB);
1735}
1736
1737
1738static inline int UsefulBuf_IsNULLOrEmptyC(UsefulBufC UB)
1739{
1740 return UsefulBuf_IsEmptyC(UB) || UsefulBuf_IsNULLC(UB);
1741}
1742
1743
1744static inline UsefulBufC UsefulBuf_Const(const UsefulBuf UB)
1745{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001746 UsefulBufC UBC;
1747 UBC.ptr = UB.ptr;
1748 UBC.len = UB.len;
1749
1750 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001751}
1752
Michael Eckel5c531332020-03-02 01:35:30 +01001753static inline UsefulBuf UsefulBuf_Unconst(const UsefulBufC UBC)
1754{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001755 UsefulBuf UB;
1756
Laurence Lundbladeb9702452021-03-08 21:02:57 -08001757 /* -Wcast-qual is a good warning flag to use in general. This is
Maxim Zhukovd538f0a2022-12-20 20:40:38 +03001758 * the one place in UsefulBuf where it needs to be quieted.
1759 */
1760 UB.ptr = (void *)(uintptr_t)UBC.ptr;
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001761
1762 UB.len = UBC.len;
1763
1764 return UB;
Michael Eckel5c531332020-03-02 01:35:30 +01001765}
1766
1767
1768static inline UsefulBufC UsefulBuf_FromSZ(const char *szString)
1769{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001770 UsefulBufC UBC;
1771 UBC.ptr = szString;
1772 UBC.len = strlen(szString);
1773 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001774}
1775
1776
1777static inline UsefulBufC UsefulBuf_Copy(UsefulBuf Dest, const UsefulBufC Src)
1778{
1779 return UsefulBuf_CopyOffset(Dest, 0, Src);
1780}
1781
1782
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001783static inline UsefulBufC UsefulBuf_Set(UsefulBuf Dest, uint8_t value)
Michael Eckel5c531332020-03-02 01:35:30 +01001784{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001785 memset(Dest.ptr, value, Dest.len);
1786
1787 UsefulBufC UBC;
1788 UBC.ptr = Dest.ptr;
1789 UBC.len = Dest.len;
1790
1791 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001792}
1793
1794
1795static inline UsefulBufC UsefulBuf_CopyPtr(UsefulBuf Dest, const void *ptr, size_t len)
1796{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001797 UsefulBufC UBC;
1798 UBC.ptr = ptr;
1799 UBC.len = len;
1800 return UsefulBuf_Copy(Dest, UBC);
Michael Eckel5c531332020-03-02 01:35:30 +01001801}
1802
1803
1804static inline UsefulBufC UsefulBuf_Head(UsefulBufC UB, size_t uAmount)
1805{
1806 if(uAmount > UB.len) {
1807 return NULLUsefulBufC;
1808 }
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001809 UsefulBufC UBC;
1810
1811 UBC.ptr = UB.ptr;
1812 UBC.len = uAmount;
1813
1814 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001815}
1816
1817
1818static inline UsefulBufC UsefulBuf_Tail(UsefulBufC UB, size_t uAmount)
1819{
1820 UsefulBufC ReturnValue;
1821
1822 if(uAmount > UB.len) {
1823 ReturnValue = NULLUsefulBufC;
1824 } else if(UB.ptr == NULL) {
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001825 ReturnValue.ptr = NULL;
1826 ReturnValue.len = UB.len - uAmount;
Michael Eckel5c531332020-03-02 01:35:30 +01001827 } else {
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001828 ReturnValue.ptr = (const uint8_t *)UB.ptr + uAmount;
1829 ReturnValue.len = UB.len - uAmount;
Michael Eckel5c531332020-03-02 01:35:30 +01001830 }
1831
1832 return ReturnValue;
1833}
1834
1835
Laurence Lundbladecf41c522021-02-20 10:19:07 -07001836static inline size_t UsefulBuf_PointerToOffset(UsefulBufC UB, const void *p)
1837{
1838 if(UB.ptr == NULL) {
1839 return SIZE_MAX;
1840 }
1841
1842 if(p < UB.ptr) {
1843 /* given pointer is before start of buffer */
1844 return SIZE_MAX;
1845 }
1846
1847 // Cast to size_t (from ptrdiff_t) is OK because of check above
Laurence Lundbladeb9702452021-03-08 21:02:57 -08001848 const size_t uOffset = (size_t)((const uint8_t *)p - (const uint8_t *)UB.ptr);
Laurence Lundbladecf41c522021-02-20 10:19:07 -07001849
1850 if(uOffset >= UB.len) {
1851 /* given pointer is off the end of the buffer */
1852 return SIZE_MAX;
1853 }
1854
1855 return uOffset;
1856}
1857
Michael Eckel5c531332020-03-02 01:35:30 +01001858
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001859#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001860static inline uint32_t UsefulBufUtil_CopyFloatToUint32(float f)
1861{
1862 uint32_t u32;
1863 memcpy(&u32, &f, sizeof(uint32_t));
1864 return u32;
1865}
1866
1867static inline uint64_t UsefulBufUtil_CopyDoubleToUint64(double d)
1868{
1869 uint64_t u64;
1870 memcpy(&u64, &d, sizeof(uint64_t));
1871 return u64;
1872}
1873
1874static inline double UsefulBufUtil_CopyUint64ToDouble(uint64_t u64)
1875{
1876 double d;
1877 memcpy(&d, &u64, sizeof(uint64_t));
1878 return d;
1879}
1880
1881static inline float UsefulBufUtil_CopyUint32ToFloat(uint32_t u32)
1882{
1883 float f;
1884 memcpy(&f, &u32, sizeof(uint32_t));
1885 return f;
1886}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001887#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001888
1889
1890
1891
1892static inline void UsefulOutBuf_Reset(UsefulOutBuf *pMe)
1893{
1894 pMe->data_len = 0;
1895 pMe->err = 0;
1896}
1897
1898
1899static inline size_t UsefulOutBuf_GetEndPosition(UsefulOutBuf *pMe)
1900{
1901 return pMe->data_len;
1902}
1903
1904
1905static inline int UsefulOutBuf_AtStart(UsefulOutBuf *pMe)
1906{
1907 return 0 == pMe->data_len;
1908}
1909
1910
1911static inline void UsefulOutBuf_InsertData(UsefulOutBuf *pMe,
1912 const void *pBytes,
1913 size_t uLen,
1914 size_t uPos)
1915{
1916 UsefulBufC Data = {pBytes, uLen};
1917 UsefulOutBuf_InsertUsefulBuf(pMe, Data, uPos);
1918}
1919
1920
1921static inline void UsefulOutBuf_InsertString(UsefulOutBuf *pMe,
1922 const char *szString,
1923 size_t uPos)
1924{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001925 UsefulBufC UBC;
1926 UBC.ptr = szString;
1927 UBC.len = strlen(szString);
1928
1929 UsefulOutBuf_InsertUsefulBuf(pMe, UBC, uPos);
Michael Eckel5c531332020-03-02 01:35:30 +01001930}
1931
1932
1933static inline void UsefulOutBuf_InsertByte(UsefulOutBuf *me,
1934 uint8_t byte,
1935 size_t uPos)
1936{
1937 UsefulOutBuf_InsertData(me, &byte, 1, uPos);
1938}
1939
1940
1941static inline void UsefulOutBuf_InsertUint16(UsefulOutBuf *me,
1942 uint16_t uInteger16,
1943 size_t uPos)
1944{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001945 /* See UsefulOutBuf_InsertUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01001946
1947 const void *pBytes;
1948
1949#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
1950 pBytes = &uInteger16;
1951
1952#elif defined(USEFULBUF_CONFIG_HTON)
1953 uint16_t uTmp = htons(uInteger16);
1954 pBytes = &uTmp;
1955
1956#elif defined(USEFULBUF_CONFIG_LITTLE_ENDIAN) && defined(USEFULBUF_CONFIG_BSWAP)
1957 uint16_t uTmp = __builtin_bswap16(uInteger16);
1958 pBytes = &uTmp;
1959
1960#else
1961 uint8_t aTmp[2];
1962
1963 aTmp[0] = (uint8_t)((uInteger16 & 0xff00) >> 8);
1964 aTmp[1] = (uint8_t)(uInteger16 & 0xff);
1965
1966 pBytes = aTmp;
1967#endif
1968
1969 UsefulOutBuf_InsertData(me, pBytes, 2, uPos);
1970}
1971
1972
1973static inline void UsefulOutBuf_InsertUint32(UsefulOutBuf *pMe,
1974 uint32_t uInteger32,
1975 size_t uPos)
1976{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001977 /* See UsefulOutBuf_InsertUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01001978
1979 const void *pBytes;
1980
1981#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
1982 pBytes = &uInteger32;
1983
1984#elif defined(USEFULBUF_CONFIG_HTON)
1985 uint32_t uTmp = htonl(uInteger32);
1986 pBytes = &uTmp;
1987
1988#elif defined(USEFULBUF_CONFIG_LITTLE_ENDIAN) && defined(USEFULBUF_CONFIG_BSWAP)
1989 uint32_t uTmp = __builtin_bswap32(uInteger32);
1990
1991 pBytes = &uTmp;
1992
1993#else
1994 uint8_t aTmp[4];
1995
1996 aTmp[0] = (uint8_t)((uInteger32 & 0xff000000) >> 24);
1997 aTmp[1] = (uint8_t)((uInteger32 & 0xff0000) >> 16);
1998 aTmp[2] = (uint8_t)((uInteger32 & 0xff00) >> 8);
1999 aTmp[3] = (uint8_t)(uInteger32 & 0xff);
2000
2001 pBytes = aTmp;
2002#endif
2003
2004 UsefulOutBuf_InsertData(pMe, pBytes, 4, uPos);
2005}
2006
2007static inline void UsefulOutBuf_InsertUint64(UsefulOutBuf *pMe,
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002008 uint64_t uInteger64,
2009 size_t uPos)
Michael Eckel5c531332020-03-02 01:35:30 +01002010{
2011 const void *pBytes;
2012
2013#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002014 /* We have been told explicitly we are running on a big-endian
2015 * machine. Network byte order is big endian, so just copy. There
2016 * is no issue with alignment here because uInteger64 is always
2017 * aligned (and it doesn't matter if pBytes is aligned).
2018 */
Michael Eckel5c531332020-03-02 01:35:30 +01002019 pBytes = &uInteger64;
2020
2021#elif defined(USEFULBUF_CONFIG_HTON)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002022 /* Use system function to handle big- and little-endian. This works
2023 * on both big- and little-endian machines, but hton() is not
2024 * always available or in a standard place so it is not used by
2025 * default. With some compilers and CPUs the code for this is very
2026 * compact through use of a special swap instruction and on
2027 * big-endian machines hton() will reduce to nothing.
2028 */
Michael Eckel5c531332020-03-02 01:35:30 +01002029 uint64_t uTmp = htonll(uInteger64);
2030
2031 pBytes = &uTmp;
2032
2033#elif defined(USEFULBUF_CONFIG_LITTLE_ENDIAN) && defined(USEFULBUF_CONFIG_BSWAP)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002034 /* Use built-in function for byte swapping. This usually compiles
2035 * to an efficient special byte swap instruction. Unlike hton() it
2036 * does not do this conditionally on the CPU endianness, so this
2037 * code is also conditional on USEFULBUF_CONFIG_LITTLE_ENDIAN
2038 */
Michael Eckel5c531332020-03-02 01:35:30 +01002039 uint64_t uTmp = __builtin_bswap64(uInteger64);
2040
2041 pBytes = &uTmp;
2042
2043#else
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002044 /* Default which works on every CPU with no dependency on anything
2045 * from the CPU, compiler, libraries or OS. This always works, but
2046 * it is usually a little larger and slower than hton().
2047 */
Michael Eckel5c531332020-03-02 01:35:30 +01002048 uint8_t aTmp[8];
2049
2050 aTmp[0] = (uint8_t)((uInteger64 & 0xff00000000000000) >> 56);
2051 aTmp[1] = (uint8_t)((uInteger64 & 0xff000000000000) >> 48);
2052 aTmp[2] = (uint8_t)((uInteger64 & 0xff0000000000) >> 40);
2053 aTmp[3] = (uint8_t)((uInteger64 & 0xff00000000) >> 32);
2054 aTmp[4] = (uint8_t)((uInteger64 & 0xff000000) >> 24);
2055 aTmp[5] = (uint8_t)((uInteger64 & 0xff0000) >> 16);
2056 aTmp[6] = (uint8_t)((uInteger64 & 0xff00) >> 8);
2057 aTmp[7] = (uint8_t)(uInteger64 & 0xff);
2058
2059 pBytes = aTmp;
2060#endif
2061
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002062 /* Do the insert */
Michael Eckel5c531332020-03-02 01:35:30 +01002063 UsefulOutBuf_InsertData(pMe, pBytes, sizeof(uint64_t), uPos);
2064}
2065
2066
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002067#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01002068static inline void UsefulOutBuf_InsertFloat(UsefulOutBuf *pMe,
2069 float f,
2070 size_t uPos)
2071{
2072 UsefulOutBuf_InsertUint32(pMe, UsefulBufUtil_CopyFloatToUint32(f), uPos);
2073}
2074
2075
2076static inline void UsefulOutBuf_InsertDouble(UsefulOutBuf *pMe,
2077 double d,
2078 size_t uPos)
2079{
2080 UsefulOutBuf_InsertUint64(pMe, UsefulBufUtil_CopyDoubleToUint64(d), uPos);
2081}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002082#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01002083
2084
2085static inline void UsefulOutBuf_AppendUsefulBuf(UsefulOutBuf *pMe,
2086 UsefulBufC NewData)
2087{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002088 /* An append is just a insert at the end */
Michael Eckel5c531332020-03-02 01:35:30 +01002089 UsefulOutBuf_InsertUsefulBuf(pMe, NewData, UsefulOutBuf_GetEndPosition(pMe));
2090}
2091
2092
2093static inline void UsefulOutBuf_AppendData(UsefulOutBuf *pMe,
2094 const void *pBytes,
2095 size_t uLen)
2096{
2097 UsefulBufC Data = {pBytes, uLen};
2098 UsefulOutBuf_AppendUsefulBuf(pMe, Data);
2099}
2100
2101
2102static inline void UsefulOutBuf_AppendString(UsefulOutBuf *pMe,
2103 const char *szString)
2104{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07002105 UsefulBufC UBC;
2106 UBC.ptr = szString;
2107 UBC.len = strlen(szString);
2108
2109 UsefulOutBuf_AppendUsefulBuf(pMe, UBC);
Michael Eckel5c531332020-03-02 01:35:30 +01002110}
2111
2112
2113static inline void UsefulOutBuf_AppendByte(UsefulOutBuf *pMe,
2114 uint8_t byte)
2115{
2116 UsefulOutBuf_AppendData(pMe, &byte, 1);
2117}
2118
2119
2120static inline void UsefulOutBuf_AppendUint16(UsefulOutBuf *pMe,
2121 uint16_t uInteger16)
2122{
2123 UsefulOutBuf_InsertUint16(pMe, uInteger16, UsefulOutBuf_GetEndPosition(pMe));
2124}
2125
2126static inline void UsefulOutBuf_AppendUint32(UsefulOutBuf *pMe,
2127 uint32_t uInteger32)
2128{
2129 UsefulOutBuf_InsertUint32(pMe, uInteger32, UsefulOutBuf_GetEndPosition(pMe));
2130}
2131
2132
2133static inline void UsefulOutBuf_AppendUint64(UsefulOutBuf *pMe,
2134 uint64_t uInteger64)
2135{
2136 UsefulOutBuf_InsertUint64(pMe, uInteger64, UsefulOutBuf_GetEndPosition(pMe));
2137}
2138
2139
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002140#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01002141static inline void UsefulOutBuf_AppendFloat(UsefulOutBuf *pMe,
2142 float f)
2143{
2144 UsefulOutBuf_InsertFloat(pMe, f, UsefulOutBuf_GetEndPosition(pMe));
2145}
2146
2147
2148static inline void UsefulOutBuf_AppendDouble(UsefulOutBuf *pMe,
2149 double d)
2150{
2151 UsefulOutBuf_InsertDouble(pMe, d, UsefulOutBuf_GetEndPosition(pMe));
2152}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002153#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01002154
2155
2156static inline int UsefulOutBuf_GetError(UsefulOutBuf *pMe)
2157{
2158 return pMe->err;
2159}
2160
2161
2162static inline size_t UsefulOutBuf_RoomLeft(UsefulOutBuf *pMe)
2163{
2164 return pMe->UB.len - pMe->data_len;
2165}
2166
2167
2168static inline int UsefulOutBuf_WillItFit(UsefulOutBuf *pMe, size_t uLen)
2169{
2170 return uLen <= UsefulOutBuf_RoomLeft(pMe);
2171}
2172
2173
2174static inline int UsefulOutBuf_IsBufferNULL(UsefulOutBuf *pMe)
2175{
2176 return pMe->UB.ptr == NULL;
2177}
2178
2179
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06002180static inline UsefulBuf UsefulOutBuf_GetOutPlace(UsefulOutBuf *pUOutBuf)
2181{
2182 UsefulBuf R;
2183
2184 R.len = UsefulOutBuf_RoomLeft(pUOutBuf);
Paul Liétarc6cfa332022-07-26 19:24:01 +01002185 if(R.len > 0 && pUOutBuf->UB.ptr != NULL) {
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06002186 R.ptr = (uint8_t *)pUOutBuf->UB.ptr + pUOutBuf->data_len;
2187 } else {
2188 R.ptr = NULL;
2189 }
2190
2191 return R;
2192}
2193
2194
2195
Michael Eckel5c531332020-03-02 01:35:30 +01002196
2197static inline void UsefulInputBuf_Init(UsefulInputBuf *pMe, UsefulBufC UB)
2198{
2199 pMe->cursor = 0;
2200 pMe->err = 0;
2201 pMe->magic = UIB_MAGIC;
2202 pMe->UB = UB;
2203}
2204
2205static inline size_t UsefulInputBuf_Tell(UsefulInputBuf *pMe)
2206{
2207 return pMe->cursor;
2208}
2209
2210
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07002211static inline size_t UsefulInputBuf_GetBufferLength(UsefulInputBuf *pMe)
Laurence Lundblade0750fc42020-06-20 21:02:34 -07002212{
2213 return pMe->UB.len;
2214}
2215
2216
Michael Eckel5c531332020-03-02 01:35:30 +01002217static inline void UsefulInputBuf_Seek(UsefulInputBuf *pMe, size_t uPos)
2218{
2219 if(uPos > pMe->UB.len) {
2220 pMe->err = 1;
2221 } else {
2222 pMe->cursor = uPos;
2223 }
2224}
2225
2226
2227static inline size_t UsefulInputBuf_BytesUnconsumed(UsefulInputBuf *pMe)
2228{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002229 /* Code Reviewers: THIS FUNCTION DOES POINTER MATH */
Michael Eckel5c531332020-03-02 01:35:30 +01002230
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002231 /* Magic number is messed up. Either the structure got overwritten
2232 * or was never initialized.
2233 */
Michael Eckel5c531332020-03-02 01:35:30 +01002234 if(pMe->magic != UIB_MAGIC) {
2235 return 0;
2236 }
2237
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002238 /* The cursor is off the end of the input buffer given.
2239 * Presuming there are no bugs in this code, this should never happen.
2240 * If it so, the struct was corrupted. The check is retained as
2241 * as a defense in case there is a bug in this code or the struct is
2242 * corrupted.
2243 */
Michael Eckel5c531332020-03-02 01:35:30 +01002244 if(pMe->cursor > pMe->UB.len) {
2245 return 0;
2246 }
2247
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002248 /* subtraction can't go negative because of check above */
Michael Eckel5c531332020-03-02 01:35:30 +01002249 return pMe->UB.len - pMe->cursor;
2250}
2251
2252
2253static inline int UsefulInputBuf_BytesAvailable(UsefulInputBuf *pMe, size_t uLen)
2254{
2255 return UsefulInputBuf_BytesUnconsumed(pMe) >= uLen ? 1 : 0;
2256}
2257
2258
Laurence Lundbladecf41c522021-02-20 10:19:07 -07002259static inline size_t UsefulInputBuf_PointerToOffset(UsefulInputBuf *pUInBuf, const void *p)
2260{
2261 return UsefulBuf_PointerToOffset(pUInBuf->UB, p);
2262}
2263
2264
Michael Eckel5c531332020-03-02 01:35:30 +01002265static inline UsefulBufC UsefulInputBuf_GetUsefulBuf(UsefulInputBuf *pMe, size_t uNum)
2266{
2267 const void *pResult = UsefulInputBuf_GetBytes(pMe, uNum);
2268 if(!pResult) {
2269 return NULLUsefulBufC;
2270 } else {
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07002271 UsefulBufC UBC;
2272 UBC.ptr = pResult;
2273 UBC.len = uNum;
2274 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01002275 }
2276}
2277
2278
2279static inline uint8_t UsefulInputBuf_GetByte(UsefulInputBuf *pMe)
2280{
2281 const void *pResult = UsefulInputBuf_GetBytes(pMe, sizeof(uint8_t));
2282
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002283 /* The ternary operator is subject to integer promotion, because
2284 * the operands are smaller than int, so cast back to uint8_t is
2285 * needed to be completely explicit about types (for static
2286 * analyzers).
2287 */
Laurence Lundbladeb9702452021-03-08 21:02:57 -08002288 return (uint8_t)(pResult ? *(const uint8_t *)pResult : 0);
Michael Eckel5c531332020-03-02 01:35:30 +01002289}
2290
2291static inline uint16_t UsefulInputBuf_GetUint16(UsefulInputBuf *pMe)
2292{
2293 const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(pMe, sizeof(uint16_t));
2294
2295 if(!pResult) {
2296 return 0;
2297 }
2298
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002299 /* See UsefulInputBuf_GetUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01002300#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) || defined(USEFULBUF_CONFIG_HTON) || defined(USEFULBUF_CONFIG_BSWAP)
2301 uint16_t uTmp;
2302 memcpy(&uTmp, pResult, sizeof(uint16_t));
2303
2304#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
2305 return uTmp;
2306
2307#elif defined(USEFULBUF_CONFIG_HTON)
2308 return ntohs(uTmp);
2309
2310#else
2311 return __builtin_bswap16(uTmp);
2312
2313#endif
2314
2315#else
2316
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002317 /* The operations here are subject to integer promotion because the
2318 * operands are smaller than int. They will be promoted to unsigned
2319 * int for the shift and addition. The cast back to uint16_t is is
2320 * needed to be completely explicit about types (for static
2321 * analyzers).
2322 */
Michael Eckel5c531332020-03-02 01:35:30 +01002323 return (uint16_t)((pResult[0] << 8) + pResult[1]);
2324
2325#endif
2326}
2327
2328
2329static inline uint32_t UsefulInputBuf_GetUint32(UsefulInputBuf *pMe)
2330{
2331 const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(pMe, sizeof(uint32_t));
2332
2333 if(!pResult) {
2334 return 0;
2335 }
2336
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002337 /* See UsefulInputBuf_GetUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01002338#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) || defined(USEFULBUF_CONFIG_HTON) || defined(USEFULBUF_CONFIG_BSWAP)
2339 uint32_t uTmp;
2340 memcpy(&uTmp, pResult, sizeof(uint32_t));
2341
2342#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
2343 return uTmp;
2344
2345#elif defined(USEFULBUF_CONFIG_HTON)
2346 return ntohl(uTmp);
2347
2348#else
2349 return __builtin_bswap32(uTmp);
2350
2351#endif
2352
2353#else
2354 return ((uint32_t)pResult[0]<<24) +
2355 ((uint32_t)pResult[1]<<16) +
2356 ((uint32_t)pResult[2]<<8) +
2357 (uint32_t)pResult[3];
2358#endif
2359}
2360
2361
2362static inline uint64_t UsefulInputBuf_GetUint64(UsefulInputBuf *pMe)
2363{
2364 const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(pMe, sizeof(uint64_t));
2365
2366 if(!pResult) {
2367 return 0;
2368 }
2369
2370#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) || defined(USEFULBUF_CONFIG_HTON) || defined(USEFULBUF_CONFIG_BSWAP)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002371 /* pResult will probably not be aligned. This memcpy() moves the
2372 * bytes into a temp variable safely for CPUs that can or can't do
2373 * unaligned memory access. Many compilers will optimize the
2374 * memcpy() into a simple move instruction.
2375 */
Michael Eckel5c531332020-03-02 01:35:30 +01002376 uint64_t uTmp;
2377 memcpy(&uTmp, pResult, sizeof(uint64_t));
2378
2379#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002380 /* We have been told expliclity this is a big-endian CPU. Since
2381 * network byte order is big-endian, there is nothing to do.
2382 */
Michael Eckel5c531332020-03-02 01:35:30 +01002383
2384 return uTmp;
2385
2386#elif defined(USEFULBUF_CONFIG_HTON)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002387 /* We have been told to use ntoh(), the system function to handle
2388 * big- and little-endian. This works on both big- and
2389 * little-endian machines, but ntoh() is not always available or in
2390 * a standard place so it is not used by default. On some CPUs the
2391 * code for this is very compact through use of a special swap
2392 * instruction.
2393 */
Michael Eckel5c531332020-03-02 01:35:30 +01002394
2395 return ntohll(uTmp);
2396
2397#else
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002398 /* Little-endian (since it is not USEFULBUF_CONFIG_BIG_ENDIAN) and
2399 * USEFULBUF_CONFIG_BSWAP (since it is not USEFULBUF_CONFIG_HTON).
2400 * __builtin_bswap64() and friends are not conditional on CPU
2401 * endianness so this must only be used on little-endian machines.
2402 */
Michael Eckel5c531332020-03-02 01:35:30 +01002403
2404 return __builtin_bswap64(uTmp);
2405
2406
2407#endif
2408
2409#else
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002410 /* This is the default code that works on every CPU and every
2411 * endianness with no dependency on ntoh(). This works on CPUs
2412 * that either allow or do not allow unaligned access. It will
2413 * always work, but usually is a little less efficient than ntoh().
2414 */
Michael Eckel5c531332020-03-02 01:35:30 +01002415
2416 return ((uint64_t)pResult[0]<<56) +
2417 ((uint64_t)pResult[1]<<48) +
2418 ((uint64_t)pResult[2]<<40) +
2419 ((uint64_t)pResult[3]<<32) +
2420 ((uint64_t)pResult[4]<<24) +
2421 ((uint64_t)pResult[5]<<16) +
2422 ((uint64_t)pResult[6]<<8) +
2423 (uint64_t)pResult[7];
2424#endif
2425}
2426
2427
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002428#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01002429static inline float UsefulInputBuf_GetFloat(UsefulInputBuf *pMe)
2430{
2431 uint32_t uResult = UsefulInputBuf_GetUint32(pMe);
2432
2433 return uResult ? UsefulBufUtil_CopyUint32ToFloat(uResult) : 0;
2434}
2435
2436
2437static inline double UsefulInputBuf_GetDouble(UsefulInputBuf *pMe)
2438{
2439 uint64_t uResult = UsefulInputBuf_GetUint64(pMe);
2440
2441 return uResult ? UsefulBufUtil_CopyUint64ToDouble(uResult) : 0;
2442}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002443#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01002444
2445
2446static inline int UsefulInputBuf_GetError(UsefulInputBuf *pMe)
2447{
2448 return pMe->err;
2449}
2450
Laurence Lundblade24d509a2020-06-06 18:43:15 -07002451
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07002452static inline void UsefulInputBuf_SetBufferLength(UsefulInputBuf *pMe, size_t uNewLen)
Laurence Lundblade24d509a2020-06-06 18:43:15 -07002453{
2454 pMe->UB.len = uNewLen;
2455}
2456
2457
Michael Eckel5c531332020-03-02 01:35:30 +01002458#ifdef __cplusplus
2459}
2460#endif
2461
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002462#endif /* _UsefulBuf_h */
Michael Eckel5c531332020-03-02 01:35:30 +01002463
2464