blob: 8e6ce7fa69b1ffb5e049e6856fa94858395c92b5 [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 Lundbladeb24faef2022-04-26 11:03:08 -060045 4/11/2022 llundblade Add GetOutPlace and Advance to UsefulOutBuf.
Laurence Lundblade8ece3732021-09-21 21:47:23 -070046 9/21/2021 llundbla Clarify UsefulOutBuf size calculation mode
Laurence Lundblade48d8ace2021-08-19 22:00:26 -070047 8/8/2021 dthaler/llundbla Work with C++ without compiler extensions
Laurence Lundbladedabaffe2021-05-11 10:47:46 -070048 5/11/2021 llundblade Improve comments and comment formatting.
Laurence Lundbladeb9702452021-03-08 21:02:57 -080049 3/6/2021 mcr/llundblade Fix warnings related to --Wcast-qual
Laurence Lundbladecf41c522021-02-20 10:19:07 -070050 2/17/2021 llundblade Add method to go from a pointer to an offset.
Michael Eckel5c531332020-03-02 01:35:30 +010051 1/25/2020 llundblade Add some casts so static anlyzers don't complain.
52 5/21/2019 llundblade #define configs for efficient endianness handling.
53 5/16/2019 llundblade Add UsefulOutBuf_IsBufferNULL().
54 3/23/2019 llundblade Big documentation & style update. No interface
55 change.
56 3/6/2019 llundblade Add UsefulBuf_IsValue()
57 12/17/2018 llundblade Remove const from UsefulBuf and UsefulBufC .len
58 12/13/2018 llundblade Documentation improvements
59 09/18/2018 llundblade Cleaner distinction between UsefulBuf and
60 UsefulBufC.
61 02/02/18 llundbla Full support for integers in and out; fix pointer
62 alignment bug. Incompatible change: integers
63 in/out are now in network byte order.
64 08/12/17 llundbla Added UsefulOutBuf_AtStart and UsefulBuf_Find
65 06/27/17 llundbla Fix UsefulBuf_Compare() bug. Only affected
66 comparison for < or > for unequal length buffers.
67 Added UsefulBuf_Set() function.
68 05/30/17 llundbla Functions for NULL UsefulBufs and const / unconst
69 11/13/16 llundbla Initial Version.
70
71 =============================================================================*/
72
73#ifndef _UsefulBuf_h
74#define _UsefulBuf_h
75
76
77/*
Laurence Lundbladedabaffe2021-05-11 10:47:46 -070078 * Endianness Configuration
79 *
80 * This code is written so it will work correctly on big- and
81 * little-endian CPUs without configuration or any auto-detection of
82 * endianness. All code here will run correctly regardless of the
83 * endianness of the CPU it is running on.
84 *
85 * There are four C preprocessor macros that can be set with #define
86 * to explicitly configure endianness handling. Setting them can
87 * reduce code size a little and improve efficiency a little.
88 *
89 * Note that most of QCBOR is unaffected by this configuration. Its
90 * endianness handling is integrated with the code that handles
91 * alignment and preferred serialization. This configuration does
92 * affect QCBOR's (planned) implementation of integer arrays (tagged
93 * arrays) and use of the functions here to serialize or deserialize
94 * integers and floating-point values.
95 *
96 * Following is the recipe for configuring the endianness-related
97 * #defines.
98 *
99 * The first option is to not define anything. This will work fine
100 * with all CPUs, OS's and compilers. The code for encoding integers
101 * may be a little larger and slower.
102 *
103 * If your CPU is big-endian then define
104 * USEFULBUF_CONFIG_BIG_ENDIAN. This will give the most efficient code
105 * for big-endian CPUs. It will be small and efficient because there
106 * will be no byte swapping.
107 *
108 * Try defining USEFULBUF_CONFIG_HTON. This will work on most CPUs,
109 * OS's and compilers, but not all. On big-endian CPUs this should
110 * give the most efficient code, the same as
111 * USEFULBUF_CONFIG_BIG_ENDIAN does. On little-endian CPUs it should
112 * call the system-defined byte swapping method which is presumably
113 * implemented efficiently. In some cases, this will be a dedicated
114 * byte swap instruction like Intel's bswap.
115 *
116 * If USEFULBUF_CONFIG_HTON works and you know your CPU is
117 * little-endian, it is also good to define
118 * USEFULBUF_CONFIG_LITTLE_ENDIAN.
119 *
120 * if USEFULBUF_CONFIG_HTON doesn't work and you know your system is
121 * little-endian, try defining both USEFULBUF_CONFIG_LITTLE_ENDIAN and
122 * USEFULBUF_CONFIG_BSWAP. This should call the most efficient
123 * system-defined byte swap method. However, note
124 * https://hardwarebug.org/2010/01/14/beware-the-builtins/. Perhaps
125 * this is fixed now. Often hton() and ntoh() will call the built-in
126 * __builtin_bswapXX()() function, so this size issue could affect
127 * USEFULBUF_CONFIG_HTON.
128 *
129 * Last, run the tests. They must all pass.
130 *
131 * These #define config options affect the inline implementation of
132 * UsefulOutBuf_InsertUint64() and UsefulInputBuf_GetUint64(). They
133 * also affect the 16-, 32-bit, float and double versions of these
134 * functions. Since they are inline, the size effect is not in the
135 * UsefulBuf object code, but in the calling code.
136 *
137 * Summary:
138 * USEFULBUF_CONFIG_BIG_ENDIAN -- Force configuration to big-endian.
139 * USEFULBUF_CONFIG_LITTLE_ENDIAN -- Force to little-endian.
140 * USEFULBUF_CONFIG_HTON -- Use hton(), htonl(), ntohl()... to
141 * handle big and little-endian with system option.
142 * USEFULBUF_CONFIG_BSWAP -- With USEFULBUF_CONFIG_LITTLE_ENDIAN,
143 * use __builtin_bswapXX().
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200144 *
145 * It is possible to run this code in environments where using floating point is
146 * not allowed. Defining USEFULBUF_DISABLE_ALL_FLOAT will disable all the code
147 * that is related to handling floating point types, along with related
148 * interfaces. This makes it possible to compile the code with the compile
149 * option -mgeneral-regs-only.
Michael Eckel5c531332020-03-02 01:35:30 +0100150 */
151
152#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) && defined(USEFULBUF_CONFIG_LITTLE_ENDIAN)
153#error "Cannot define both USEFULBUF_CONFIG_BIG_ENDIAN and USEFULBUF_CONFIG_LITTLE_ENDIAN"
154#endif
155
156
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700157#include <stdint.h> /* for uint8_t, uint16_t.... */
158#include <string.h> /* for strlen, memcpy, memmove, memset */
159#include <stddef.h> /* for size_t */
Michael Eckel5c531332020-03-02 01:35:30 +0100160
161
162#ifdef USEFULBUF_CONFIG_HTON
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700163#include <arpa/inet.h> /* for htons, htonl, htonll, ntohs... */
Michael Eckel5c531332020-03-02 01:35:30 +0100164#endif
165
166#ifdef __cplusplus
167extern "C" {
Laurence Lundblade24d509a2020-06-06 18:43:15 -0700168#if 0
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700169} /* Keep editor indention formatting happy */
Laurence Lundblade24d509a2020-06-06 18:43:15 -0700170#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100171#endif
172
173/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700174 * @file UsefulBuf.h
175 *
176 * The goal of this code is to make buffer and pointer manipulation
177 * easier and safer when working with binary data.
178 *
179 * The @ref UsefulBuf, @ref UsefulOutBuf and @ref UsefulInputBuf
180 * structures are used to represent buffers rather than ad hoc
181 * pointers and lengths.
182 *
183 * With these it is possible to write code that does little or no
184 * direct pointer manipulation for copying and formatting data. For
185 * example, the QCBOR encoder was written using these and has less
186 * pointer manipulation.
187 *
188 * While it is true that object code using these functions will be a
189 * little larger and slower than a white-knuckle clever use of
190 * pointers might be, but not by that much or enough to have an effect
191 * for most use cases. For security-oriented code this is highly
192 * worthwhile. Clarity, simplicity, reviewability and are more
193 * important.
194 *
195 * There are some extra sanity and double checks in this code to help
196 * catch coding errors and simple memory corruption. They are helpful,
197 * but not a substitute for proper code review, input validation and
198 * such.
199 *
200 * This code consists of a lot of inline functions and a few that are
201 * not. It should not generate very much object code, especially with
202 * the optimizer turned up to @c -Os or @c -O3.
Michael Eckel5c531332020-03-02 01:35:30 +0100203 */
204
205
206/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700207 * @ref UsefulBufC and @ref UsefulBuf are simple data structures to
208 * hold a pointer and length for binary data. In C99 this data
209 * structure can be passed on the stack making a lot of code cleaner
210 * than carrying around a pointer and length as two parameters.
211 *
212 * This is also conducive to secure coding practice as the length is
213 * always carried with the pointer and the convention for handling a
214 * pointer and a length is clear.
215 *
216 * While it might be possible to write buffer and pointer code more
217 * efficiently in some use cases, the thought is that unless there is
218 * an extreme need for performance (e.g., you are building a
219 * gigabit-per-second IP router), it is probably better to have
220 * cleaner code you can be most certain about the security of.
221 *
222 * The non-const @ref UsefulBuf is usually used to refer an empty
223 * buffer to be filled in. The length is the size of the buffer.
224 *
225 * The const @ref UsefulBufC is usually used to refer to some data
226 * that has been filled in. The length is amount of valid data pointed
227 * to.
228 *
229 * A common use mode is to pass a @ref UsefulBuf to a function, the
230 * function puts some data in it, then the function returns a @ref
231 * UsefulBufC refering to the data. The @ref UsefulBuf is a non-const
232 * "in" parameter and the @ref UsefulBufC is a const "out" parameter
233 * so the constness stays correct. There is no single "in,out"
234 * parameter (if there was, it would have to be non-const). Note that
235 * the pointer returned in the @ref UsefulBufC usually ends up being
236 * the same pointer passed in as a @ref UsefulBuf, though this is not
237 * striclty required.
238 *
239 * A @ref UsefulBuf is null, it has no value, when @c ptr in it is
240 * @c NULL.
241 *
242 * There are functions and macros for the following:
243 * - Initializing
244 * - Create initialized const @ref UsefulBufC from compiler literals
245 * - Create initialized const @ref UsefulBufC from NULL-terminated string
246 * - Make an empty @ref UsefulBuf on the stack
247 * - Checking whether a @ref UsefulBuf is null, empty or both
248 * - Copying, copying with offset, copying head or tail
249 * - Comparing and finding substrings
250 *
251 * See also @ref UsefulOutBuf. It is a richer structure that has both
252 * the size of the valid data and the size of the buffer.
253 *
254 * @ref UsefulBuf is only 16 or 8 bytes on a 64- or 32-bit machine so
255 * it can go on the stack and be a function parameter or return value.
256 *
257 * Another way to look at it is this. C has the NULL-terminated string
258 * as a means for handling text strings, but no means or convention
259 * for binary strings. Other languages do have such means, Rust, an
260 * efficient compiled language, for example.
261 *
262 * @ref UsefulBuf is kind of like the Useful Pot Pooh gave Eeyore on
263 * his birthday. Eeyore's balloon fits beautifully, "it goes in and
264 * out like anything".
265 */
Michael Eckel5c531332020-03-02 01:35:30 +0100266typedef struct q_useful_buf_c {
267 const void *ptr;
268 size_t len;
269} UsefulBufC;
270
271
272/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700273 * This non-const @ref UsefulBuf is typically used for some allocated
274 * memory that is to be filled in. The @c len is the amount of memory,
275 * not the length of the valid data in the buffer.
Michael Eckel5c531332020-03-02 01:35:30 +0100276 */
277typedef struct q_useful_buf {
278 void *ptr;
279 size_t len;
280} UsefulBuf;
281
282
283/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700284 * A null @ref UsefulBufC is one that has no value in the same way a
285 * @c NULL pointer has no value. A @ref UsefulBufC is @c NULL when
286 * the @c ptr field is @c NULL. It doesn't matter what @c len is. See
287 * UsefulBuf_IsEmpty() for the distinction between null and empty.
Michael Eckel5c531332020-03-02 01:35:30 +0100288 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700289/*
290 * NULLUsefulBufC and few other macros have to be
291 * definied differently in C than C++ because there
292 * is no common construct for a literal structure.
293 *
294 * In C compound literals are used.
295 *
296 * In C++ list initalization is used. This only works
297 * in C++11 and later.
298 *
299 * Note that some popular C++ compilers can handle compound
300 * literals with on-by-default extensions, however
301 * this code aims for full correctness with strict
302 * compilers so they are not used.
303 */
304#ifdef __cplusplus
305#define NULLUsefulBufC {NULL, 0}
306#else
307#define NULLUsefulBufC ((UsefulBufC) {NULL, 0})
308#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100309
310/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700311 * A null @ref UsefulBuf is one that has no memory associated the same
312 * way @c NULL points to nothing. It does not matter what @c len is.
313 **/
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700314#ifdef __cplusplus
315#define NULLUsefulBuf {NULL, 0}
316#else
317#define NULLUsefulBuf ((UsefulBuf) {NULL, 0})
318#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100319
320
321/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700322 * @brief Check if a @ref UsefulBuf is @ref NULLUsefulBuf or not.
323 *
324 * @param[in] UB The UsefulBuf to check.
325 *
326 * @return 1 if it is @ref NULLUsefulBuf, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100327 */
328static inline int UsefulBuf_IsNULL(UsefulBuf UB);
329
330
331/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700332 * @brief Check if a @ref UsefulBufC is @ref NULLUsefulBufC or not.
333 *
334 * @param[in] UB The @ref UsefulBufC to check.
335 *
336 * @return 1 if it is @c NULLUsefulBufC, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100337 */
338static inline int UsefulBuf_IsNULLC(UsefulBufC UB);
339
340
341/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700342 * @brief Check if a @ref UsefulBuf is empty or not.
343 *
344 * @param[in] UB The @ref UsefulBuf to check.
345 *
346 * @return 1 if it is empty, 0 if not.
347 *
348 * An "empty" @ref UsefulBuf is one that has a value and can be
349 * considered to be set, but that value is of zero length. It is
350 * empty when @c len is zero. It doesn't matter what the @c ptr is.
351 *
352 * Many uses will not need to clearly distinguish a @c NULL @ref
353 * UsefulBuf from an empty one and can have the @c ptr @c NULL and the
354 * @c len 0. However if a use of @ref UsefulBuf needs to make a
355 * distinction then @c ptr should not be @c NULL when the @ref
356 * UsefulBuf is considered empty, but not @c NULL.
Michael Eckel5c531332020-03-02 01:35:30 +0100357 */
358static inline int UsefulBuf_IsEmpty(UsefulBuf UB);
359
360
361/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700362 * @brief Check if a @ref UsefulBufC is empty or not.
363 *
364 * @param[in] UB The @ref UsefulBufC to check.
365 *
366 * @return 1 if it is empty, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100367 */
368static inline int UsefulBuf_IsEmptyC(UsefulBufC UB);
369
370
371/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700372 * @brief Check if a @ref UsefulBuf is @ref NULLUsefulBuf or empty.
373 *
374 * @param[in] UB The @ref UsefulBuf to check.
375 *
376 * @return 1 if it is either @ref NULLUsefulBuf or empty, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100377 */
378static inline int UsefulBuf_IsNULLOrEmpty(UsefulBuf UB);
379
380
381/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700382 * @brief Check if a @ref UsefulBufC is @ref NULLUsefulBufC or empty.
383 *
384 * @param[in] UB The @ref UsefulBufC to check.
385 *
386 * @return 1 if it is either @ref NULLUsefulBufC or empty, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100387 */
388static inline int UsefulBuf_IsNULLOrEmptyC(UsefulBufC UB);
389
390
391/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700392 * @brief Convert a non-const @ref UsefulBuf to a const @ref UsefulBufC.
393 *
394 * @param[in] UB The @ref UsefulBuf to convert.
395 *
396 * @return A @ref UsefulBufC struct.
Michael Eckel5c531332020-03-02 01:35:30 +0100397 */
398static inline UsefulBufC UsefulBuf_Const(const UsefulBuf UB);
399
400
401/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700402 * @brief Convert a const @ref UsefulBufC to a non-const @ref UsefulBuf.
403 *
404 * @param[in] UBC The @ref UsefulBuf to convert.
405 *
406 * @return A non-const @ref UsefulBuf struct.
407 *
408 * Use of this is not necessary for the intended use mode of @ref
409 * UsefulBufC and @ref UsefulBuf. In that mode, the @ref UsefulBuf is
410 * created to describe a buffer that has not had any data put in
411 * it. Then the data is put in it. Then a @ref UsefulBufC is create
412 * to describe the part with the data in it. This goes from non-const
413 * to const, so this function is not needed.
414 *
415 * If the -Wcast-qual warning is enabled, this function can be used to
416 * avoid that warning.
Michael Eckel5c531332020-03-02 01:35:30 +0100417 */
418static inline UsefulBuf UsefulBuf_Unconst(const UsefulBufC UBC);
419
420
421/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700422 * Convert a literal string to a @ref UsefulBufC.
423 *
424 * @c szString must be a literal string that @c sizeof() works on.
425 * This is better for literal strings than UsefulBuf_FromSZ() because
426 * it generates less code. It will not work on non-literal strings.
427 *
428 * The terminating \0 (NULL) is NOT included in the length!
Michael Eckel5c531332020-03-02 01:35:30 +0100429 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700430#ifdef __cplusplus
431#define UsefulBuf_FROM_SZ_LITERAL(szString) {(szString), sizeof(szString)-1}
432#else
Michael Eckel5c531332020-03-02 01:35:30 +0100433#define UsefulBuf_FROM_SZ_LITERAL(szString) \
434 ((UsefulBufC) {(szString), sizeof(szString)-1})
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700435#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100436
437
438/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700439 * Convert a literal byte array to a @ref UsefulBufC.
440 *
441 * @c pBytes must be a literal string that @c sizeof() works on. It
442 * will not work on non-literal arrays.
Michael Eckel5c531332020-03-02 01:35:30 +0100443 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700444#ifdef __cplusplus
445#define UsefulBuf_FROM_BYTE_ARRAY_LITERAL(pBytes) {(pBytes), sizeof(pBytes)}
446#else
Michael Eckel5c531332020-03-02 01:35:30 +0100447#define UsefulBuf_FROM_BYTE_ARRAY_LITERAL(pBytes) \
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700448 ((UsefulBufC) {(pBytes), sizeof(pBytes)})
449#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100450
451/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700452 * Make an automatic variable named @c name of type @ref UsefulBuf and
453 * point it to a stack variable of the given @c size.
Michael Eckel5c531332020-03-02 01:35:30 +0100454 */
455#define UsefulBuf_MAKE_STACK_UB(name, size) \
456 uint8_t __pBuf##name[(size)];\
457 UsefulBuf name = {__pBuf##name , sizeof( __pBuf##name )}
458
459
460/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700461 * Make a byte array in to a @ref UsefulBuf. This is usually used on
462 * stack variables or static variables. Also see @ref
463 * UsefulBuf_MAKE_STACK_UB.
Michael Eckel5c531332020-03-02 01:35:30 +0100464 */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700465#ifdef __cplusplus
466#define UsefulBuf_FROM_BYTE_ARRAY(pBytes) {(pBytes), sizeof(pBytes)}
467#else
Michael Eckel5c531332020-03-02 01:35:30 +0100468#define UsefulBuf_FROM_BYTE_ARRAY(pBytes) \
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700469 ((UsefulBuf) {(pBytes), sizeof(pBytes)})
470#endif
Michael Eckel5c531332020-03-02 01:35:30 +0100471
472
473/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700474 * @brief Convert a NULL-terminated string to a @ref UsefulBufC.
475 *
476 * @param[in] szString The string to convert.
477 *
478 * @return A @ref UsefulBufC struct.
479 *
480 * @c UsefulBufC.ptr points to the string so its lifetime must be
481 * maintained.
482 *
483 * The terminating \0 (NULL) is NOT included in the length.
Michael Eckel5c531332020-03-02 01:35:30 +0100484 */
485static inline UsefulBufC UsefulBuf_FromSZ(const char *szString);
486
487
488/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700489 * @brief Copy one @ref UsefulBuf into another at an offset.
490 *
491 * @param[in] Dest Destination buffer to copy into.
492 * @param[in] uOffset The byte offset in @c Dest at which to copy to.
493 * @param[in] Src The bytes to copy.
494 *
495 * @return Pointer and length of the copy or @ref NULLUsefulBufC.
496 *
497 * This fails and returns @ref NULLUsefulBufC if @c offset is beyond the
498 * size of @c Dest.
499 *
500 * This fails and returns @ref NULLUsefulBufC if the @c Src length
501 * plus @c uOffset is greater than the length of @c Dest.
502 *
503 * The results are undefined if @c Dest and @c Src overlap.
504 *
505 * This assumes that there is valid data in @c Dest up to @c
506 * uOffset. The @ref UsefulBufC returned starts at the beginning of @c
507 * Dest and goes to @c Src.len @c + @c uOffset.
Michael Eckel5c531332020-03-02 01:35:30 +0100508 */
509UsefulBufC UsefulBuf_CopyOffset(UsefulBuf Dest, size_t uOffset, const UsefulBufC Src);
510
511
512/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700513 * @brief Copy one @ref UsefulBuf into another.
514 *
515 * @param[in] Dest The destination buffer to copy into.
516 * @param[out] Src The source to copy from.
517 *
518 * @return Filled in @ref UsefulBufC on success, @ref NULLUsefulBufC
519 * on failure.
520 *
521 * This fails if @c Src.len is greater than @c Dest.len.
522 *
523 * Note that like @c memcpy(), the pointers are not checked and this
524 * will crash rather than return @ref NULLUsefulBufC if they are @c
525 * NULL or invalid.
526 *
527 * The results are undefined if @c Dest and @c Src overlap.
Michael Eckel5c531332020-03-02 01:35:30 +0100528 */
529static inline UsefulBufC UsefulBuf_Copy(UsefulBuf Dest, const UsefulBufC Src);
530
531
532/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700533 * @brief Set all bytes in a @ref UsefulBuf to a value, for example to 0.
534 *
535 * @param[in] pDest The destination buffer to copy into.
536 * @param[in] value The value to set the bytes to.
537 *
538 * Note that like @c memset(), the pointer in @c pDest is not checked
539 * and this will crash if @c NULL or invalid.
Michael Eckel5c531332020-03-02 01:35:30 +0100540 */
541static inline UsefulBufC UsefulBuf_Set(UsefulBuf pDest, uint8_t value);
542
543
544/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700545 * @brief Copy a pointer into a @ref UsefulBuf.
546 *
547 * @param[in,out] Dest The destination buffer to copy into.
548 * @param[in] ptr The source to copy from.
549 * @param[in] uLen Length of the source; amount to copy.
550 *
551 * @return Filled in @ref UsefulBufC on success, @ref NULLUsefulBufC
552 * on failure.
553 *
554 * This fails and returns @ref NULLUsefulBufC if @c uLen is greater
555 * than @c pDest->len.
556 *
557 * Note that like @c memcpy(), the pointers are not checked and this
558 * will crash, rather than return 1 if they are @c NULL or invalid.
Michael Eckel5c531332020-03-02 01:35:30 +0100559 */
560static inline UsefulBufC UsefulBuf_CopyPtr(UsefulBuf Dest,
561 const void *ptr,
562 size_t uLen);
563
564
565/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700566 * @brief Returns a truncation of a @ref UsefulBufC.
567 *
568 * @param[in] UB The buffer to get the head of.
569 * @param[in] uAmount The number of bytes in the head.
570 *
571 * @return A @ref UsefulBufC that is the head of UB.
Michael Eckel5c531332020-03-02 01:35:30 +0100572 */
573static inline UsefulBufC UsefulBuf_Head(UsefulBufC UB, size_t uAmount);
574
575
576/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700577 * @brief Returns bytes from the end of a @ref UsefulBufC.
578 *
579 * @param[in] UB The buffer to get the tail of.
580 * @param[in] uAmount The offset from the start where the tail is to begin.
581 *
582 * @return A @ref UsefulBufC that is the tail of @c UB or @ref NULLUsefulBufC
583 * if @c uAmount is greater than the length of the @ref UsefulBufC.
584 *
585 * If @c UB.ptr is @c NULL, but @c UB.len is not zero, then the result will
586 * be a @ref UsefulBufC with a @c NULL @c ptr and @c len with the length
587 * of the tail.
Michael Eckel5c531332020-03-02 01:35:30 +0100588 */
589static inline UsefulBufC UsefulBuf_Tail(UsefulBufC UB, size_t uAmount);
590
591
592/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700593 * @brief Compare one @ref UsefulBufC to another.
594 *
595 * @param[in] UB1 The first buffer to compare.
596 * @param[in] UB2 The second buffer to compare.
597 *
598 * @return 0, positive or negative value.
599 *
600 * Returns a negative value if @c UB1 if is less than @c UB2. @c UB1 is
601 * less than @c UB2 if it is shorter or the first byte that is not the
602 * same is less.
603 *
604 * Returns 0 if the inputs are the same.
605 *
606 * Returns a positive value if @c UB2 is less than @c UB1.
607 *
608 * All that is of significance is that the result is positive, negative
609 * or 0. (This doesn't return the difference between the first
610 * non-matching byte like @c memcmp() ).
Michael Eckel5c531332020-03-02 01:35:30 +0100611 */
612int UsefulBuf_Compare(const UsefulBufC UB1, const UsefulBufC UB2);
613
614
615/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700616 * @brief Find first byte that is not a particular byte value.
617 *
618 * @param[in] UB The destination buffer for byte comparison.
619 * @param[in] uValue The byte value to compare to.
620 *
621 * @return Offset of first byte that isn't @c uValue or
622 * @c SIZE_MAX if all bytes are @c uValue.
623 *
624 * Note that unlike most comparison functions, 0
625 * does not indicate a successful comparison, so the
626 * test for match is:
627 *
628 * UsefulBuf_IsValue(...) == SIZE_MAX
629 *
630 * If @c UB is null or empty, there is no match
631 * and 0 is returned.
Michael Eckel5c531332020-03-02 01:35:30 +0100632 */
633size_t UsefulBuf_IsValue(const UsefulBufC UB, uint8_t uValue);
634
635
636/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700637 * @brief Find one @ref UsefulBufC in another.
638 *
639 * @param[in] BytesToSearch Buffer to search through.
640 * @param[in] BytesToFind Buffer with bytes to be found.
641 *
642 * @return Position of found bytes or @c SIZE_MAX if not found.
Michael Eckel5c531332020-03-02 01:35:30 +0100643 */
644size_t UsefulBuf_FindBytes(UsefulBufC BytesToSearch, UsefulBufC BytesToFind);
645
646
Laurence Lundbladecf41c522021-02-20 10:19:07 -0700647/**
648 @brief Convert a pointer to an offset with bounds checking.
649
650 @param[in] UB Pointer to the UsefulInputBuf.
651 @param[in] p Pointer to convert to offset.
652
653 @return SIZE_MAX if @c p is out of range, the byte offset if not.
654*/
655static inline size_t UsefulBuf_PointerToOffset(UsefulBufC UB, const void *p);
656
657
Laurence Lundbladeb9702452021-03-08 21:02:57 -0800658#ifndef USEFULBUF_DISABLE_DEPRECATED
Michael Eckel5c531332020-03-02 01:35:30 +0100659/** Deprecated macro; use @ref UsefulBuf_FROM_SZ_LITERAL instead */
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700660#define SZLiteralToUsefulBufC(szString) UsefulBuf_FROM_SZ_LITERAL(szString)
Michael Eckel5c531332020-03-02 01:35:30 +0100661
662/** Deprecated macro; use UsefulBuf_MAKE_STACK_UB instead */
663#define MakeUsefulBufOnStack(name, size) \
664 uint8_t __pBuf##name[(size)];\
665 UsefulBuf name = {__pBuf##name , sizeof( __pBuf##name )}
666
667/** Deprecated macro; use @ref UsefulBuf_FROM_BYTE_ARRAY_LITERAL instead */
668#define ByteArrayLiteralToUsefulBufC(pBytes) \
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700669 UsefulBuf_FROM_BYTE_ARRAY_LITERAL(pBytes)
Michael Eckel5c531332020-03-02 01:35:30 +0100670
671/** Deprecated function; use UsefulBuf_Unconst() instead */
672static inline UsefulBuf UsefulBufC_Unconst(const UsefulBufC UBC)
673{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700674 UsefulBuf UB;
675
Maxim Zhukovd538f0a2022-12-20 20:40:38 +0300676 // See UsefulBuf_Unconst() implementation for comment
677 UB.ptr = (void *)(uintptr_t)UBC.ptr;
Laurence Lundblade48d8ace2021-08-19 22:00:26 -0700678
679 UB.len = UBC.len;
680
681 return UB;
Michael Eckel5c531332020-03-02 01:35:30 +0100682}
Laurence Lundbladeb9702452021-03-08 21:02:57 -0800683#endif /* USEFULBUF_DISABLE_DEPRECATED */
Michael Eckel5c531332020-03-02 01:35:30 +0100684
685
686
687
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200688#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +0100689/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700690 * @brief Copy a @c float to a @c uint32_t.
691 *
692 * @param[in] f Float value to copy.
693 *
694 * @return A @c uint32_t with the float bits.
695 *
696 * Convenience function to avoid type punning, compiler warnings and
697 * such. The optimizer usually reduces this to a simple assignment. This
698 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100699 */
700static inline uint32_t UsefulBufUtil_CopyFloatToUint32(float f);
701
702
703/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700704 * @brief Copy a @c double to a @c uint64_t.
705 *
706 * @param[in] d Double value to copy.
707 *
708 * @return A @c uint64_t with the double bits.
709 *
710 * Convenience function to avoid type punning, compiler warnings and
711 * such. The optimizer usually reduces this to a simple assignment. This
712 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100713 */
714static inline uint64_t UsefulBufUtil_CopyDoubleToUint64(double d);
715
716
717/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700718 * @brief Copy a @c uint32_t to a @c float.
719 *
720 * @param[in] u32 Integer value to copy.
721 *
722 * @return The value as a @c float.
723 *
724 * Convenience function to avoid type punning, compiler warnings and
725 * such. The optimizer usually reduces this to a simple assignment. This
726 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100727 */
728static inline float UsefulBufUtil_CopyUint32ToFloat(uint32_t u32);
729
730
731/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700732 * @brief Copy a @c uint64_t to a @c double.
733 *
734 * @param[in] u64 Integer value to copy.
735 *
736 * @return The value as a @c double.
737 *
738 * Convenience function to avoid type punning, compiler warnings and
739 * such. The optimizer usually reduces this to a simple assignment. This
740 * is a crusty corner of C.
Michael Eckel5c531332020-03-02 01:35:30 +0100741 */
742static inline double UsefulBufUtil_CopyUint64ToDouble(uint64_t u64);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200743#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +0100744
745
746
747
748/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700749 * UsefulOutBuf is a structure and functions (an object) for
750 * serializing data into a buffer to encode for a network protocol or
751 * write data to a file.
752 *
753 * The main idea is that all the pointer manipulation is performed by
754 * @ref UsefulOutBuf functions so the caller doesn't have to do any
755 * pointer manipulation. The pointer manipulation is centralized.
756 * This code has been reviewed and written carefully so it
757 * spares the caller of much of this work and results in safer code
758 * with less effort.
759 *
760 * The @ref UsefulOutBuf methods that add data to the output buffer
761 * always check the length and will never write off the end of the
762 * output buffer. If an attempt to add data that will not fit is made,
763 * an internal error flag will be set and further attempts to add data
764 * will not do anything.
765 *
766 * There is no way to ever write off the end of that buffer when
767 * calling the @c UsefulOutBuf_AddXxx() and
768 * @c UsefulOutBuf_InsertXxx() functions.
769 *
770 * The functions to add data do not report success of failure. The
771 * caller only needs to check for an error in the final call, either
772 * UsefulOutBuf_OutUBuf() or UsefulOutBuf_CopyOut() to get the
773 * result. This makes the calling code cleaner.
774 *
775 * There is a utility function to get the error status anytime along
776 * the way for a special circumstance. There are functions to see how
777 * much room is left and see if some data will fit too, but their use
778 * is generally unnecessary.
779 *
780 * The general call flow is:
781 *
782 * - Initialize by calling @ref UsefulOutBuf_Init(). The output
783 * buffer given to it can be from the heap, stack or
784 * otherwise. @ref UsefulOutBuf_MakeOnStack is a convenience
785 * macro that makes a buffer on the stack and initializes it.
786 *
787 * - Call methods like UsefulOutBuf_InsertString(),
788 * UsefulOutBuf_AppendUint32() and UsefulOutBuf_InsertUsefulBuf()
789 * to output data. The append calls add data to the end of the
790 * valid data. The insert calls take a position argument.
791 *
792 * - Call UsefulOutBuf_OutUBuf() or UsefulOutBuf_CopyOut() to see
793 * there were no errors and to get the serialized output bytes.
794 *
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700795 * @ref UsefulOutBuf can be used in a mode to calculate the size of
796 * what would be output without actually outputting anything. This is
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700797 * useful to calculate the size of a buffer that is to be allocated to
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700798 * hold the output. See @ref SizeCalculateUsefulBuf.
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700799 *
800 * Methods like UsefulOutBuf_InsertUint64() always output in network
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700801 * byte order (big endian).
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700802 *
803 * The possible errors are:
804 *
805 * - The @ref UsefulOutBuf was not initialized or was corrupted.
806 *
807 * - An attempt was made to add data that will not fit.
808 *
809 * - An attempt was made to insert data at a position beyond the end of
810 * the buffer.
811 *
812 * - An attempt was made to insert data at a position beyond the valid
813 * data in the buffer.
814 *
815 * Some inexpensive simple sanity checks are performed before every
816 * data addition to guard against use of an uninitialized or corrupted
817 * UsefulOutBuf.
818 *
819 * @ref UsefulOutBuf has been used to create a CBOR encoder. The CBOR
820 * encoder has almost no pointer manipulation in it, is easier to
821 * read, and easier to review.
822 *
823 * A @ref UsefulOutBuf is small and can go on the stack:
824 * - 32 bytes (27 bytes plus alignment padding) on a 64-bit CPU
825 * - 16 bytes (15 bytes plus alignment padding) on a 32-bit CPU
Michael Eckel5c531332020-03-02 01:35:30 +0100826 */
827typedef struct useful_out_buf {
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700828 /* PRIVATE DATA STRUCTURE */
829 UsefulBuf UB; /* Memory that is being output to */
830 size_t data_len; /* length of the valid data, the insertion point */
831 uint16_t magic; /* Used to detect corruption and lack
832 * of initialization */
Michael Eckel5c531332020-03-02 01:35:30 +0100833 uint8_t err;
834} UsefulOutBuf;
835
836
837/**
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700838 * This is a @ref UsefulBuf value that can be passed to
839 * UsefulOutBuf_Init() to have it calculate the size of the output
840 * buffer needed. Pass this for @c Storage, call all the append and
841 * insert functions normally, then call UsefulOutBuf_OutUBuf(). The
842 * returned @ref UsefulBufC has the size.
843 *
844 * As one can see, this is just a NULL pointer and very large size.
845 * The NULL pointer tells UsefulOutputBuf to not copy any data.
846 */
847#ifdef __cplusplus
848#define SizeCalculateUsefulBuf {NULL, SIZE_MAX}
849#else
850#define SizeCalculateUsefulBuf ((UsefulBuf) {NULL, SIZE_MAX})
851#endif
852
853
854/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700855 * @brief Initialize and supply the actual output buffer.
856 *
857 * @param[out] pUOutBuf The @ref UsefulOutBuf to initialize.
858 * @param[in] Storage Buffer to output into.
859 *
860 * This initializes the @ref UsefulOutBuf with storage, sets the
861 * current position to the beginning of the buffer and clears the
862 * error state.
863 *
Laurence Lundblade8ece3732021-09-21 21:47:23 -0700864 * See @ref SizeCalculateUsefulBuf for instructions on how to
865 * initialize a @ref UsefulOutBuf to calculate the size that would be
866 * output without actually outputting.
867 *
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700868 * This must be called before the @ref UsefulOutBuf is used.
Michael Eckel5c531332020-03-02 01:35:30 +0100869 */
870void UsefulOutBuf_Init(UsefulOutBuf *pUOutBuf, UsefulBuf Storage);
871
872
873/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700874 * Convenience macro to make a @ref UsefulOutBuf on the stack and
875 * initialize it with a stack buffer of the given size. The variable
876 * will be named @c name.
Michael Eckel5c531332020-03-02 01:35:30 +0100877 */
878#define UsefulOutBuf_MakeOnStack(name, size) \
879 uint8_t __pBuf##name[(size)];\
880 UsefulOutBuf name;\
881 UsefulOutBuf_Init(&(name), (UsefulBuf){__pBuf##name, (size)});
882
883
884/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700885 * @brief Reset a @ref UsefulOutBuf for re use.
886 *
887 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf
888 *
889 * This sets the amount of data in the output buffer to none and
890 * clears the error state.
891 *
892 * The output buffer is still the same one and size as from the
893 * UsefulOutBuf_Init() call.
894 *
895 * This doesn't zero the data, just resets to 0 bytes of valid data.
Michael Eckel5c531332020-03-02 01:35:30 +0100896 */
897static inline void UsefulOutBuf_Reset(UsefulOutBuf *pUOutBuf);
898
899
900/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700901 * @brief Returns position of end of data in the @ref UsefulOutBuf.
902 *
903 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
904 *
905 * @return position of end of data.
906 *
907 * On a freshly initialized @ref UsefulOutBuf with no data added, this
908 * will return 0. After 10 bytes have been added, it will return 10
909 * and so on.
910 *
911 * Generally, there is no need to call this for most uses of @ref
912 * UsefulOutBuf.
Michael Eckel5c531332020-03-02 01:35:30 +0100913 */
914static inline size_t UsefulOutBuf_GetEndPosition(UsefulOutBuf *pUOutBuf);
915
916
917/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700918 * @brief Returns whether any data has been added to the @ref UsefulOutBuf.
919 *
920 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
921 *
922 * @return 1 if output position is at start, 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +0100923 */
924static inline int UsefulOutBuf_AtStart(UsefulOutBuf *pUOutBuf);
925
926
927/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700928 * @brief Inserts bytes into the @ref UsefulOutBuf.
929 *
930 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
931 * @param[in] NewData The bytes to insert.
932 * @param[in] uPos Index in output buffer at which to insert.
933 *
934 * @c NewData is the pointer and length for the bytes to be added to
935 * the output buffer. There must be room in the output buffer for all
936 * of @c NewData or an error will occur.
937 *
938 * The insertion point must be between 0 and the current valid
939 * data. If not, an error will occur. Appending data to the output
940 * buffer is achieved by inserting at the end of the valid data. This
941 * can be retrieved by calling UsefulOutBuf_GetEndPosition().
942 *
943 * When insertion is performed, the bytes between the insertion point
944 * and the end of data previously added to the output buffer are slid
945 * to the right to make room for the new data.
946 *
947 * Overlapping buffers are OK. @c NewData can point to data in the
948 * output buffer.
949 *
Laurence Lundblade54618d52022-12-19 21:41:55 -0700950 * NewData.len may be 0 in which case nothing will be inserted.
951 *
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700952 * If an error occurs, an error state is set in the @ref
953 * UsefulOutBuf. No error is returned. All subsequent attempts to add
954 * data will do nothing.
955 *
956 * The intended use is that all additions are made without checking
957 * for an error. The error will be taken into account when
958 * UsefulOutBuf_OutUBuf() returns @c NullUsefulBufC.
959 * UsefulOutBuf_GetError() can also be called to check for an error.
Michael Eckel5c531332020-03-02 01:35:30 +0100960 */
961void UsefulOutBuf_InsertUsefulBuf(UsefulOutBuf *pUOutBuf,
962 UsefulBufC NewData,
963 size_t uPos);
964
965
966/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700967 * @brief Insert a data buffer into the @ref UsefulOutBuf.
968 *
969 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
970 * @param[in] pBytes Pointer to the bytes to insert
971 * @param[in] uLen Length of the bytes to insert
972 * @param[in] uPos Index in output buffer at which to insert
973 *
974 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
975 * the difference being a pointer and length is passed in rather than an
976 * @ref UsefulBufC.
Michael Eckel5c531332020-03-02 01:35:30 +0100977 */
978static inline void UsefulOutBuf_InsertData(UsefulOutBuf *pUOutBuf,
979 const void *pBytes,
980 size_t uLen,
981 size_t uPos);
982
983
984/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700985 * @brief Insert a NULL-terminated string into the UsefulOutBuf.
986 *
987 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
988 * @param[in] szString NULL-terminated string to insert.
989 * @param[in] uPos Index in output buffer at which to insert.
Michael Eckel5c531332020-03-02 01:35:30 +0100990 */
991static inline void UsefulOutBuf_InsertString(UsefulOutBuf *pUOutBuf,
992 const char *szString,
993 size_t uPos);
994
995
996/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -0700997 * @brief Insert a byte into the @ref UsefulOutBuf.
998 *
999 * @param[in] pUOutBuf Pointer to the UsefulOutBuf.
1000 * @param[in] byte Bytes to insert.
1001 * @param[in] uPos Index in output buffer at which to insert.
1002 *
1003 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1004 * with the difference being a single byte is to be inserted.
Michael Eckel5c531332020-03-02 01:35:30 +01001005 */
1006static inline void UsefulOutBuf_InsertByte(UsefulOutBuf *pUOutBuf,
1007 uint8_t byte,
1008 size_t uPos);
1009
1010
1011/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001012 * @brief Insert a 16-bit integer into the @ref UsefulOutBuf.
1013 *
1014 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1015 * @param[in] uInteger16 Integer to insert.
1016 * @param[in] uPos Index in output buffer at which to insert.
1017 *
1018 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1019 * with the difference being a two-byte integer is to be inserted.
1020 *
1021 * The integer will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001022 */
1023static inline void UsefulOutBuf_InsertUint16(UsefulOutBuf *pUOutBuf,
1024 uint16_t uInteger16,
1025 size_t uPos);
1026
1027
1028/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001029 * @brief Insert a 32-bit integer into the @ref UsefulOutBuf.
1030 *
1031 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1032 * @param[in] uInteger32 Integer to insert.
1033 * @param[in] uPos Index in output buffer at which to insert.
1034 *
1035 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1036 * with the difference being a four-byte integer is to be inserted.
1037 *
1038 * The integer will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001039 */
1040static inline void UsefulOutBuf_InsertUint32(UsefulOutBuf *pUOutBuf,
1041 uint32_t uInteger32,
1042 size_t uPos);
1043
1044
1045/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001046 * @brief Insert a 64-bit integer into the @ref UsefulOutBuf.
1047 *
1048 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1049 * @param[in] uInteger64 Integer to insert.
1050 * @param[in] uPos Index in output buffer at which to insert.
1051 *
1052 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1053 * with the difference being an eight-byte integer is to be inserted.
1054 *
1055 * The integer will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001056 */
1057static inline void UsefulOutBuf_InsertUint64(UsefulOutBuf *pUOutBuf,
1058 uint64_t uInteger64,
1059 size_t uPos);
1060
1061
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001062#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001063/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001064 * @brief Insert a @c float into the @ref UsefulOutBuf.
1065 *
1066 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1067 * @param[in] f @c float to insert.
1068 * @param[in] uPos Index in output buffer at which to insert.
1069 *
1070 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1071 * with the difference being a @c float is to be inserted.
1072 *
1073 * The @c float will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001074 */
1075static inline void UsefulOutBuf_InsertFloat(UsefulOutBuf *pUOutBuf,
1076 float f,
1077 size_t uPos);
1078
1079
1080/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001081 * @brief Insert a @c double into the @ref UsefulOutBuf.
1082 *
1083 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1084 * @param[in] d @c double to insert.
1085 * @param[in] uPos Index in output buffer at which to insert.
1086 *
1087 * See UsefulOutBuf_InsertUsefulBuf() for details. This is the same
1088 * with the difference being a @c double is to be inserted.
1089 *
1090 * The @c double will be inserted in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001091 */
1092static inline void UsefulOutBuf_InsertDouble(UsefulOutBuf *pUOutBuf,
1093 double d,
1094 size_t uPos);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001095#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001096
1097
1098/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001099 * @brief Append a @ref UsefulBuf into the @ref UsefulOutBuf.
1100 *
1101 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1102 * @param[in] NewData The @ref UsefulBuf with the bytes to append.
1103 *
1104 * See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
1105 * with the insertion point at the end of the valid data.
1106 */
Michael Eckel5c531332020-03-02 01:35:30 +01001107static inline void UsefulOutBuf_AppendUsefulBuf(UsefulOutBuf *pUOutBuf,
1108 UsefulBufC NewData);
1109
1110
1111/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001112 * @brief Append bytes to the @ref UsefulOutBuf.
1113 *
1114 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1115 * @param[in] pBytes Pointer to bytes to append.
1116 * @param[in] uLen Length of @c pBytes to append.
1117 *
1118 * See UsefulOutBuf_InsertData() for details. This does the same with
1119 * the insertion point at the end of the valid data.
Michael Eckel5c531332020-03-02 01:35:30 +01001120 */
1121static inline void UsefulOutBuf_AppendData(UsefulOutBuf *pUOutBuf,
1122 const void *pBytes,
1123 size_t uLen);
1124
1125
1126/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001127 * @brief Append a NULL-terminated string to the @ref UsefulOutBuf
1128 *
1129 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1130 * @param[in] szString NULL-terminated string to append.
Michael Eckel5c531332020-03-02 01:35:30 +01001131 */
1132static inline void UsefulOutBuf_AppendString(UsefulOutBuf *pUOutBuf,
1133 const char *szString);
1134
1135
1136/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001137 * @brief Append a byte to the @ref UsefulOutBuf
1138 *
1139 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1140 * @param[in] byte Bytes to append.
1141 *
1142 * See UsefulOutBuf_InsertByte() for details. This does the same
1143 * with the insertion point at the end of the valid data.
Michael Eckel5c531332020-03-02 01:35:30 +01001144 */
1145static inline void UsefulOutBuf_AppendByte(UsefulOutBuf *pUOutBuf,
1146 uint8_t byte);
1147
1148
1149/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001150 * @brief Append an integer to the @ref UsefulOutBuf
1151 *
1152 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1153 * @param[in] uInteger16 Integer to append.
1154 *
1155 * See UsefulOutBuf_InsertUint16() for details. This does the same
1156 * with the insertion point at the end of the valid data.
1157 *
1158 * The integer will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001159 */
1160static inline void UsefulOutBuf_AppendUint16(UsefulOutBuf *pUOutBuf,
1161 uint16_t uInteger16);
1162
1163
1164/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001165 * @brief Append an integer to the @ref UsefulOutBuf
1166 *
1167 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1168 * @param[in] uInteger32 Integer to append.
1169 *
1170 * See UsefulOutBuf_InsertUint32() for details. This does the same
1171 * with the insertion point at the end of the valid data.
1172 *
1173 * The integer will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001174 */
1175static inline void UsefulOutBuf_AppendUint32(UsefulOutBuf *pUOutBuf,
1176 uint32_t uInteger32);
1177
1178
1179/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001180 * @brief Append an integer to the @ref UsefulOutBuf
1181 *
1182 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1183 * @param[in] uInteger64 Integer to append.
1184 *
1185 * See UsefulOutBuf_InsertUint64() for details. This does the same
1186 * with the insertion point at the end of the valid data.
1187 *
1188 * The integer will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001189 */
1190static inline void UsefulOutBuf_AppendUint64(UsefulOutBuf *pUOutBuf,
1191 uint64_t uInteger64);
1192
1193
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001194#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001195/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001196 * @brief Append a @c float to the @ref UsefulOutBuf
1197 *
1198 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1199 * @param[in] f @c float to append.
1200 *
1201 * See UsefulOutBuf_InsertFloat() for details. This does the same with
1202 * the insertion point at the end of the valid data.
1203 *
1204 * The float will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001205 */
1206static inline void UsefulOutBuf_AppendFloat(UsefulOutBuf *pUOutBuf,
1207 float f);
1208
1209
1210/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001211 * @brief Append a @c double to the @ref UsefulOutBuf
1212 *
1213 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1214 * @param[in] d @c double to append.
1215 *
1216 * See UsefulOutBuf_InsertDouble() for details. This does the same
1217 * with the insertion point at the end of the valid data.
1218 *
1219 * The double will be appended in network byte order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001220 */
1221static inline void UsefulOutBuf_AppendDouble(UsefulOutBuf *pUOutBuf,
1222 double d);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001223#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001224
1225
1226/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001227 * @brief Returns the current error status.
1228 *
1229 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1230 *
1231 * @return 0 if all OK, 1 on error.
1232 *
1233 * This returns the error status since a call to either
1234 * UsefulOutBuf_Reset() of UsefulOutBuf_Init(). Once a @ref UsefulOutBuf
1235 * goes into the error state, it will stay until one of those
1236 * functions is called.
1237 *
1238 * Possible error conditions are:
1239 * - bytes to be inserted will not fit
1240 * - insertion point is out of buffer or past valid data
1241 * - current position is off end of buffer (probably corrupted or uninitialized)
1242 * - detect corruption / uninitialized by bad magic number
Michael Eckel5c531332020-03-02 01:35:30 +01001243 */
1244static inline int UsefulOutBuf_GetError(UsefulOutBuf *pUOutBuf);
1245
1246
1247/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001248 * @brief Returns number of bytes unused used in the output buffer.
1249 *
1250 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1251 *
1252 * @return Number of unused bytes or zero.
1253 *
1254 * Because of the error handling strategy and checks in
1255 * UsefulOutBuf_InsertUsefulBuf() it is usually not necessary to use
1256 * this.
Michael Eckel5c531332020-03-02 01:35:30 +01001257 */
1258static inline size_t UsefulOutBuf_RoomLeft(UsefulOutBuf *pUOutBuf);
1259
1260
1261/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001262 *@brief Returns 1 if some number of bytes will fit in the @ref UsefulOutBuf.
1263 *
1264 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf
1265 * @param[in] uLen Number of bytes for which to check
1266 *
1267 * @return 1 if @c uLen bytes will fit, 0 if not.
1268 *
1269 * Because of the error handling strategy and checks in
1270 * UsefulOutBuf_InsertUsefulBuf() it is usually not necessary to use
1271 * this.
Michael Eckel5c531332020-03-02 01:35:30 +01001272 */
1273static inline int UsefulOutBuf_WillItFit(UsefulOutBuf *pUOutBuf, size_t uLen);
1274
1275
1276 /**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001277 * @brief Returns 1 if buffer given to UsefulOutBuf_Init() was @c NULL.
1278 *
1279 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf
1280 *
1281 * @return 1 if buffer given to UsefulOutBuf_Init() was @c NULL.
1282 *
1283 * Giving a @c NULL output buffer to UsefulOutBuf_Init() is used when
1284 * just calculating the length of the encoded data.
1285 */
Michael Eckel5c531332020-03-02 01:35:30 +01001286static inline int UsefulOutBuf_IsBufferNULL(UsefulOutBuf *pUOutBuf);
1287
1288
1289/**
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001290 * @brief Returns pointer and length of the output buffer not yet used.
1291 *
1292 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1293 *
1294 * @return pointer and length of output buffer not used.
1295 *
1296 * This is an escape that allows the caller to write directly
1297 * to the output buffer without any checks. This doesn't
1298 * change the output buffer or state. It just returns a pointer
1299 * and length of the bytes remaining.
1300 *
1301 * This is useful to avoid having the bytes to be added all
1302 * in a contiguous buffer. Its use can save memory. A good
1303 * example is in the COSE encrypt implementation where
1304 * the output of the symmetric cipher can go directly
1305 * into the output buffer, rather than having to go into
1306 * an intermediate buffer.
1307 *
1308 * See UsefulOutBuf_Advance() which is used to tell
1309 * UsefulOutBuf how much was written.
1310 *
1311 * Warning: this bypasses the buffer safety provided by
1312 * UsefulOutBuf!
1313 */
1314static inline UsefulBuf
1315UsefulOutBuf_GetOutPlace(UsefulOutBuf *pUOutBuf);
1316
1317
1318/**
1319 * @brief Advance the amount output assuming it was written by the caller.
1320 *
1321 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1322 * @param[in] uAmount The amount to advance.
1323 *
1324 * This advances the position in the output buffer
1325 * by \c uAmount. This assumes that the
1326 * caller has written \c uAmount to the pointer obtained
1327 * with UsefulOutBuf_GetOutPlace().
1328 *
1329 * Warning: this bypasses the buffer safety provided by
1330 * UsefulOutBuf!
1331 */
1332void
1333UsefulOutBuf_Advance(UsefulOutBuf *pUOutBuf, size_t uAmount);
1334
1335
1336/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001337 * @brief Returns the resulting valid data in a UsefulOutBuf
1338 *
1339 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1340 *
1341 * @return The valid data in @ref UsefulOutBuf or
1342 * @ref NULLUsefulBufC if there was an error adding data.
1343 *
1344 * The storage for the returned data is the @c Storage parameter
1345 * passed to UsefulOutBuf_Init(). See also UsefulOutBuf_CopyOut().
1346 *
1347 * This can be called anytime and many times to get intermediate
1348 * results. It doesn't change the data or reset the current position,
1349 * so further data can be added.
Michael Eckel5c531332020-03-02 01:35:30 +01001350 */
1351UsefulBufC UsefulOutBuf_OutUBuf(UsefulOutBuf *pUOutBuf);
1352
1353
1354/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001355 * @brief Copies the valid data into a supplied buffer
1356 *
1357 * @param[in] pUOutBuf Pointer to the @ref UsefulOutBuf.
1358 * @param[out] Dest The destination buffer to copy into.
1359 *
1360 * @return Pointer and length of copied data or @c NULLUsefulBufC
1361 * if it will not fit in the @c Dest buffer or the error
1362 * state was entered.
1363 *
1364 * This is the same as UsefulOutBuf_OutUBuf() except it copies the
1365 * data to @c Dest.
1366 */
Michael Eckel5c531332020-03-02 01:35:30 +01001367UsefulBufC UsefulOutBuf_CopyOut(UsefulOutBuf *pUOutBuf, UsefulBuf Dest);
1368
1369
1370
1371
1372/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001373 * @ref UsefulInputBuf is the counterpart to @ref UsefulOutBuf. It is
1374 * for parsing data received. Initialize it with the data from the
1375 * network. Then use the functions like UsefulInputBuf_GetBytes() to
1376 * get data chunks of various types. A position cursor is maintained
1377 * internally.
1378 *
1379 * As long as the functions here are used, there will never be any
1380 * reference off the end of the given buffer (except
1381 * UsefulInputBuf_SetBufferLength()). This is true even if they are
1382 * called incorrectly, an attempt is made to seek off the end of the
1383 * buffer or such. This makes it easier to write safe and correct
1384 * code. For example, the QCBOR decoder implementation is safer and
1385 * easier to review through its use of @ref UsefulInputBuf.
1386 *
1387 * @ref UsefulInputBuf maintains an internal error state. The
1388 * intended use is fetching data chunks without any error checks until
1389 * the end. If there was any error, such as an attempt to fetch data
1390 * off the end, the error state is entered and no further data will be
1391 * returned. In the error state the @c UsefulInputBuf_GetXxxx()
1392 * functions return 0, or @c NULL or @ref NULLUsefulBufC. As long as
1393 * null is not dereferenced, the error check can be put off until the
1394 * end, simplifying the calling code.
1395 *
1396 * The integer and float parsing expects network byte order (big
1397 * endian). Network byte order is what is used by TCP/IP, CBOR and
1398 * most internet protocols.
1399 *
1400 * Lots of inline functions are used to keep code size down. The
1401 * optimizer, particularly with the @c -Os or @c -O3, also reduces
1402 * code size a lot. The only non-inline code is
1403 * UsefulInputBuf_GetBytes(). It is less than 100 bytes so use of
1404 * @ref UsefulInputBuf doesn't add much code for all the messy
1405 * hard-to-get right issues with parsing binary protocols in C that it
1406 * solves.
1407 *
1408 * The parse context size is:
1409 * - 64-bit machine: 16 + 8 + 2 + 1 (+ 5 bytes padding to align) = 32 bytes
1410 * - 32-bit machine: 8 + 4 + 2 + 1 (+ 1 byte padding to align) = 16 bytes
Michael Eckel5c531332020-03-02 01:35:30 +01001411 */
1412typedef struct useful_input_buf {
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001413 /* PRIVATE DATA STRUCTURE */
1414 UsefulBufC UB; /* Data being parsed */
1415 size_t cursor; /* Current offset in data being parse */
1416 uint16_t magic; /* Check for corrupted or uninitialized UsefulInputBuf */
1417 uint8_t err; /* Set request goes off end or magic number is bad */
Michael Eckel5c531332020-03-02 01:35:30 +01001418} UsefulInputBuf;
1419
1420#define UIB_MAGIC (0xB00F)
1421
1422
1423/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001424 * @brief Initialize the @ref UsefulInputBuf structure before use.
1425 *
1426 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1427 * @param[in] UB The data to parse.
Michael Eckel5c531332020-03-02 01:35:30 +01001428 */
1429static inline void UsefulInputBuf_Init(UsefulInputBuf *pUInBuf, UsefulBufC UB);
1430
1431
1432/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001433 * @brief Returns current position in input buffer.
1434 *
1435 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1436 *
1437 * @return Integer position of the cursor.
1438 *
1439 * The position that the next bytes will be returned from.
Michael Eckel5c531332020-03-02 01:35:30 +01001440 */
1441static size_t UsefulInputBuf_Tell(UsefulInputBuf *pUInBuf);
1442
1443
1444/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001445 * @brief Sets the current position in input buffer.
1446 *
1447 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1448 * @param[in] uPos Position to set to.
1449 *
1450 * If the position is off the end of the input buffer, the error state
1451 * is entered.
1452 *
1453 * Seeking to a valid position in the buffer will not reset the error
1454 * state. Only re-initialization will do that.
Michael Eckel5c531332020-03-02 01:35:30 +01001455 */
1456static void UsefulInputBuf_Seek(UsefulInputBuf *pUInBuf, size_t uPos);
1457
1458
1459/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001460 * @brief Returns the number of bytes from the cursor to the end of the buffer,
1461 * the unconsumed bytes.
1462 *
1463 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1464 *
1465 * @return Number of bytes unconsumed or 0 on error.
1466 *
1467 * Returns 0 if the cursor is invalid or corruption of the
1468 * @ref UsefulInputBuf structure is detected.
Michael Eckel5c531332020-03-02 01:35:30 +01001469 */
1470static size_t UsefulInputBuf_BytesUnconsumed(UsefulInputBuf *pUInBuf);
1471
1472
1473/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001474 * @brief Check if there are unconsumed bytes.
1475 *
1476 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1477 * @param[in] uLen Number of bytes to check availability for.
1478 *
1479 * @return 1 if @c uLen bytes are available after the cursor, and 0 if not.
Michael Eckel5c531332020-03-02 01:35:30 +01001480 */
1481static int UsefulInputBuf_BytesAvailable(UsefulInputBuf *pUInBuf, size_t uLen);
1482
1483
1484/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001485 * @brief Convert a pointer to an offset with bounds checking.
1486 *
1487 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1488 * @param[in] p Pointer to convert to offset.
1489 *
1490 * @return SIZE_MAX if @c p is out of range, the byte offset if not.
1491 */
Laurence Lundbladecf41c522021-02-20 10:19:07 -07001492static inline size_t UsefulInputBuf_PointerToOffset(UsefulInputBuf *pUInBuf, const void *p);
1493
1494
1495/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001496 * @brief Get pointer to bytes out of the input buffer.
1497 *
1498 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1499 * @param[in] uNum Number of bytes to get.
1500 *
1501 * @return Pointer to bytes.
1502 *
1503 * This consumes @c uNum bytes from the input buffer. This returns a
1504 * pointer to the start of the @c uNum bytes.
1505 *
1506 * If there are not @c uNum bytes in the input buffer, @c NULL will be
1507 * returned and the error state is entered.
1508 *
1509 * This advances the position cursor by @c uNum bytes.
Michael Eckel5c531332020-03-02 01:35:30 +01001510 */
1511const void * UsefulInputBuf_GetBytes(UsefulInputBuf *pUInBuf, size_t uNum);
1512
1513
1514/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001515 * @brief Get @ref UsefulBuf out of the input buffer.
1516 *
1517 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1518 * @param[in] uNum Number of bytes to get.
1519 *
1520 * @return A @ref UsefulBufC with ptr and length of bytes consumed.
1521 *
1522 * This consumes @c uNum bytes from the input buffer and returns the
1523 * pointer and length for them as a @ref UsefulBufC. The length
1524 * returned will always be @c uNum. The position cursor is advanced by
1525 * @c uNum bytes.
1526 *
1527 * If there are not @c uNum bytes in the input buffer, @ref
1528 * NULLUsefulBufC will be returned and the error state is entered.
Michael Eckel5c531332020-03-02 01:35:30 +01001529 */
1530static inline UsefulBufC UsefulInputBuf_GetUsefulBuf(UsefulInputBuf *pUInBuf, size_t uNum);
1531
1532
1533/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001534 * @brief Get a byte out of the input buffer.
1535 *
1536 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1537 *
1538 * @return The byte.
1539 *
1540 * This consumes 1 byte from the input buffer, returns it and advances
1541 * the position cursor by 1.
1542 *
1543 * If there is not 1 byte in the buffer, 0 will be returned for the
1544 * byte and the error state is entered. To know if the 0 returned was
1545 * in error or the real value, the error state must be checked. If
1546 * possible, put this off until all values are retrieved to have
1547 * smaller and simpler code, but if not possible
1548 * UsefulInputBuf_GetError() can be called. Also, in the error state
1549 * UsefulInputBuf_GetBytes() returns @c NULL *or the @c ptr from
1550 * UsefulInputBuf_GetUsefulBuf() is @c NULL.
Michael Eckel5c531332020-03-02 01:35:30 +01001551 */
1552static inline uint8_t UsefulInputBuf_GetByte(UsefulInputBuf *pUInBuf);
1553
1554
1555/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001556 * @brief Get a @c uint16_t out of the input buffer.
1557 *
1558 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1559 *
1560 * @return The @c uint16_t.
1561 *
1562 * See UsefulInputBuf_GetByte(). This works the same, except it returns
1563 * a @c uint16_t and two bytes are consumed.
1564 *
1565 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001566 */
1567static inline uint16_t UsefulInputBuf_GetUint16(UsefulInputBuf *pUInBuf);
1568
1569
1570/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001571 * @brief Get a @c uint32_t out of the input buffer.
1572 *
1573 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1574 *
1575 * @return The @c uint32_t.
1576 *
1577 * See UsefulInputBuf_GetByte(). This works the same, except it
1578 * returns a @c uint32_t and four bytes are consumed.
1579 *
1580 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001581 */
1582static uint32_t UsefulInputBuf_GetUint32(UsefulInputBuf *pUInBuf);
1583
1584
1585/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001586 * @brief Get a @c uint64_t out of the input buffer.
1587 *
1588 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1589 *
1590 * @return The uint64_t.
1591 *
1592 * See UsefulInputBuf_GetByte(). This works the same, except it returns
1593 * a @c uint64_t and eight bytes are consumed.
1594 *
1595 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001596 */
1597static uint64_t UsefulInputBuf_GetUint64(UsefulInputBuf *pUInBuf);
1598
1599
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001600#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001601/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001602 * @brief Get a float out of the input buffer.
1603 *
1604 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1605 *
1606 * @return The float.
1607 *
1608 * See UsefulInputBuf_GetByte(). This works the same, except it
1609 * returns a float and four bytes are consumed.
1610 *
1611 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001612 */
1613static float UsefulInputBuf_GetFloat(UsefulInputBuf *pUInBuf);
1614
1615
1616/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001617 * @brief Get a double out of the input buffer.
1618 *
1619 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1620 *
1621 * @return The double.
1622 *
1623 * See UsefulInputBuf_GetByte(). This works the same, except it
1624 * returns a double and eight bytes are consumed.
1625 *
1626 * The input bytes are interpreted in network order (big endian).
Michael Eckel5c531332020-03-02 01:35:30 +01001627 */
1628static double UsefulInputBuf_GetDouble(UsefulInputBuf *pUInBuf);
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001629#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001630
1631
1632/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001633 * @brief Get the error status.
1634 *
1635 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1636 *
1637 * @return 0 if not in the error state, 1 if in the error state.
1638 *
1639 * This returns whether the @ref UsefulInputBuf is in the
1640 * error state or not.
1641 *
1642 * The error state is entered for one of these reasons:
1643 * - Attempt to fetch data past the end of the buffer
1644 * - Attempt to seek to a position past the end of the buffer
1645 * - Attempt to get data from an uninitialized or corrupt instance
1646 * of @ref UsefulInputBuf
1647 *
1648 * Once in the error state, it can only be cleared by calling
1649 * UsefulInputBuf_Init().
1650 *
1651 * For many use cases, it is possible to only call this once after all
1652 * the @c UsefulInputBuf_GetXxxx() calls have been made. This is
1653 * possible if no reference to the data returned are needed before the
1654 * error state is checked.
1655 *
1656 * In some cases UsefulInputBuf_GetUsefulBuf() or
1657 * UsefulInputBuf_GetBytes() can stand in for this because they return
1658 * @c NULL if the error state has been entered. (The others can't stand
1659 * in because they don't return a clearly distinct error value.)
Michael Eckel5c531332020-03-02 01:35:30 +01001660 */
1661static int UsefulInputBuf_GetError(UsefulInputBuf *pUInBuf);
1662
1663
Laurence Lundblade24d509a2020-06-06 18:43:15 -07001664/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001665 * @brief Gets the input buffer length.
1666 *
1667 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1668 *
1669 * @return The length of the input buffer.
1670 *
1671 * This returns the length of the input buffer set by
1672 * UsefulInputBuf_Init() or UsefulInputBuf_SetBufferLength().
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07001673 */
1674static inline size_t UsefulInputBuf_GetBufferLength(UsefulInputBuf *pUInBuf);
1675
1676
1677/**
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001678 * @brief Alters the input buffer length (use with caution).
1679 *
1680 * @param[in] pUInBuf Pointer to the @ref UsefulInputBuf.
1681 * @param[in] uNewLen The new length of the input buffer.
1682 *
1683 * This alters the internal remembered length of the input buffer set
1684 * when UsefulInputBuf_Init() was called.
1685 *
1686 * The new length given here should always be equal to or less than
1687 * the length given when UsefulInputBuf_Init() was called. Making it
1688 * larger allows @ref UsefulInputBuf to run off the input buffer.
1689 *
1690 * The typical use is to set a length shorter than that when
1691 * initialized to constrain parsing. If
1692 * UsefulInputBuf_GetBufferLength() was called before this, then the
1693 * original length can be restored with another call to this.
1694 *
1695 * This should be used with caution. It is the only
1696 * @ref UsefulInputBuf method that can violate the safety of input
1697 * buffer parsing.
Laurence Lundblade24d509a2020-06-06 18:43:15 -07001698 */
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07001699static void UsefulInputBuf_SetBufferLength(UsefulInputBuf *pUInBuf, size_t uNewLen);
Michael Eckel5c531332020-03-02 01:35:30 +01001700
1701
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001702
1703
Michael Eckel5c531332020-03-02 01:35:30 +01001704/*----------------------------------------------------------
1705 Inline implementations.
1706 */
1707static inline int UsefulBuf_IsNULL(UsefulBuf UB)
1708{
1709 return !UB.ptr;
1710}
1711
1712
1713static inline int UsefulBuf_IsNULLC(UsefulBufC UB)
1714{
1715 return !UB.ptr;
1716}
1717
1718
1719static inline int UsefulBuf_IsEmpty(UsefulBuf UB)
1720{
1721 return !UB.len;
1722}
1723
1724
1725static inline int UsefulBuf_IsEmptyC(UsefulBufC UB)
1726{
1727 return !UB.len;
1728}
1729
1730
1731static inline int UsefulBuf_IsNULLOrEmpty(UsefulBuf UB)
1732{
1733 return UsefulBuf_IsEmpty(UB) || UsefulBuf_IsNULL(UB);
1734}
1735
1736
1737static inline int UsefulBuf_IsNULLOrEmptyC(UsefulBufC UB)
1738{
1739 return UsefulBuf_IsEmptyC(UB) || UsefulBuf_IsNULLC(UB);
1740}
1741
1742
1743static inline UsefulBufC UsefulBuf_Const(const UsefulBuf UB)
1744{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001745 UsefulBufC UBC;
1746 UBC.ptr = UB.ptr;
1747 UBC.len = UB.len;
1748
1749 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001750}
1751
Michael Eckel5c531332020-03-02 01:35:30 +01001752static inline UsefulBuf UsefulBuf_Unconst(const UsefulBufC UBC)
1753{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001754 UsefulBuf UB;
1755
Laurence Lundbladeb9702452021-03-08 21:02:57 -08001756 /* -Wcast-qual is a good warning flag to use in general. This is
Maxim Zhukovd538f0a2022-12-20 20:40:38 +03001757 * the one place in UsefulBuf where it needs to be quieted.
1758 */
1759 UB.ptr = (void *)(uintptr_t)UBC.ptr;
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001760
1761 UB.len = UBC.len;
1762
1763 return UB;
Michael Eckel5c531332020-03-02 01:35:30 +01001764}
1765
1766
1767static inline UsefulBufC UsefulBuf_FromSZ(const char *szString)
1768{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001769 UsefulBufC UBC;
1770 UBC.ptr = szString;
1771 UBC.len = strlen(szString);
1772 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001773}
1774
1775
1776static inline UsefulBufC UsefulBuf_Copy(UsefulBuf Dest, const UsefulBufC Src)
1777{
1778 return UsefulBuf_CopyOffset(Dest, 0, Src);
1779}
1780
1781
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001782static inline UsefulBufC UsefulBuf_Set(UsefulBuf Dest, uint8_t value)
Michael Eckel5c531332020-03-02 01:35:30 +01001783{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001784 memset(Dest.ptr, value, Dest.len);
1785
1786 UsefulBufC UBC;
1787 UBC.ptr = Dest.ptr;
1788 UBC.len = Dest.len;
1789
1790 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001791}
1792
1793
1794static inline UsefulBufC UsefulBuf_CopyPtr(UsefulBuf Dest, const void *ptr, size_t len)
1795{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001796 UsefulBufC UBC;
1797 UBC.ptr = ptr;
1798 UBC.len = len;
1799 return UsefulBuf_Copy(Dest, UBC);
Michael Eckel5c531332020-03-02 01:35:30 +01001800}
1801
1802
1803static inline UsefulBufC UsefulBuf_Head(UsefulBufC UB, size_t uAmount)
1804{
1805 if(uAmount > UB.len) {
1806 return NULLUsefulBufC;
1807 }
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001808 UsefulBufC UBC;
1809
1810 UBC.ptr = UB.ptr;
1811 UBC.len = uAmount;
1812
1813 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01001814}
1815
1816
1817static inline UsefulBufC UsefulBuf_Tail(UsefulBufC UB, size_t uAmount)
1818{
1819 UsefulBufC ReturnValue;
1820
1821 if(uAmount > UB.len) {
1822 ReturnValue = NULLUsefulBufC;
1823 } else if(UB.ptr == NULL) {
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001824 ReturnValue.ptr = NULL;
1825 ReturnValue.len = UB.len - uAmount;
Michael Eckel5c531332020-03-02 01:35:30 +01001826 } else {
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001827 ReturnValue.ptr = (const uint8_t *)UB.ptr + uAmount;
1828 ReturnValue.len = UB.len - uAmount;
Michael Eckel5c531332020-03-02 01:35:30 +01001829 }
1830
1831 return ReturnValue;
1832}
1833
1834
Laurence Lundbladecf41c522021-02-20 10:19:07 -07001835static inline size_t UsefulBuf_PointerToOffset(UsefulBufC UB, const void *p)
1836{
1837 if(UB.ptr == NULL) {
1838 return SIZE_MAX;
1839 }
1840
1841 if(p < UB.ptr) {
1842 /* given pointer is before start of buffer */
1843 return SIZE_MAX;
1844 }
1845
1846 // Cast to size_t (from ptrdiff_t) is OK because of check above
Laurence Lundbladeb9702452021-03-08 21:02:57 -08001847 const size_t uOffset = (size_t)((const uint8_t *)p - (const uint8_t *)UB.ptr);
Laurence Lundbladecf41c522021-02-20 10:19:07 -07001848
1849 if(uOffset >= UB.len) {
1850 /* given pointer is off the end of the buffer */
1851 return SIZE_MAX;
1852 }
1853
1854 return uOffset;
1855}
1856
Michael Eckel5c531332020-03-02 01:35:30 +01001857
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001858#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01001859static inline uint32_t UsefulBufUtil_CopyFloatToUint32(float f)
1860{
1861 uint32_t u32;
1862 memcpy(&u32, &f, sizeof(uint32_t));
1863 return u32;
1864}
1865
1866static inline uint64_t UsefulBufUtil_CopyDoubleToUint64(double d)
1867{
1868 uint64_t u64;
1869 memcpy(&u64, &d, sizeof(uint64_t));
1870 return u64;
1871}
1872
1873static inline double UsefulBufUtil_CopyUint64ToDouble(uint64_t u64)
1874{
1875 double d;
1876 memcpy(&d, &u64, sizeof(uint64_t));
1877 return d;
1878}
1879
1880static inline float UsefulBufUtil_CopyUint32ToFloat(uint32_t u32)
1881{
1882 float f;
1883 memcpy(&f, &u32, sizeof(uint32_t));
1884 return f;
1885}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02001886#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01001887
1888
1889
1890
1891static inline void UsefulOutBuf_Reset(UsefulOutBuf *pMe)
1892{
1893 pMe->data_len = 0;
1894 pMe->err = 0;
1895}
1896
1897
1898static inline size_t UsefulOutBuf_GetEndPosition(UsefulOutBuf *pMe)
1899{
1900 return pMe->data_len;
1901}
1902
1903
1904static inline int UsefulOutBuf_AtStart(UsefulOutBuf *pMe)
1905{
1906 return 0 == pMe->data_len;
1907}
1908
1909
1910static inline void UsefulOutBuf_InsertData(UsefulOutBuf *pMe,
1911 const void *pBytes,
1912 size_t uLen,
1913 size_t uPos)
1914{
1915 UsefulBufC Data = {pBytes, uLen};
1916 UsefulOutBuf_InsertUsefulBuf(pMe, Data, uPos);
1917}
1918
1919
1920static inline void UsefulOutBuf_InsertString(UsefulOutBuf *pMe,
1921 const char *szString,
1922 size_t uPos)
1923{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07001924 UsefulBufC UBC;
1925 UBC.ptr = szString;
1926 UBC.len = strlen(szString);
1927
1928 UsefulOutBuf_InsertUsefulBuf(pMe, UBC, uPos);
Michael Eckel5c531332020-03-02 01:35:30 +01001929}
1930
1931
1932static inline void UsefulOutBuf_InsertByte(UsefulOutBuf *me,
1933 uint8_t byte,
1934 size_t uPos)
1935{
1936 UsefulOutBuf_InsertData(me, &byte, 1, uPos);
1937}
1938
1939
1940static inline void UsefulOutBuf_InsertUint16(UsefulOutBuf *me,
1941 uint16_t uInteger16,
1942 size_t uPos)
1943{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001944 /* See UsefulOutBuf_InsertUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01001945
1946 const void *pBytes;
1947
1948#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
1949 pBytes = &uInteger16;
1950
1951#elif defined(USEFULBUF_CONFIG_HTON)
1952 uint16_t uTmp = htons(uInteger16);
1953 pBytes = &uTmp;
1954
1955#elif defined(USEFULBUF_CONFIG_LITTLE_ENDIAN) && defined(USEFULBUF_CONFIG_BSWAP)
1956 uint16_t uTmp = __builtin_bswap16(uInteger16);
1957 pBytes = &uTmp;
1958
1959#else
1960 uint8_t aTmp[2];
1961
1962 aTmp[0] = (uint8_t)((uInteger16 & 0xff00) >> 8);
1963 aTmp[1] = (uint8_t)(uInteger16 & 0xff);
1964
1965 pBytes = aTmp;
1966#endif
1967
1968 UsefulOutBuf_InsertData(me, pBytes, 2, uPos);
1969}
1970
1971
1972static inline void UsefulOutBuf_InsertUint32(UsefulOutBuf *pMe,
1973 uint32_t uInteger32,
1974 size_t uPos)
1975{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07001976 /* See UsefulOutBuf_InsertUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01001977
1978 const void *pBytes;
1979
1980#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
1981 pBytes = &uInteger32;
1982
1983#elif defined(USEFULBUF_CONFIG_HTON)
1984 uint32_t uTmp = htonl(uInteger32);
1985 pBytes = &uTmp;
1986
1987#elif defined(USEFULBUF_CONFIG_LITTLE_ENDIAN) && defined(USEFULBUF_CONFIG_BSWAP)
1988 uint32_t uTmp = __builtin_bswap32(uInteger32);
1989
1990 pBytes = &uTmp;
1991
1992#else
1993 uint8_t aTmp[4];
1994
1995 aTmp[0] = (uint8_t)((uInteger32 & 0xff000000) >> 24);
1996 aTmp[1] = (uint8_t)((uInteger32 & 0xff0000) >> 16);
1997 aTmp[2] = (uint8_t)((uInteger32 & 0xff00) >> 8);
1998 aTmp[3] = (uint8_t)(uInteger32 & 0xff);
1999
2000 pBytes = aTmp;
2001#endif
2002
2003 UsefulOutBuf_InsertData(pMe, pBytes, 4, uPos);
2004}
2005
2006static inline void UsefulOutBuf_InsertUint64(UsefulOutBuf *pMe,
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002007 uint64_t uInteger64,
2008 size_t uPos)
Michael Eckel5c531332020-03-02 01:35:30 +01002009{
2010 const void *pBytes;
2011
2012#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002013 /* We have been told explicitly we are running on a big-endian
2014 * machine. Network byte order is big endian, so just copy. There
2015 * is no issue with alignment here because uInteger64 is always
2016 * aligned (and it doesn't matter if pBytes is aligned).
2017 */
Michael Eckel5c531332020-03-02 01:35:30 +01002018 pBytes = &uInteger64;
2019
2020#elif defined(USEFULBUF_CONFIG_HTON)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002021 /* Use system function to handle big- and little-endian. This works
2022 * on both big- and little-endian machines, but hton() is not
2023 * always available or in a standard place so it is not used by
2024 * default. With some compilers and CPUs the code for this is very
2025 * compact through use of a special swap instruction and on
2026 * big-endian machines hton() will reduce to nothing.
2027 */
Michael Eckel5c531332020-03-02 01:35:30 +01002028 uint64_t uTmp = htonll(uInteger64);
2029
2030 pBytes = &uTmp;
2031
2032#elif defined(USEFULBUF_CONFIG_LITTLE_ENDIAN) && defined(USEFULBUF_CONFIG_BSWAP)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002033 /* Use built-in function for byte swapping. This usually compiles
2034 * to an efficient special byte swap instruction. Unlike hton() it
2035 * does not do this conditionally on the CPU endianness, so this
2036 * code is also conditional on USEFULBUF_CONFIG_LITTLE_ENDIAN
2037 */
Michael Eckel5c531332020-03-02 01:35:30 +01002038 uint64_t uTmp = __builtin_bswap64(uInteger64);
2039
2040 pBytes = &uTmp;
2041
2042#else
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002043 /* Default which works on every CPU with no dependency on anything
2044 * from the CPU, compiler, libraries or OS. This always works, but
2045 * it is usually a little larger and slower than hton().
2046 */
Michael Eckel5c531332020-03-02 01:35:30 +01002047 uint8_t aTmp[8];
2048
2049 aTmp[0] = (uint8_t)((uInteger64 & 0xff00000000000000) >> 56);
2050 aTmp[1] = (uint8_t)((uInteger64 & 0xff000000000000) >> 48);
2051 aTmp[2] = (uint8_t)((uInteger64 & 0xff0000000000) >> 40);
2052 aTmp[3] = (uint8_t)((uInteger64 & 0xff00000000) >> 32);
2053 aTmp[4] = (uint8_t)((uInteger64 & 0xff000000) >> 24);
2054 aTmp[5] = (uint8_t)((uInteger64 & 0xff0000) >> 16);
2055 aTmp[6] = (uint8_t)((uInteger64 & 0xff00) >> 8);
2056 aTmp[7] = (uint8_t)(uInteger64 & 0xff);
2057
2058 pBytes = aTmp;
2059#endif
2060
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002061 /* Do the insert */
Michael Eckel5c531332020-03-02 01:35:30 +01002062 UsefulOutBuf_InsertData(pMe, pBytes, sizeof(uint64_t), uPos);
2063}
2064
2065
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002066#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01002067static inline void UsefulOutBuf_InsertFloat(UsefulOutBuf *pMe,
2068 float f,
2069 size_t uPos)
2070{
2071 UsefulOutBuf_InsertUint32(pMe, UsefulBufUtil_CopyFloatToUint32(f), uPos);
2072}
2073
2074
2075static inline void UsefulOutBuf_InsertDouble(UsefulOutBuf *pMe,
2076 double d,
2077 size_t uPos)
2078{
2079 UsefulOutBuf_InsertUint64(pMe, UsefulBufUtil_CopyDoubleToUint64(d), uPos);
2080}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002081#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01002082
2083
2084static inline void UsefulOutBuf_AppendUsefulBuf(UsefulOutBuf *pMe,
2085 UsefulBufC NewData)
2086{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002087 /* An append is just a insert at the end */
Michael Eckel5c531332020-03-02 01:35:30 +01002088 UsefulOutBuf_InsertUsefulBuf(pMe, NewData, UsefulOutBuf_GetEndPosition(pMe));
2089}
2090
2091
2092static inline void UsefulOutBuf_AppendData(UsefulOutBuf *pMe,
2093 const void *pBytes,
2094 size_t uLen)
2095{
2096 UsefulBufC Data = {pBytes, uLen};
2097 UsefulOutBuf_AppendUsefulBuf(pMe, Data);
2098}
2099
2100
2101static inline void UsefulOutBuf_AppendString(UsefulOutBuf *pMe,
2102 const char *szString)
2103{
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07002104 UsefulBufC UBC;
2105 UBC.ptr = szString;
2106 UBC.len = strlen(szString);
2107
2108 UsefulOutBuf_AppendUsefulBuf(pMe, UBC);
Michael Eckel5c531332020-03-02 01:35:30 +01002109}
2110
2111
2112static inline void UsefulOutBuf_AppendByte(UsefulOutBuf *pMe,
2113 uint8_t byte)
2114{
2115 UsefulOutBuf_AppendData(pMe, &byte, 1);
2116}
2117
2118
2119static inline void UsefulOutBuf_AppendUint16(UsefulOutBuf *pMe,
2120 uint16_t uInteger16)
2121{
2122 UsefulOutBuf_InsertUint16(pMe, uInteger16, UsefulOutBuf_GetEndPosition(pMe));
2123}
2124
2125static inline void UsefulOutBuf_AppendUint32(UsefulOutBuf *pMe,
2126 uint32_t uInteger32)
2127{
2128 UsefulOutBuf_InsertUint32(pMe, uInteger32, UsefulOutBuf_GetEndPosition(pMe));
2129}
2130
2131
2132static inline void UsefulOutBuf_AppendUint64(UsefulOutBuf *pMe,
2133 uint64_t uInteger64)
2134{
2135 UsefulOutBuf_InsertUint64(pMe, uInteger64, UsefulOutBuf_GetEndPosition(pMe));
2136}
2137
2138
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002139#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01002140static inline void UsefulOutBuf_AppendFloat(UsefulOutBuf *pMe,
2141 float f)
2142{
2143 UsefulOutBuf_InsertFloat(pMe, f, UsefulOutBuf_GetEndPosition(pMe));
2144}
2145
2146
2147static inline void UsefulOutBuf_AppendDouble(UsefulOutBuf *pMe,
2148 double d)
2149{
2150 UsefulOutBuf_InsertDouble(pMe, d, UsefulOutBuf_GetEndPosition(pMe));
2151}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002152#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01002153
2154
2155static inline int UsefulOutBuf_GetError(UsefulOutBuf *pMe)
2156{
2157 return pMe->err;
2158}
2159
2160
2161static inline size_t UsefulOutBuf_RoomLeft(UsefulOutBuf *pMe)
2162{
2163 return pMe->UB.len - pMe->data_len;
2164}
2165
2166
2167static inline int UsefulOutBuf_WillItFit(UsefulOutBuf *pMe, size_t uLen)
2168{
2169 return uLen <= UsefulOutBuf_RoomLeft(pMe);
2170}
2171
2172
2173static inline int UsefulOutBuf_IsBufferNULL(UsefulOutBuf *pMe)
2174{
2175 return pMe->UB.ptr == NULL;
2176}
2177
2178
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06002179static inline UsefulBuf UsefulOutBuf_GetOutPlace(UsefulOutBuf *pUOutBuf)
2180{
2181 UsefulBuf R;
2182
2183 R.len = UsefulOutBuf_RoomLeft(pUOutBuf);
Paul Liétarc6cfa332022-07-26 19:24:01 +01002184 if(R.len > 0 && pUOutBuf->UB.ptr != NULL) {
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06002185 R.ptr = (uint8_t *)pUOutBuf->UB.ptr + pUOutBuf->data_len;
2186 } else {
2187 R.ptr = NULL;
2188 }
2189
2190 return R;
2191}
2192
2193
2194
Michael Eckel5c531332020-03-02 01:35:30 +01002195
2196static inline void UsefulInputBuf_Init(UsefulInputBuf *pMe, UsefulBufC UB)
2197{
2198 pMe->cursor = 0;
2199 pMe->err = 0;
2200 pMe->magic = UIB_MAGIC;
2201 pMe->UB = UB;
2202}
2203
2204static inline size_t UsefulInputBuf_Tell(UsefulInputBuf *pMe)
2205{
2206 return pMe->cursor;
2207}
2208
2209
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07002210static inline size_t UsefulInputBuf_GetBufferLength(UsefulInputBuf *pMe)
Laurence Lundblade0750fc42020-06-20 21:02:34 -07002211{
2212 return pMe->UB.len;
2213}
2214
2215
Michael Eckel5c531332020-03-02 01:35:30 +01002216static inline void UsefulInputBuf_Seek(UsefulInputBuf *pMe, size_t uPos)
2217{
2218 if(uPos > pMe->UB.len) {
2219 pMe->err = 1;
2220 } else {
2221 pMe->cursor = uPos;
2222 }
2223}
2224
2225
2226static inline size_t UsefulInputBuf_BytesUnconsumed(UsefulInputBuf *pMe)
2227{
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002228 /* Code Reviewers: THIS FUNCTION DOES POINTER MATH */
Michael Eckel5c531332020-03-02 01:35:30 +01002229
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002230 /* Magic number is messed up. Either the structure got overwritten
2231 * or was never initialized.
2232 */
Michael Eckel5c531332020-03-02 01:35:30 +01002233 if(pMe->magic != UIB_MAGIC) {
2234 return 0;
2235 }
2236
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002237 /* The cursor is off the end of the input buffer given.
2238 * Presuming there are no bugs in this code, this should never happen.
2239 * If it so, the struct was corrupted. The check is retained as
2240 * as a defense in case there is a bug in this code or the struct is
2241 * corrupted.
2242 */
Michael Eckel5c531332020-03-02 01:35:30 +01002243 if(pMe->cursor > pMe->UB.len) {
2244 return 0;
2245 }
2246
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002247 /* subtraction can't go negative because of check above */
Michael Eckel5c531332020-03-02 01:35:30 +01002248 return pMe->UB.len - pMe->cursor;
2249}
2250
2251
2252static inline int UsefulInputBuf_BytesAvailable(UsefulInputBuf *pMe, size_t uLen)
2253{
2254 return UsefulInputBuf_BytesUnconsumed(pMe) >= uLen ? 1 : 0;
2255}
2256
2257
Laurence Lundbladecf41c522021-02-20 10:19:07 -07002258static inline size_t UsefulInputBuf_PointerToOffset(UsefulInputBuf *pUInBuf, const void *p)
2259{
2260 return UsefulBuf_PointerToOffset(pUInBuf->UB, p);
2261}
2262
2263
Michael Eckel5c531332020-03-02 01:35:30 +01002264static inline UsefulBufC UsefulInputBuf_GetUsefulBuf(UsefulInputBuf *pMe, size_t uNum)
2265{
2266 const void *pResult = UsefulInputBuf_GetBytes(pMe, uNum);
2267 if(!pResult) {
2268 return NULLUsefulBufC;
2269 } else {
Laurence Lundblade48d8ace2021-08-19 22:00:26 -07002270 UsefulBufC UBC;
2271 UBC.ptr = pResult;
2272 UBC.len = uNum;
2273 return UBC;
Michael Eckel5c531332020-03-02 01:35:30 +01002274 }
2275}
2276
2277
2278static inline uint8_t UsefulInputBuf_GetByte(UsefulInputBuf *pMe)
2279{
2280 const void *pResult = UsefulInputBuf_GetBytes(pMe, sizeof(uint8_t));
2281
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002282 /* The ternary operator is subject to integer promotion, because
2283 * the operands are smaller than int, so cast back to uint8_t is
2284 * needed to be completely explicit about types (for static
2285 * analyzers).
2286 */
Laurence Lundbladeb9702452021-03-08 21:02:57 -08002287 return (uint8_t)(pResult ? *(const uint8_t *)pResult : 0);
Michael Eckel5c531332020-03-02 01:35:30 +01002288}
2289
2290static inline uint16_t UsefulInputBuf_GetUint16(UsefulInputBuf *pMe)
2291{
2292 const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(pMe, sizeof(uint16_t));
2293
2294 if(!pResult) {
2295 return 0;
2296 }
2297
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002298 /* See UsefulInputBuf_GetUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01002299#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) || defined(USEFULBUF_CONFIG_HTON) || defined(USEFULBUF_CONFIG_BSWAP)
2300 uint16_t uTmp;
2301 memcpy(&uTmp, pResult, sizeof(uint16_t));
2302
2303#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
2304 return uTmp;
2305
2306#elif defined(USEFULBUF_CONFIG_HTON)
2307 return ntohs(uTmp);
2308
2309#else
2310 return __builtin_bswap16(uTmp);
2311
2312#endif
2313
2314#else
2315
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002316 /* The operations here are subject to integer promotion because the
2317 * operands are smaller than int. They will be promoted to unsigned
2318 * int for the shift and addition. The cast back to uint16_t is is
2319 * needed to be completely explicit about types (for static
2320 * analyzers).
2321 */
Michael Eckel5c531332020-03-02 01:35:30 +01002322 return (uint16_t)((pResult[0] << 8) + pResult[1]);
2323
2324#endif
2325}
2326
2327
2328static inline uint32_t UsefulInputBuf_GetUint32(UsefulInputBuf *pMe)
2329{
2330 const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(pMe, sizeof(uint32_t));
2331
2332 if(!pResult) {
2333 return 0;
2334 }
2335
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002336 /* See UsefulInputBuf_GetUint64() for comments on this code */
Michael Eckel5c531332020-03-02 01:35:30 +01002337#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) || defined(USEFULBUF_CONFIG_HTON) || defined(USEFULBUF_CONFIG_BSWAP)
2338 uint32_t uTmp;
2339 memcpy(&uTmp, pResult, sizeof(uint32_t));
2340
2341#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
2342 return uTmp;
2343
2344#elif defined(USEFULBUF_CONFIG_HTON)
2345 return ntohl(uTmp);
2346
2347#else
2348 return __builtin_bswap32(uTmp);
2349
2350#endif
2351
2352#else
2353 return ((uint32_t)pResult[0]<<24) +
2354 ((uint32_t)pResult[1]<<16) +
2355 ((uint32_t)pResult[2]<<8) +
2356 (uint32_t)pResult[3];
2357#endif
2358}
2359
2360
2361static inline uint64_t UsefulInputBuf_GetUint64(UsefulInputBuf *pMe)
2362{
2363 const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(pMe, sizeof(uint64_t));
2364
2365 if(!pResult) {
2366 return 0;
2367 }
2368
2369#if defined(USEFULBUF_CONFIG_BIG_ENDIAN) || defined(USEFULBUF_CONFIG_HTON) || defined(USEFULBUF_CONFIG_BSWAP)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002370 /* pResult will probably not be aligned. This memcpy() moves the
2371 * bytes into a temp variable safely for CPUs that can or can't do
2372 * unaligned memory access. Many compilers will optimize the
2373 * memcpy() into a simple move instruction.
2374 */
Michael Eckel5c531332020-03-02 01:35:30 +01002375 uint64_t uTmp;
2376 memcpy(&uTmp, pResult, sizeof(uint64_t));
2377
2378#if defined(USEFULBUF_CONFIG_BIG_ENDIAN)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002379 /* We have been told expliclity this is a big-endian CPU. Since
2380 * network byte order is big-endian, there is nothing to do.
2381 */
Michael Eckel5c531332020-03-02 01:35:30 +01002382
2383 return uTmp;
2384
2385#elif defined(USEFULBUF_CONFIG_HTON)
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002386 /* We have been told to use ntoh(), the system function to handle
2387 * big- and little-endian. This works on both big- and
2388 * little-endian machines, but ntoh() is not always available or in
2389 * a standard place so it is not used by default. On some CPUs the
2390 * code for this is very compact through use of a special swap
2391 * instruction.
2392 */
Michael Eckel5c531332020-03-02 01:35:30 +01002393
2394 return ntohll(uTmp);
2395
2396#else
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002397 /* Little-endian (since it is not USEFULBUF_CONFIG_BIG_ENDIAN) and
2398 * USEFULBUF_CONFIG_BSWAP (since it is not USEFULBUF_CONFIG_HTON).
2399 * __builtin_bswap64() and friends are not conditional on CPU
2400 * endianness so this must only be used on little-endian machines.
2401 */
Michael Eckel5c531332020-03-02 01:35:30 +01002402
2403 return __builtin_bswap64(uTmp);
2404
2405
2406#endif
2407
2408#else
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002409 /* This is the default code that works on every CPU and every
2410 * endianness with no dependency on ntoh(). This works on CPUs
2411 * that either allow or do not allow unaligned access. It will
2412 * always work, but usually is a little less efficient than ntoh().
2413 */
Michael Eckel5c531332020-03-02 01:35:30 +01002414
2415 return ((uint64_t)pResult[0]<<56) +
2416 ((uint64_t)pResult[1]<<48) +
2417 ((uint64_t)pResult[2]<<40) +
2418 ((uint64_t)pResult[3]<<32) +
2419 ((uint64_t)pResult[4]<<24) +
2420 ((uint64_t)pResult[5]<<16) +
2421 ((uint64_t)pResult[6]<<8) +
2422 (uint64_t)pResult[7];
2423#endif
2424}
2425
2426
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002427#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Michael Eckel5c531332020-03-02 01:35:30 +01002428static inline float UsefulInputBuf_GetFloat(UsefulInputBuf *pMe)
2429{
2430 uint32_t uResult = UsefulInputBuf_GetUint32(pMe);
2431
2432 return uResult ? UsefulBufUtil_CopyUint32ToFloat(uResult) : 0;
2433}
2434
2435
2436static inline double UsefulInputBuf_GetDouble(UsefulInputBuf *pMe)
2437{
2438 uint64_t uResult = UsefulInputBuf_GetUint64(pMe);
2439
2440 return uResult ? UsefulBufUtil_CopyUint64ToDouble(uResult) : 0;
2441}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02002442#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Michael Eckel5c531332020-03-02 01:35:30 +01002443
2444
2445static inline int UsefulInputBuf_GetError(UsefulInputBuf *pMe)
2446{
2447 return pMe->err;
2448}
2449
Laurence Lundblade24d509a2020-06-06 18:43:15 -07002450
Laurence Lundblade1ba100d2020-09-19 21:41:02 -07002451static inline void UsefulInputBuf_SetBufferLength(UsefulInputBuf *pMe, size_t uNewLen)
Laurence Lundblade24d509a2020-06-06 18:43:15 -07002452{
2453 pMe->UB.len = uNewLen;
2454}
2455
2456
Michael Eckel5c531332020-03-02 01:35:30 +01002457#ifdef __cplusplus
2458}
2459#endif
2460
Laurence Lundbladedabaffe2021-05-11 10:47:46 -07002461#endif /* _UsefulBuf_h */
Michael Eckel5c531332020-03-02 01:35:30 +01002462
2463