blob: 47dcd4078ef90ef07d611c97e680121f97f9c3a7 [file] [log] [blame]
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001/*==============================================================================
Laurence Lundbladed92a6162018-11-01 11:38:35 +07002 Copyright (c) 2016-2018, The Linux Foundation.
Laurence Lundblade240ca822024-01-16 11:11:00 -07003 Copyright (c) 2018-2024, Laurence Lundblade.
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +02004 Copyright (c) 2021, Arm Limited.
Laurence Lundbladed92a6162018-11-01 11:38:35 +07005 All rights reserved.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08006
Laurence Lundblade0dbc9172018-11-01 14:17:21 +07007Redistribution and use in source and binary forms, with or without
8modification, are permitted provided that the following conditions are
9met:
10 * Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12 * Redistributions in binary form must reproduce the above
13 copyright notice, this list of conditions and the following
14 disclaimer in the documentation and/or other materials provided
15 with the distribution.
16 * Neither the name of The Linux Foundation nor the names of its
17 contributors, nor the name "Laurence Lundblade" may be used to
18 endorse or promote products derived from this software without
19 specific prior written permission.
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080020
Laurence Lundblade0dbc9172018-11-01 14:17:21 +070021THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
22WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
24ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
25BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
30OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
31IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Laurence Lundbladeee851742020-01-08 08:37:05 -080032 =============================================================================*/
Laurence Lundblade624405d2018-09-18 20:10:47 -070033
Laurence Lundblade3aee3a32018-12-17 16:17:45 -080034
Laurence Lundblade844bb5c2020-03-01 17:27:25 -080035#include "qcbor/qcbor_encode.h"
Laurence Lundblade12d32c52018-09-19 11:25:27 -070036#include "ieee754.h"
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070037
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070038
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080039/**
40 * @file qcbor_encode.c
Laurence Lundblade3f1318a2021-01-04 18:26:44 -080041 *
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080042 * The entire implementation of the QCBOR encoder.
43 */
44
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070045
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070046/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080047 * == Nesting Tracking ==
48 *
49 * The following functions and data type QCBORTrackNesting implement
50 * the nesting management for encoding.
51 *
52 * CBOR's two nesting types, arrays and maps, are tracked here. There
53 * is a limit of QCBOR_MAX_ARRAY_NESTING to the number of arrays and
54 * maps that can be nested in one encoding so the encoding context
55 * stays small enough to fit on the stack.
56 *
57 * When an array/map is opened, pCurrentNesting points to the element
58 * in pArrays that records the type, start position and accumulates a
59 * count of the number of items added. When closed the start position
60 * is used to go back and fill in the type and number of items in the
61 * array/map.
62 *
63 * Encoded output can be a CBOR Sequence (RFC 8742) in which case
64 * there is no top-level array or map. It starts out with a string,
65 * integer or other non-aggregate type. It may have an array or map
66 * other than at the start, in which case that nesting is tracked
67 * here.
68 *
69 * QCBOR has a special feature to allow constructing byte string
70 * wrapped CBOR directly into the output buffer, so no extra buffer is
71 * needed for byte string wrapping. This is implemented as nesting
72 * with the type CBOR_MAJOR_TYPE_BYTE_STRING and is tracked here. Byte
73 * string wrapped CBOR is used by COSE for data that is to be hashed.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070074 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -070075static void
Laurence Lundblade274ddef2022-05-17 09:12:23 -070076Nesting_Init(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070077{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080078 /* Assumes pNesting has been zeroed. */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070079 pNesting->pCurrentNesting = &pNesting->pArrays[0];
Laurence Lundblade1fa579b2020-11-25 00:31:37 -080080 /* Implied CBOR array at the top nesting level. This is never
81 * returned, but makes the item count work correctly.
82 */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070083 pNesting->pCurrentNesting->uMajorType = CBOR_MAJOR_TYPE_ARRAY;
84}
85
Laurence Lundblade8e36f812024-01-26 10:59:29 -070086static uint8_t
Laurence Lundblade274ddef2022-05-17 09:12:23 -070087Nesting_Increase(QCBORTrackNesting *pNesting,
Laurence Lundblade8e36f812024-01-26 10:59:29 -070088 const uint8_t uMajorType,
89 const uint32_t uPos)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070090{
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070091 if(pNesting->pCurrentNesting == &pNesting->pArrays[QCBOR_MAX_ARRAY_NESTING]) {
Laurence Lundblade29497c02020-07-11 15:44:03 -070092 return QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070093 } else {
94 pNesting->pCurrentNesting++;
95 pNesting->pCurrentNesting->uCount = 0;
96 pNesting->pCurrentNesting->uStart = uPos;
97 pNesting->pCurrentNesting->uMajorType = uMajorType;
Laurence Lundblade29497c02020-07-11 15:44:03 -070098 return QCBOR_SUCCESS;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -070099 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700100}
101
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700102static void
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700103Nesting_Decrease(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700104{
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700105 if(pNesting->pCurrentNesting > &pNesting->pArrays[0]) {
106 pNesting->pCurrentNesting--;
107 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700108}
109
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700110static uint8_t
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700111Nesting_Increment(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700112{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800113#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -0800114 if(1 >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700115 return QCBOR_ERR_ARRAY_TOO_LONG;
116 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800117#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800118
Laurence Lundbladee6bcef12020-04-01 10:56:27 -0700119 pNesting->pCurrentNesting->uCount++;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800120
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700121 return QCBOR_SUCCESS;
122}
123
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700124static void
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700125Nesting_Decrement(QCBORTrackNesting *pNesting)
Laurence Lundblade8d3b8552021-06-10 11:11:54 -0700126{
127 /* No error check for going below 0 here needed because this
128 * is only used by QCBOREncode_CancelBstrWrap() and it checks
129 * the nesting level before calling this. */
130 pNesting->pCurrentNesting->uCount--;
131}
132
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700133static uint16_t
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700134Nesting_GetCount(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700135{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800136 /* The nesting count recorded is always the actual number of
137 * individual data items in the array or map. For arrays CBOR uses
138 * the actual item count. For maps, CBOR uses the number of pairs.
139 * This function returns the number needed for the CBOR encoding,
140 * so it divides the number of items by two for maps to get the
141 * number of pairs.
142 */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800143 if(pNesting->pCurrentNesting->uMajorType == CBOR_MAJOR_TYPE_MAP) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800144 /* Cast back to uint16_t after integer promotion from bit shift */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800145 return (uint16_t)(pNesting->pCurrentNesting->uCount >> 1);
146 } else {
147 return pNesting->pCurrentNesting->uCount;
148 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700149}
150
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700151static uint32_t
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700152Nesting_GetStartPos(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700153{
154 return pNesting->pCurrentNesting->uStart;
155}
156
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800157#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700158static uint8_t
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700159Nesting_GetMajorType(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700160{
161 return pNesting->pCurrentNesting->uMajorType;
162}
163
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700164static bool
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700165Nesting_IsInNest(QCBORTrackNesting *pNesting)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700166{
Laurence Lundbladeee851742020-01-08 08:37:05 -0800167 return pNesting->pCurrentNesting == &pNesting->pArrays[0] ? false : true;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700168}
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800169#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700170
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700171
172
173
174/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800175 * == Major CBOR Types ==
176 *
177 * Encoding of the major CBOR types is by these functions:
178 *
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800179 * CBOR Major Type Public Function
180 * 0 QCBOREncode_AddUInt64()
181 * 0, 1 QCBOREncode_AddUInt64(), QCBOREncode_AddInt64()
182 * 2, 3 QCBOREncode_AddBuffer()
183 * 4, 5 QCBOREncode_OpenMapOrArray(), QCBOREncode_CloseMapOrArray(),
184 * QCBOREncode_OpenMapOrArrayIndefiniteLength(),
185 * QCBOREncode_CloseMapOrArrayIndefiniteLength()
186 * 6 QCBOREncode_AddTag()
187 * 7 QCBOREncode_AddDouble(), QCBOREncode_AddFloat(),
188 * QCBOREncode_AddDoubleNoPreferred(),
189 * QCBOREncode_AddFloatNoPreferred(), QCBOREncode_AddType7()
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800190 *
191 * Additionally, encoding of decimal fractions and bigfloats is by
192 * QCBOREncode_AddExponentAndMantissa() and byte strings that wrap
193 * encoded CBOR are handled by QCBOREncode_OpenMapOrArray() and
194 * QCBOREncode_CloseBstrWrap2().
195 *
196 *
197 * == Error Tracking Plan ==
198 *
199 * Errors are tracked internally and not returned until
200 * QCBOREncode_Finish() or QCBOREncode_GetErrorState() is called. The
201 * CBOR errors are in me->uError. UsefulOutBuf also tracks whether
202 * the buffer is full or not in its context. Once either of these
203 * errors is set they are never cleared. Only QCBOREncode_Init()
204 * resets them. Or said another way, they must never be cleared or
205 * we'll tell the caller all is good when it is not.
206 *
207 * Only one error code is reported by QCBOREncode_Finish() even if
208 * there are multiple errors. The last one set wins. The caller might
209 * have to fix one error to reveal the next one they have to fix.
210 * This is OK.
211 *
212 * The buffer full error tracked by UsefulBuf is only pulled out of
213 * UsefulBuf in QCBOREncode_Finish() so it is the one that usually
214 * wins. UsefulBuf will never go off the end of the buffer even if it
215 * is called again and again when full.
216 *
217 * QCBOR_DISABLE_ENCODE_USAGE_GUARDS disables about half of the error
218 * checks here to reduce code size by about 150 bytes leaving only the
219 * checks for size to avoid buffer overflow. If the calling code is
220 * completely correct, checks are completely unnecessary. For
221 * example, there is no need to check that all the opens are matched
222 * by a close.
223 *
224 * QCBOR_DISABLE_ENCODE_USAGE_GUARDS also disables the check for more
225 * than QCBOR_MAX_ITEMS_IN_ARRAY in an array. Since
226 * QCBOR_MAX_ITEMS_IN_ARRAY is very large (65,535) it is very unlikely
227 * to be reached. If it is reached, the count will wrap around to zero
228 * and CBOR that is not well formed will be produced, but there will
229 * be no buffers overrun and new security issues in the code.
230 *
231 * The 8 errors returned here fall into three categories:
232 *
233 * Sizes
234 * QCBOR_ERR_BUFFER_TOO_LARGE -- Encoded output exceeded UINT32_MAX
235 * QCBOR_ERR_BUFFER_TOO_SMALL -- Output buffer too small
236 * QCBOR_ERR_ARRAY_NESTING_TOO_DEEP -- Nesting > QCBOR_MAX_ARRAY_NESTING1
237 * QCBOR_ERR_ARRAY_TOO_LONG -- Too many items added to an array/map [1]
238 *
239 * Nesting constructed incorrectly
240 * QCBOR_ERR_TOO_MANY_CLOSES -- More close calls than opens [1]
241 * QCBOR_ERR_CLOSE_MISMATCH -- Type of close does not match open [1]
242 * QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN -- Finish called without enough closes [1]
243 *
244 * Would generate not-well-formed CBOR
245 * QCBOR_ERR_ENCODE_UNSUPPORTED -- Simple type between 24 and 31 [1]
246 *
247 * [1] indicated disabled by QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700248 */
249
Laurence Lundblade240ca822024-01-16 11:11:00 -0700250void QCBOREncode_CloseMapUnsorted(QCBOREncodeContext *pMe); // TODO: relocate/doc
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700251
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700252/*
Laurence Lundblade844bb5c2020-03-01 17:27:25 -0800253 Public function for initialization. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700254 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700255void
256QCBOREncode_Init(QCBOREncodeContext *pMe, UsefulBuf Storage)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700257{
Laurence Lundblade240ca822024-01-16 11:11:00 -0700258 memset(pMe, 0, sizeof(QCBOREncodeContext));
259 UsefulOutBuf_Init(&(pMe->OutBuf), Storage);
260 Nesting_Init(&(pMe->nesting));
261 pMe->pfnCloseMap = QCBOREncode_CloseMapUnsorted;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700262}
263
264
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000265/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800266 * Public function to encode a CBOR head. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700267 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700268UsefulBufC
269QCBOREncode_EncodeHead(UsefulBuf Buffer,
270 uint8_t uMajorType,
271 uint8_t uMinLen,
272 uint64_t uArgument)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700273{
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800274 /*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800275 * == Description of the CBOR Head ==
276 *
277 * The head of a CBOR data item
278 * +---+-----+ +--------+ +--------+ +--------+ +--------+
279 * |M T| A R G U M E N T . . . |
280 * +---+-----+ +--------+ +--------+ +--------+ ... +--------+
281 *
282 * Every CBOR data item has a "head". It is made up of the "major
283 * type" and the "argument".
284 *
285 * The major type indicates whether the data item is an integer,
286 * string, array or such. It is encoded in 3 bits giving it a range
287 * from 0 to 7. 0 indicates the major type is a positive integer,
288 * 1 a negative integer, 2 a byte string and so on.
289 *
290 * These 3 bits are the first part of the "initial byte" in a data
291 * item. Every data item has an initial byte, and some only have
292 * the initial byte.
293 *
294 * The argument is essentially a number between 0 and UINT64_MAX
295 * (18446744073709551615). This number is interpreted to mean
296 * different things for the different major types. For major type
297 * 0, a positive integer, it is value of the data item. For major
298 * type 2, a byte string, it is the length in bytes of the byte
299 * string. For major type 4, an array, it is the number of data
300 * items in the array.
301 *
302 * Special encoding is used so that the argument values less than
303 * 24 can be encoded very compactly in the same byte as the major
304 * type is encoded. When the lower 5 bits of the initial byte have
305 * a value less than 24, then that is the value of the argument.
306 *
307 * If the lower 5 bits of the initial byte are less than 24, then
308 * they are the value of the argument. This allows integer values 0
309 * - 23 to be CBOR encoded in just one byte.
310 *
311 * When the value of lower 5 bits are 24, 25, 26, or 27 the
312 * argument is encoded in 1, 2, 4 or 8 bytes following the initial
313 * byte in network byte order (bit endian). The cases when it is
314 * 28, 29 and 30 are reserved for future use. The value 31 is a
315 * special indicator for indefinite length strings, arrays and
316 * maps.
317 *
318 * The lower 5 bits are called the "additional information."
319 *
320 * Thus the CBOR head may be 1, 2, 3, 5 or 9 bytes long.
321 *
322 * It is legal in CBOR to encode the argument using any of these
323 * lengths even if it could be encoded in a shorter length. For
324 * example it is legal to encode a data item representing the
325 * positive integer 0 in 9 bytes even though it could be encoded in
326 * only 0. This is legal to allow for for very simple code or even
327 * hardware-only implementations that just output a register
328 * directly.
329 *
330 * CBOR defines preferred encoding as the encoding of the argument
331 * in the smallest number of bytes needed to encode it.
332 *
333 * This function takes the major type and argument as inputs and
334 * outputs the encoded CBOR head for them. It does conversion to
335 * network byte order. It implements CBOR preferred encoding,
336 * outputting the shortest representation of the argument.
337 *
338 * == Endian Conversion ==
339 *
340 * This code does endian conversion without hton() or knowing the
341 * endianness of the machine by using masks and shifts. This avoids
342 * the dependency on hton() and the mess of figuring out how to
343 * find the machine's endianness.
344 *
345 * This is a good efficient implementation on little-endian
346 * machines. A faster and smaller implementation is possible on
347 * big-endian machines because CBOR/network byte order is
348 * big-endian. However big-endian machines are uncommon.
349 *
350 * On x86, this is about 150 bytes instead of 500 bytes for the
351 * original, more formal unoptimized code.
352 *
353 * This also does the CBOR preferred shortest encoding for integers
354 * and is called to do endian conversion for floats.
355 *
356 * It works backwards from the least significant byte to the most
357 * significant byte.
358 *
359 * == Floating Point ==
360 *
361 * When the major type is 7 and the 5 lower bits have the values
362 * 25, 26 or 27, the argument is a floating-point number that is
363 * half, single or double-precision. Note that it is not the
364 * conversion from a floating-point value to an integer value like
365 * converting 0x00 to 0.00, it is the interpretation of the bits in
366 * the argument as an IEEE 754 float-point number.
367 *
368 * Floating-point numbers must be converted to network byte
369 * order. That is accomplished here by exactly the same code that
370 * converts integer arguments to network byte order.
371 *
372 * There is preferred encoding for floating-point numbers in CBOR,
373 * but it is very different than for integers and it is not
374 * implemented here. Half-precision is preferred to
375 * single-precision which is preferred to double-precision only if
376 * the conversion can be performed without loss of precision. Zero
377 * and infinity can always be converted to half-precision, without
378 * loss but 3.141592653589 cannot.
379 *
380 * The way this function knows to not do preferred encoding on the
381 * argument passed here when it is a floating point number is the
382 * uMinLen parameter. It should be 2, 4 or 8 for half, single and
383 * double precision floating point values. This prevents and the
384 * incorrect removal of leading zeros when encoding arguments that
385 * are floating-point numbers.
386 *
387 * == Use of Type int and Static Analyzers ==
388 *
389 * The type int is used here for several variables because of the
390 * way integer promotion works in C for variables that are uint8_t
391 * or uint16_t. The basic rule is that they will always be promoted
392 * to int if they will fit. These integer variables here need only
393 * hold values less than 255 so they will always fit into an int.
394 *
395 * Most of values stored are never negative, so one might think
396 * that unsigned int would be more correct than int. However the C
397 * integer promotion rules only promote to unsigned int if the
398 * result won't fit into an int even if the promotion is for an
399 * unsigned variable like uint8_t.
400 *
401 * By declaring these int, there are few implicit conversions and
402 * fewer casts needed. Code size is reduced a little. It makes
403 * static analyzers happier.
404 *
405 * Note also that declaring these uint8_t won't stop integer wrap
406 * around if the code is wrong. It won't make the code more
407 * correct.
408 *
409 * https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules
410 * https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be
411 *
412 * Code Reviewers: THIS FUNCTION DOES POINTER MATH
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800413 */
Laurence Lundbladeee851742020-01-08 08:37:05 -0800414
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800415 /* The buffer must have room for the largest CBOR HEAD + one
416 * extra. The one extra is needed for this code to work as it does
417 * a pre-decrement.
418 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700419 if(Buffer.len < QCBOR_HEAD_BUFFER_SIZE) {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000420 return NULLUsefulBufC;
421 }
422
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800423 /* Pointer to last valid byte in the buffer */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700424 uint8_t * const pBufferEnd = &((uint8_t *)Buffer.ptr)[QCBOR_HEAD_BUFFER_SIZE-1];
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000425
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800426 /* Point to the last byte and work backwards */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000427 uint8_t *pByte = pBufferEnd;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800428 /* The 5 bits in the initial byte that are not the major type */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800429 int nAdditionalInfo;
Laurence Lundblade2c40ab82018-12-30 14:20:29 -0800430
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800431 if(uMajorType > QCBOR_INDEFINITE_LEN_TYPE_MODIFIER) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800432 /* Special case for start & end of indefinite length */
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800433 uMajorType = uMajorType - QCBOR_INDEFINITE_LEN_TYPE_MODIFIER;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800434 /* This takes advantage of design of CBOR where additional info
435 * is 31 for both opening and closing indefinite length
436 * maps and arrays.
437 */
438 #if CBOR_SIMPLE_BREAK != LEN_IS_INDEFINITE
439 #error additional info for opening array not the same as for closing
440 #endif
Laurence Lundblade8c858ab2020-11-02 19:53:49 -0800441 nAdditionalInfo = CBOR_SIMPLE_BREAK;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800442
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000443 } else if (uArgument < CBOR_TWENTY_FOUR && uMinLen == 0) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800444 /* Simple case where argument is < 24 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000445 nAdditionalInfo = (int)uArgument;
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800446
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800447 } else {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800448 /* This encodes the argument in 1,2,4 or 8 bytes. The outer loop
449 * runs once for 1 byte and 4 times for 8 bytes. The inner loop
450 * runs 1, 2 or 4 times depending on outer loop counter. This
451 * works backwards shifting 8 bits off the argument being
452 * encoded at a time until all bits from uArgument have been
453 * encoded and the minimum encoding size is reached. Minimum
454 * encoding size is for floating-point numbers that have some
455 * zero-value bytes that must be output.
Laurence Lundbladee9b00322018-12-30 10:33:26 -0800456 */
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800457 static const uint8_t aIterate[] = {1,1,2,4};
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000458
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800459 /* uMinLen passed in is unsigned, but goes negative in the loop
460 * so it must be converted to a signed value.
461 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000462 int nMinLen = (int)uMinLen;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800463 int i;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000464 for(i = 0; uArgument || nMinLen > 0; i++) {
465 const int nIterations = (int)aIterate[i];
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800466 for(int j = 0; j < nIterations; j++) {
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000467 *--pByte = (uint8_t)(uArgument & 0xff);
468 uArgument = uArgument >> 8;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800469 }
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800470 nMinLen -= nIterations;
Laurence Lundblade04a859b2018-12-11 12:13:02 -0800471 }
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800472
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800473 nAdditionalInfo = LEN_IS_ONE_BYTE-1 + i;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700474 }
Laurence Lundbladef970f1d2018-12-14 01:44:23 -0800475
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800476 /* This expression integer-promotes to type int. The code above in
477 * function guarantees that nAdditionalInfo will never be larger
478 * than 0x1f. The caller may pass in a too-large uMajor type. The
479 * conversion to unint8_t will cause an integer wrap around and
480 * incorrect CBOR will be generated, but no security issue will
481 * occur.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800482 */
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800483 const int nInitialByte = (uMajorType << 5) + nAdditionalInfo;
484 *--pByte = (uint8_t)nInitialByte;
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800485
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000486#ifdef EXTRA_ENCODE_HEAD_CHECK
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800487 /* This is a sanity check that can be turned on to verify the
488 * pointer math in this function is not going wrong. Turn it on and
489 * run the whole test suite to perform the check.
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800490 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000491 if(pBufferEnd - pByte > 9 || pBufferEnd - pByte < 1 || pByte < (uint8_t *)buffer.ptr) {
492 return NULLUsefulBufC;
493 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800494#endif /* EXTRA_ENCODE_HEAD_CHECK */
Laurence Lundbladec5fef682020-01-25 11:38:45 -0800495
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800496 /* Length will not go negative because the loops run for at most 8 decrements
497 * of pByte, only one other decrement is made, and the array is sized
498 * for this.
499 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000500 return (UsefulBufC){pByte, (size_t)(pBufferEnd - pByte)};
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700501}
502
503
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000504/**
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800505 * @brief Append the CBOR head, the major type and argument
506 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700507 * @param pMe Encoder context.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800508 * @param uMajorType Major type to insert.
509 * @param uArgument The argument (an integer value or a length).
510 * @param uMinLen The minimum number of bytes for encoding the CBOR argument.
511 *
512 * This formats the CBOR "head" and appends it to the output.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000513 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700514static void
515QCBOREncode_Private_AppendCBORHead(QCBOREncodeContext *pMe,
516 const uint8_t uMajorType,
517 const uint64_t uArgument,
518 const uint8_t uMinLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700519{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800520 /* A stack buffer large enough for a CBOR head */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000521 UsefulBuf_MAKE_STACK_UB (pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
522
523 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
524 uMajorType,
525 uMinLen,
526 uArgument);
527
528 /* No check for EncodedHead == NULLUsefulBufC is performed here to
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800529 * save object code. It is very clear that pBufferForEncodedHead is
530 * the correct size. If EncodedHead == NULLUsefulBufC then
531 * UsefulOutBuf_AppendUsefulBuf() will do nothing so there is no
532 * security hole introduced.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000533 */
534
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700535 UsefulOutBuf_AppendUsefulBuf(&(pMe->OutBuf), EncodedHead);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700536}
537
538
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000539/**
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700540 * @brief Check for errors when decreasing nesting.
541 *
542 * @param pMe QCBOR encoding context.
543 * @param uMajorType The major type of the nesting.
544 *
545 * Check that there is no previous error, that there is actually some
546 * nesting and that the major type of the opening of the nesting
547 * matches the major type of the nesting being closed.
548 *
549 * This is called when closing maps, arrays, byte string wrapping and
550 * open/close of byte strings.
551 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700552static bool
553QCBOREncode_Private_CheckDecreaseNesting(QCBOREncodeContext *pMe,
554 const uint8_t uMajorType)
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700555{
556#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
557 if(pMe->uError != QCBOR_SUCCESS) {
558 return true;
559 }
560
561 if(!Nesting_IsInNest(&(pMe->nesting))) {
562 pMe->uError = QCBOR_ERR_TOO_MANY_CLOSES;
563 return true;
564 }
565
566 if(Nesting_GetMajorType(&(pMe->nesting)) != uMajorType) {
567 pMe->uError = QCBOR_ERR_CLOSE_MISMATCH;
568 return true;
569 }
570
571#else
572 /* None of these checks are performed if the encode guards are
573 * turned off as they all relate to correct calling.
574 *
575 * Turning off all these checks does not turn off any checking for
576 * buffer overflows or pointer issues.
577 */
578
579 (void)uMajorType;
580 (void)pMe;
581#endif
Laurence Lundbladed6e13022023-11-26 10:14:02 -0700582
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700583 return false;
584}
585
586
587/**
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800588 * @brief Insert the CBOR head for a map, array or wrapped bstr
589 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700590 * @param pMe QCBOR encoding context.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800591 * @param uMajorType One of CBOR_MAJOR_TYPE_XXXX.
592 * @param uLen The length of the data item.
593 *
594 * When an array, map or bstr was opened, nothing was done but note
595 * the position. This function goes back to that position and inserts
596 * the CBOR Head with the major type and length.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000597 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700598static void
599QCBOREncode_Private_InsertCBORHead(QCBOREncodeContext *pMe,
600 uint8_t uMajorType,
601 size_t uLen)
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000602{
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700603 if(QCBOREncode_Private_CheckDecreaseNesting(pMe, uMajorType)) {
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700604 return;
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000605 }
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700606
Laurence Lundbladeb24faef2022-04-26 11:03:08 -0600607 if(uMajorType == CBOR_MAJOR_NONE_TYPE_OPEN_BSTR) {
608 uMajorType = CBOR_MAJOR_TYPE_BYTE_STRING;
609 }
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800610
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700611 /* A stack buffer large enough for a CBOR head (9 bytes) */
Laurence Lundbladed8e1c512020-11-04 23:03:44 -0800612 UsefulBuf_MAKE_STACK_UB(pBufferForEncodedHead, QCBOR_HEAD_BUFFER_SIZE);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800613
614 UsefulBufC EncodedHead = QCBOREncode_EncodeHead(pBufferForEncodedHead,
615 uMajorType,
616 0,
617 uLen);
618
619 /* No check for EncodedHead == NULLUsefulBufC is performed here to
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800620 * save object code. It is very clear that pBufferForEncodedHead is
621 * the correct size. If EncodedHead == NULLUsefulBufC then
622 * UsefulOutBuf_InsertUsefulBuf() will do nothing so there is no
Laurence Lundblade9e2f7082021-05-17 02:10:48 -0700623 * security hole introduced.
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800624 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700625 UsefulOutBuf_InsertUsefulBuf(&(pMe->OutBuf),
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800626 EncodedHead,
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700627 Nesting_GetStartPos(&(pMe->nesting)));
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800628
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700629 Nesting_Decrease(&(pMe->nesting));
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +0000630}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700631
Laurence Lundblade241705e2018-12-30 18:56:14 -0800632
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800633/**
634 * @brief Increment item counter for maps and arrays.
635 *
636 * @param pMe QCBOR encoding context.
637 *
638 * This is mostly a separate function to make code more readable and
639 * to have fewer occurrences of #ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800640 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700641static void
642QCBOREncode_Private_IncrementMapOrArrayCount(QCBOREncodeContext *pMe)
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -0800643{
644#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
645 if(pMe->uError == QCBOR_SUCCESS) {
646 pMe->uError = Nesting_Increment(&(pMe->nesting));
647 }
648#else
649 (void)Nesting_Increment(&(pMe->nesting));
650#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
651}
652
653
654/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800655 * Public functions for adding unsigned integers. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700656 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700657void
658QCBOREncode_AddUInt64(QCBOREncodeContext *pMe, const uint64_t uValue)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700659{
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700660 QCBOREncode_Private_AppendCBORHead(pMe,
661 CBOR_MAJOR_TYPE_POSITIVE_INT,
662 uValue,
663 0);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800664
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700665 QCBOREncode_Private_IncrementMapOrArrayCount(pMe);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700666}
667
Laurence Lundblade56230d12018-11-01 11:14:51 +0700668
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700669/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800670 * Public functions for adding signed integers. See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -0800671 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700672void
673QCBOREncode_AddInt64(QCBOREncodeContext *pMe, const int64_t nNum)
Laurence Lundblade067035b2018-11-28 17:35:25 -0800674{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800675 uint8_t uMajorType;
676 uint64_t uValue;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800677
678 if(nNum < 0) {
Laurence Lundblade9c5c0ef2022-12-23 17:56:27 -0700679 /* In CBOR -1 encodes as 0x00 with major type negative int.
680 * First add one as a signed integer because that will not
681 * overflow. Then change the sign as needed for encoding. (The
682 * opposite order, changing the sign and subtracting, can cause
683 * an overflow when encoding INT64_MIN. */
684 int64_t nTmp = nNum + 1;
685 uValue = (uint64_t)-nTmp;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800686 uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
687 } else {
688 uValue = (uint64_t)nNum;
689 uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
690 }
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700691 QCBOREncode_Private_AppendCBORHead(pMe, uMajorType, uValue, 0);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800692
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700693 QCBOREncode_Private_IncrementMapOrArrayCount(pMe);
Laurence Lundblade067035b2018-11-28 17:35:25 -0800694}
695
696
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700697/**
698 * @brief Semi-private method to add a buffer full of bytes to encoded output.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800699 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700700 * @param[in] pMe The encoding context to add the integer to.
701 * @param[in] uMajorType The CBOR major type of the bytes.
702 * @param[in] Bytes The bytes to add.
703 *
704 * Use QCBOREncode_AddText() or QCBOREncode_AddBytes() or
705 * QCBOREncode_AddEncoded() instead. They are inline functions that
706 * call this and supply the correct major type. This function is
707 * public to make the inline functions work to keep the overall code
708 * size down and because the C language has no way to make it private.
709 *
710 * If this is called the major type should be @c CBOR_MAJOR_TYPE_TEXT_STRING,
711 * @c CBOR_MAJOR_TYPE_BYTE_STRING or @c CBOR_MAJOR_NONE_TYPE_RAW. The
712 * last one is special for adding already-encoded CBOR.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800713 *
714 * This does the work of adding actual strings bytes to the CBOR
715 * output (as opposed to adding numbers and opening / closing
716 * aggregate types).
Laurence Lundblade3aee3a32018-12-17 16:17:45 -0800717
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800718 * There are four use cases:
719 * CBOR_MAJOR_TYPE_BYTE_STRING -- Byte strings
720 * CBOR_MAJOR_TYPE_TEXT_STRING -- Text strings
721 * CBOR_MAJOR_NONE_TYPE_RAW -- Already-encoded CBOR
722 * CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY -- Special case
723 *
724 * The first two add the head plus the actual bytes. The third just
725 * adds the bytes as the heas is presumed to be in the bytes. The
726 * fourth just adds the head for the very special case of
727 * QCBOREncode_AddBytesLenOnly().
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700728 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700729void
730QCBOREncode_Private_AddBuffer(QCBOREncodeContext *pMe,
731 const uint8_t uMajorType,
732 const UsefulBufC Bytes)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700733{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800734 /* If it is not Raw CBOR, add the type and the length */
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800735 if(uMajorType != CBOR_MAJOR_NONE_TYPE_RAW) {
736 uint8_t uRealMajorType = uMajorType;
737 if(uRealMajorType == CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
738 uRealMajorType = CBOR_MAJOR_TYPE_BYTE_STRING;
739 }
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700740 QCBOREncode_Private_AppendCBORHead(pMe, uRealMajorType, Bytes.len, 0);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800741 }
742
743 if(uMajorType != CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800744 /* Actually add the bytes */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700745 UsefulOutBuf_AppendUsefulBuf(&(pMe->OutBuf), Bytes);
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800746 }
747
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700748 QCBOREncode_Private_IncrementMapOrArrayCount(pMe);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700749}
750
Laurence Lundbladecafcfe12018-10-31 21:59:50 +0700751
Laurence Lundblade55a24832018-10-30 04:35:08 +0700752/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800753 * Public functions for adding a tag. See qcbor/qcbor_encode.h
Laurence Lundblade55a24832018-10-30 04:35:08 +0700754 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700755void
756QCBOREncode_AddTag(QCBOREncodeContext *pMe, const uint64_t uTag)
Laurence Lundblade55a24832018-10-30 04:35:08 +0700757{
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700758 QCBOREncode_Private_AppendCBORHead(pMe, CBOR_MAJOR_TYPE_TAG, uTag, 0);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700759}
760
761
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700762/**
763 * @brief Semi-private method to add simple types.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800764 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700765 * @param[in] pMe The encoding context to add the simple value to.
766 * @param[in] uMinLen Minimum encoding size for uNum. Usually 0.
767 * @param[in] uNum One of CBOR_SIMPLEV_FALSE through _UNDEF or other.
768 *
769 * This is used to add simple types like true and false.
770 *
771 * Call QCBOREncode_AddBool(), QCBOREncode_AddNULL(),
772 * QCBOREncode_AddUndef() instead of this.
773 *
774 * This function can add simple values that are not defined by CBOR
775 * yet. This expansion point in CBOR should not be used unless they are
776 * standardized.
777 *
778 * Error handling is the same as QCBOREncode_AddInt64().
Laurence Lundblade56230d12018-11-01 11:14:51 +0700779 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700780void
781QCBOREncode_Private_AddType7(QCBOREncodeContext *pMe,
782 const uint8_t uMinLen,
783 const uint64_t uNum)
Laurence Lundblade55a24832018-10-30 04:35:08 +0700784{
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800785#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700786 if(pMe->uError == QCBOR_SUCCESS) {
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700787 if(uNum >= CBOR_SIMPLEV_RESERVED_START && uNum <= CBOR_SIMPLEV_RESERVED_END) {
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700788 pMe->uError = QCBOR_ERR_ENCODE_UNSUPPORTED;
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800789 return;
Laurence Lundbladebb1062e2019-08-12 23:28:54 -0700790 }
Laurence Lundblade487930f2018-11-30 11:01:45 -0800791 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -0800792#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
793
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800794 /* AppendCBORHead() does endian swapping for the float / double */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700795 QCBOREncode_Private_AppendCBORHead(pMe, CBOR_MAJOR_TYPE_SIMPLE, uNum, uMinLen);
Laurence Lundblade3f1318a2021-01-04 18:26:44 -0800796
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700797 QCBOREncode_Private_IncrementMapOrArrayCount(pMe);
Laurence Lundblade55a24832018-10-30 04:35:08 +0700798}
799
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700800
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200801#ifndef USEFULBUF_DISABLE_ALL_FLOAT
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700802/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800803 * Public functions for adding a double. See qcbor/qcbor_encode.h
804 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700805void
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700806QCBOREncode_AddDoubleNoPreferred(QCBOREncodeContext *pMe, double dNum)
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700807{
Laurence Lundblade240ca822024-01-16 11:11:00 -0700808#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
809 if(pMe->uMode >= QCBOR_ENCODE_MODE_PREFERRED) {
810 pMe->uError = QCBOR_ERR_NOT_PREFERRED;
811 return;
812 }
813#endif /* ! QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
814
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700815 QCBOREncode_Private_AddType7(pMe,
816 sizeof(uint64_t),
817 UsefulBufUtil_CopyDoubleToUint64(dNum));
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700818}
819
Laurence Lundblade240ca822024-01-16 11:11:00 -0700820#include <math.h> // For NaN. Maybe a better way? TODO:
Laurence Lundblade32f3e622020-07-13 20:35:11 -0700821
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700822/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800823 * Public functions for adding a double. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700824 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700825void
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700826QCBOREncode_AddDouble(QCBOREncodeContext *pMe, double dNum)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -0700827{
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700828#ifndef QCBOR_DISABLE_PREFERRED_FLOAT
Laurence Lundblade240ca822024-01-16 11:11:00 -0700829 IEEE754_union FloatResult;
830 bool bNoNaNPayload;
831 struct IEEE754_ToInt IntResult;
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700832
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700833 if(pMe->uMode == QCBOR_ENCODE_MODE_DCBOR) {
Laurence Lundblade240ca822024-01-16 11:11:00 -0700834 IntResult = IEEE754_DoubleToInt(dNum);
835 switch(IntResult.type) {
836 case IEEE754_ToInt_IS_INT:
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700837 QCBOREncode_AddInt64(pMe, IntResult.integer.is_signed);
Laurence Lundblade240ca822024-01-16 11:11:00 -0700838 return;
839 case IEEE754_ToInt_IS_UINT:
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700840 QCBOREncode_AddUInt64(pMe, IntResult.integer.un_signed);
Laurence Lundblade240ca822024-01-16 11:11:00 -0700841 return;
842 case IEEE754_To_int_NaN:
Laurence Lundbladee026f4f2024-01-18 13:48:34 -0700843 dNum = NAN;
844 bNoNaNPayload = true;
845 break;
Laurence Lundblade240ca822024-01-16 11:11:00 -0700846 case IEEE754_ToInt_NO_CONVERSION:
847 bNoNaNPayload = true;
848 }
849 } else {
850 bNoNaNPayload = false;
851 }
852
853 FloatResult = IEEE754_DoubleToSmaller(dNum, true, bNoNaNPayload);
854
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700855 QCBOREncode_Private_AddType7(pMe, (uint8_t)FloatResult.uSize, FloatResult.uValue);
Laurence Lundblade240ca822024-01-16 11:11:00 -0700856
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800857#else /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700858 QCBOREncode_AddDoubleNoPreferred(pMe, dNum);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800859#endif /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700860}
Laurence Lundblade9682a532020-06-06 18:33:04 -0700861
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700862
Laurence Lundbladed6e13022023-11-26 10:14:02 -0700863
864
865/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800866 * Public functions for adding a float. See qcbor/qcbor_encode.h
867 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700868void
869QCBOREncode_AddFloatNoPreferred(QCBOREncodeContext *pMe, const float fNum)
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700870{
Laurence Lundblade240ca822024-01-16 11:11:00 -0700871#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
872 if(pMe->uMode >= QCBOR_ENCODE_MODE_PREFERRED) {
873 pMe->uError = QCBOR_ERR_NOT_PREFERRED;
874 return;
875 }
876#endif /* ! QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700877 QCBOREncode_Private_AddType7(pMe,
878 sizeof(uint32_t),
879 UsefulBufUtil_CopyFloatToUint32(fNum));
Laurence Lundblade9682a532020-06-06 18:33:04 -0700880}
881
882
883/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800884 * Public functions for adding a float. See qcbor/qcbor_encode.h
Laurence Lundblade9682a532020-06-06 18:33:04 -0700885 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700886void
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700887QCBOREncode_AddFloat(QCBOREncodeContext *pMe, float fNum)
Laurence Lundblade9682a532020-06-06 18:33:04 -0700888{
Laurence Lundbladeb275cdc2020-07-12 12:34:38 -0700889#ifndef QCBOR_DISABLE_PREFERRED_FLOAT
Laurence Lundblade240ca822024-01-16 11:11:00 -0700890 IEEE754_union FloatResult;
891 bool bNoNaNPayload;
892 struct IEEE754_ToInt IntResult;
Laurence Lundblade2feb1e12020-07-15 03:50:45 -0700893
Laurence Lundblade240ca822024-01-16 11:11:00 -0700894 if(pMe->uMode == QCBOR_ENCODE_MODE_DCBOR) {
895 IntResult = IEEE754_SingleToInt(fNum);
896 switch(IntResult.type) {
897 case IEEE754_ToInt_IS_INT:
898 QCBOREncode_AddInt64(pMe, IntResult.integer.is_signed);
899 return;
Laurence Lundbladee026f4f2024-01-18 13:48:34 -0700900 case IEEE754_ToInt_IS_UINT:
Laurence Lundblade240ca822024-01-16 11:11:00 -0700901 QCBOREncode_AddUInt64(pMe, IntResult.integer.un_signed);
902 return;
903 case IEEE754_To_int_NaN:
Laurence Lundbladee026f4f2024-01-18 13:48:34 -0700904 fNum = NAN;
905 bNoNaNPayload = true;
906 break;
Laurence Lundblade240ca822024-01-16 11:11:00 -0700907 case IEEE754_ToInt_NO_CONVERSION:
908 bNoNaNPayload = true;
909 }
910 } else {
911 bNoNaNPayload = false;
912 }
913
914 FloatResult = IEEE754_SingleToHalf(fNum, bNoNaNPayload);
915
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -0700916 QCBOREncode_Private_AddType7(pMe, (uint8_t)FloatResult.uSize, FloatResult.uValue);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800917#else /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700918 QCBOREncode_AddFloatNoPreferred(pMe, fNum);
Laurence Lundbladee2c893c2020-12-26 17:41:53 -0800919#endif /* QCBOR_DISABLE_PREFERRED_FLOAT */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800920}
Máté Tóth-Pálef5f07a2021-09-17 19:31:37 +0200921#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
Laurence Lundblade067035b2018-11-28 17:35:25 -0800922
923
Laurence Lundbladedd6e76e2021-03-10 01:54:01 -0700924#ifndef QCBOR_DISABLE_EXP_AND_MANTISSA
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700925/**
926 * @brief Semi-private method to add bigfloats and decimal fractions.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800927 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700928 * @param[in] pMe The encoding context to add the value to.
929 * @param[in] uTag The type 6 tag indicating what this is to be.
930 * @param[in] BigNumMantissa Is @ref NULLUsefulBufC if mantissa is an
931 * @c int64_t or the actual big number mantissa
932 * if not.
933 * @param[in] bBigNumIsNegative This is @c true if the big number is negative.
934 * @param[in] nMantissa The @c int64_t mantissa if it is not a big number.
935 * @param[in] nExponent The exponent.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800936 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700937 * This outputs either the @ref CBOR_TAG_DECIMAL_FRACTION or
938 * @ref CBOR_TAG_BIGFLOAT tag. if @c uTag is @ref CBOR_TAG_INVALID64,
939 * then this outputs the "borrowed" content format.
940 *
941 * The tag content output by this is an array with two members, the
942 * exponent and then the mantissa. The mantissa can be either a big
943 * number or an @c int64_t.
944 *
945 * This implementation cannot output an exponent further from 0 than
946 * @c INT64_MAX.
947 *
948 * To output a mantissa that is between INT64_MAX and UINT64_MAX from 0,
949 * it must be as a big number.
950 *
951 * Typically, QCBOREncode_AddDecimalFraction(), QCBOREncode_AddBigFloat(),
952 * QCBOREncode_AddDecimalFractionBigNum() or QCBOREncode_AddBigFloatBigNum()
953 * is called instead of this.
Laurence Lundblade59289e52019-12-30 13:44:37 -0800954 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700955void
956QCBOREncode_Private_AddExpMantissa(QCBOREncodeContext *pMe,
957 const uint64_t uTag,
958 const UsefulBufC BigNumMantissa,
959 const bool bBigNumIsNegative,
960 const int64_t nMantissa,
961 const int64_t nExponent)
Laurence Lundblade59289e52019-12-30 13:44:37 -0800962{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800963 /* This is for encoding either a big float or a decimal fraction,
964 * both of which are an array of two items, an exponent and a
965 * mantissa. The difference between the two is that the exponent
966 * is base-2 for big floats and base-10 for decimal fractions, but
967 * that has no effect on the code here.
Laurence Lundbladeee851742020-01-08 08:37:05 -0800968 */
Laurence Lundbladeae66d3f2020-09-14 18:12:08 -0700969 if(uTag != CBOR_TAG_INVALID64) {
970 QCBOREncode_AddTag(pMe, uTag);
971 }
Laurence Lundblade59289e52019-12-30 13:44:37 -0800972 QCBOREncode_OpenArray(pMe);
973 QCBOREncode_AddInt64(pMe, nExponent);
974 if(!UsefulBuf_IsNULLC(BigNumMantissa)) {
975 if(bBigNumIsNegative) {
976 QCBOREncode_AddNegativeBignum(pMe, BigNumMantissa);
977 } else {
978 QCBOREncode_AddPositiveBignum(pMe, BigNumMantissa);
979 }
980 } else {
981 QCBOREncode_AddInt64(pMe, nMantissa);
982 }
983 QCBOREncode_CloseArray(pMe);
984}
Laurence Lundbladedd6e76e2021-03-10 01:54:01 -0700985#endif /* QCBOR_DISABLE_EXP_AND_MANTISSA */
Laurence Lundblade59289e52019-12-30 13:44:37 -0800986
987
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700988/**
989 * @brief Semi-private method to open a map, array or bstr-wrapped CBOR
Laurence Lundblade1fa579b2020-11-25 00:31:37 -0800990 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700991 * @param[in] pMe The context to add to.
992 * @param[in] uMajorType The major CBOR type to close
993 *
994 * Call QCBOREncode_OpenArray(), QCBOREncode_OpenMap() or
995 * QCBOREncode_BstrWrap() instead of this.
Laurence Lundblade274ddef2022-05-17 09:12:23 -0700996 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -0700997void
998QCBOREncode_Private_OpenMapOrArray(QCBOREncodeContext *pMe,
999 const uint8_t uMajorType)
Laurence Lundblade067035b2018-11-28 17:35:25 -08001000{
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001001 /* Add one item to the nesting level we are in for the new map or array */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001002 QCBOREncode_Private_IncrementMapOrArrayCount(pMe);
Laurence Lundbladed39cd392019-01-11 18:17:38 -08001003
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001004 /* The offset where the length of an array or map will get written
1005 * is stored in a uint32_t, not a size_t to keep stack usage
1006 * smaller. This checks to be sure there is no wrap around when
1007 * recording the offset. Note that on 64-bit machines CBOR larger
1008 * than 4GB can be encoded as long as no array/map offsets occur
1009 * past the 4GB mark, but the public interface says that the
1010 * maximum is 4GB to keep the discussion simpler.
1011 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001012 size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(pMe->OutBuf));
Laurence Lundbladed39cd392019-01-11 18:17:38 -08001013
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001014 /* QCBOR_MAX_ARRAY_OFFSET is slightly less than UINT32_MAX so this
1015 * code can run on a 32-bit machine and tests can pass on a 32-bit
1016 * machine. If it was exactly UINT32_MAX, then this code would not
1017 * compile or run on a 32-bit machine and an #ifdef or some machine
1018 * size detection would be needed reducing portability.
1019 */
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -08001020 if(uEndPosition >= QCBOR_MAX_ARRAY_OFFSET) {
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001021 pMe->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
Laurence Lundblade3e0a45c2020-11-05 11:12:04 -08001022
1023 } else {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001024 /* Increase nesting level because this is a map or array. Cast
1025 * from size_t to uin32_t is safe because of check above.
1026 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001027 pMe->uError = Nesting_Increase(&(pMe->nesting), uMajorType, (uint32_t)uEndPosition);
Laurence Lundblade1ef8b2d2018-12-14 23:13:34 -08001028 }
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001029}
1030
Laurence Lundblade59289e52019-12-30 13:44:37 -08001031
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001032/**
1033 * @brief Semi-private method to open a map, array with indefinite length
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001034 *
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001035 * @param[in] pMe The context to add to.
1036 * @param[in] uMajorType The major CBOR type to close
1037 *
1038 * Call QCBOREncode_OpenArrayIndefiniteLength() or
1039 * QCBOREncode_OpenMapIndefiniteLength() instead of this.
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001040 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001041void
1042QCBOREncode_Private_OpenMapOrArrayIndefiniteLength(QCBOREncodeContext *pMe,
1043 const uint8_t uMajorType)
Jan Jongboom4a93a662019-07-25 08:44:58 +02001044{
Laurence Lundblade240ca822024-01-16 11:11:00 -07001045#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
1046 if(pMe->uMode >= QCBOR_ENCODE_MODE_PREFERRED) {
1047 pMe->uError = QCBOR_ERR_NOT_PREFERRED;
1048 return;
1049 }
1050#endif /* ! QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001051 /* Insert the indefinite length marker (0x9f for arrays, 0xbf for maps) */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001052 QCBOREncode_Private_AppendCBORHead(pMe, uMajorType, 0, 0);
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001053
1054 /* Call the definite-length opener just to do the bookkeeping for
1055 * nesting. It will record the position of the opening item in the
1056 * encoded output but this is not used when closing this open.
1057 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001058 QCBOREncode_Private_OpenMapOrArray(pMe, uMajorType);
Jan Jongboom4a93a662019-07-25 08:44:58 +02001059}
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001060
Laurence Lundbladeee851742020-01-08 08:37:05 -08001061
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001062/**
1063 * @brief Semi-private method to close a map, array or bstr wrapped CBOR
1064 *
1065 * @param[in] pMe The context to add to.
1066 * @param[in] uMajorType The major CBOR type to close.
1067 *
1068 * Call QCBOREncode_CloseArray() or QCBOREncode_CloseMap() instead of this.
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001069 */
Laurence Lundblade240ca822024-01-16 11:11:00 -07001070void
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001071QCBOREncode_Private_CloseMapOrArray(QCBOREncodeContext *pMe,
1072 const uint8_t uMajorType)
Laurence Lundblade240ca822024-01-16 11:11:00 -07001073{
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001074 QCBOREncode_Private_InsertCBORHead(pMe, uMajorType, Nesting_GetCount(&(pMe->nesting)));
Laurence Lundblade240ca822024-01-16 11:11:00 -07001075}
1076
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001077
Laurence Lundblade240ca822024-01-16 11:11:00 -07001078void
1079QCBOREncode_CloseMapUnsorted(QCBOREncodeContext *pMe)
1080{
Laurence Lundbladed98ffbf2024-01-27 23:27:59 -07001081 QCBOREncode_Private_InsertCBORHead(pMe, CBOR_MAJOR_TYPE_MAP, Nesting_GetCount(&(pMe->nesting)));
Laurence Lundblade240ca822024-01-16 11:11:00 -07001082}
1083
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001084
1085/**
1086 * @brief Decode a CBOR item head.
1087 *
1088 * @param[in] pUInBuf UsefulInputBuf to read from.
1089 * @param[out] pnMajorType Major type of decoded head.
1090 * @param[out] puArgument Argument of decoded head.
1091 * @param[out] pnAdditionalInfo Additional info from decoded head.
1092 *
1093 * @return SUCCESS if a head was decoded
1094 * HIT_END if there were not enough bytes to decode a head
1095 * UNSUPPORTED if the decoded item is not one that is supported
1096 *
1097 * This is copied from qcbor_decode.c rather than referenced. This
1098 * makes the core decoder 60 bytes smaller because it gets inlined.
1099 * It would not get inlined if it was referenced. It is important to
1100 * make the core decoder as small as possible. The copy here does make
1101 * map sorting 200 bytes bigger, but map sorting is rarely used in
1102 * environments that need small object code. It would also make
1103 * qcbor_encode.c depend on qcbor_decode.c
1104 *
1105 * This is also super stable and tested. It implements the very
1106 * well-defined part of CBOR that will never change. So this won't
1107 * change.
1108 */
1109static QCBORError
1110QCBOREncodePriv_DecodeHead(UsefulInputBuf *pUInBuf,
1111 int *pnMajorType,
1112 uint64_t *puArgument,
1113 int *pnAdditionalInfo)
1114{
1115 QCBORError uReturn;
1116
1117 /* Get the initial byte that every CBOR data item has and break it
1118 * down. */
1119 const int nInitialByte = (int)UsefulInputBuf_GetByte(pUInBuf);
1120 const int nTmpMajorType = nInitialByte >> 5;
1121 const int nAdditionalInfo = nInitialByte & 0x1f;
1122
1123 /* Where the argument accumulates */
1124 uint64_t uArgument;
1125
1126 if(nAdditionalInfo >= LEN_IS_ONE_BYTE && nAdditionalInfo <= LEN_IS_EIGHT_BYTES) {
1127 /* Need to get 1,2,4 or 8 additional argument bytes. Map
1128 * LEN_IS_ONE_BYTE..LEN_IS_EIGHT_BYTES to actual length.
1129 */
1130 static const uint8_t aIterate[] = {1,2,4,8};
1131
1132 /* Loop getting all the bytes in the argument */
1133 uArgument = 0;
1134 for(int i = aIterate[nAdditionalInfo - LEN_IS_ONE_BYTE]; i; i--) {
1135 /* This shift and add gives the endian conversion. */
1136 uArgument = (uArgument << 8) + UsefulInputBuf_GetByte(pUInBuf);
1137 }
1138 } else if(nAdditionalInfo >= ADDINFO_RESERVED1 && nAdditionalInfo <= ADDINFO_RESERVED3) {
1139 /* The reserved and thus-far unused additional info values */
1140 uReturn = QCBOR_ERR_UNSUPPORTED;
1141 goto Done;
1142 } else {
1143 /* Less than 24, additional info is argument or 31, an
1144 * indefinite-length. No more bytes to get.
1145 */
1146 uArgument = (uint64_t)nAdditionalInfo;
1147 }
1148
1149 if(UsefulInputBuf_GetError(pUInBuf)) {
1150 uReturn = QCBOR_ERR_HIT_END;
1151 goto Done;
1152 }
1153
1154 /* All successful if arrived here. */
1155 uReturn = QCBOR_SUCCESS;
1156 *pnMajorType = nTmpMajorType;
1157 *puArgument = uArgument;
1158 *pnAdditionalInfo = nAdditionalInfo;
1159
1160Done:
1161 return uReturn;
1162}
1163
1164
1165/**
1166 * @brief Consume the next item from a UsefulInputBuf.
1167 *
1168 * @param[in] pInBuf UsefulInputBuf from which to consume item.
1169 *
1170 * Recursive, but stack usage is light and encoding depth limit
1171 */
1172static QCBORError
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001173QCBOR_Private_ConsumeNext(UsefulInputBuf *pInBuf)
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001174{
1175 int nMajor;
1176 uint64_t uArgument;
1177 int nAdditional;
1178 uint16_t uItemCount;
1179 uint16_t uMul;
1180 uint16_t i;
1181 QCBORError uCBORError;
1182
1183 uCBORError = QCBOREncodePriv_DecodeHead(pInBuf, &nMajor, &uArgument, &nAdditional);
1184 if(uCBORError != QCBOR_SUCCESS) {
1185 return uCBORError;
1186 }
1187
1188 uMul = 1;
1189
1190 switch(nMajor) {
1191 case CBOR_MAJOR_TYPE_POSITIVE_INT: /* Major type 0 */
1192 case CBOR_MAJOR_TYPE_NEGATIVE_INT: /* Major type 1 */
1193 break;
1194
1195 case CBOR_MAJOR_TYPE_SIMPLE:
1196 return uArgument == CBOR_SIMPLE_BREAK ? 1 : 0;
1197 break;
1198
1199 case CBOR_MAJOR_TYPE_BYTE_STRING:
1200 case CBOR_MAJOR_TYPE_TEXT_STRING:
1201 if(nAdditional == LEN_IS_INDEFINITE) {
1202 /* Segments of indefinite length */
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001203 while(QCBOR_Private_ConsumeNext(pInBuf) == 0);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001204 }
1205 (void)UsefulInputBuf_GetBytes(pInBuf, uArgument);
1206 break;
1207
1208 case CBOR_MAJOR_TYPE_TAG:
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001209 QCBOR_Private_ConsumeNext(pInBuf);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001210 break;
1211
1212 case CBOR_MAJOR_TYPE_MAP:
1213 uMul = 2;
1214 /* Fallthrough */
1215 case CBOR_MAJOR_TYPE_ARRAY:
1216 uItemCount = (uint16_t)uArgument * uMul;
1217 if(nAdditional == LEN_IS_INDEFINITE) {
1218 uItemCount = UINT16_MAX;
1219 }
1220 for(i = uItemCount; i > 0; i--) {
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001221 if(QCBOR_Private_ConsumeNext(pInBuf)) {
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001222 /* End of indefinite length */
1223 break;
1224 }
1225 }
1226 break;
1227 }
1228
1229 return QCBOR_SUCCESS;
1230}
1231
1232
1233/**
1234 * @brief Decoded next item to get its length.
1235 *
1236 * Decode the next item in map no matter what type it is. It works
1237 * recursively when an item is a map or array It returns offset just
1238 * past the item decoded or zero there are no more items in the output
1239 * buffer.
1240 *
1241 * This doesn't distinguish between end of the input and an error
1242 * because it is used to decode stuff we encoded into a buffer, not
1243 * stuff that came in from outside. We still want a check for safety
1244 * in case of bugs here, but it is OK to report end of input on error.
1245 */
1246static uint32_t
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001247QCBOREncode_Private_DecodeNextInMap(QCBOREncodeContext *pMe, uint32_t uStart)
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001248{
1249 UsefulInputBuf InBuf;
1250 UsefulBufC EncodedMapBytes;
1251 QCBORError uCBORError;
1252
1253 EncodedMapBytes = UsefulOutBuf_OutUBufOffset(&(pMe->OutBuf), uStart);
1254 if(UsefulBuf_IsNULLC(EncodedMapBytes)) {
1255 return 0;
1256 }
1257
1258 UsefulInputBuf_Init(&InBuf, EncodedMapBytes);
1259
1260 /* This is always used on maps, so consume two, the label and the value */
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001261 uCBORError = QCBOR_Private_ConsumeNext(&InBuf);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001262 if(uCBORError) {
1263 return 0;
1264 }
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001265 uCBORError = QCBOR_Private_ConsumeNext(&InBuf);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001266 if(uCBORError) {
1267 return 0;
1268 }
1269
1270 /* Cast is safe because this is QCBOR which limits sizes to UINT32_MAX */
1271 return (uint32_t)UsefulInputBuf_Tell(&InBuf);
1272}
1273
1274
1275/**
1276 * @brief Sort items lexographically by encoded labels.
1277 *
1278 * @param[in] pMe Encoding context.
1279 * @param[in] uStart Offset in outbuf of first item for sorting.
1280 *
1281 * This reaches into the UsefulOutBuf in the encoding context and
1282 * sorts encoded CBOR items. The byte offset start of the items is at
1283 * @c uStart and it goes to the end of valid bytes in the
1284 * UsefulOutBuf.
1285 */
1286static void
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001287QCBOREncode_Private_SortMap(QCBOREncodeContext *pMe, uint32_t uStart)
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001288{
1289 bool bSwapped;
1290 int nComparison;
1291 uint32_t uLen2;
1292 uint32_t uLen1;
1293 uint32_t uStart1;
1294 uint32_t uStart2;
1295
1296 if(pMe->uError != QCBOR_SUCCESS) {
1297 return;
1298 }
1299
1300 /* Bubble sort because the sizes of all the items are not the
1301 * same. It works with adjacent pairs so the swap is not too
1302 * difficult even though sizes are different.
1303 *
1304 * While bubble sort is n-squared, it seems OK here because n will
1305 * usually be small and the comparison and swap functions aren't
1306 * too CPU intensive.
1307 *
1308 * Another approach would be to have an array of offsets to the
1309 * items. However this requires memory allocation and the swap
1310 * operation for quick sort or such is complicated because the item
1311 * sizes are not the same and overlap may occur in the bytes being
1312 * swapped.
1313 */
1314 do {
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001315 uLen1 = QCBOREncode_Private_DecodeNextInMap(pMe, uStart);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001316 if(uLen1 == 0) {
1317 /* It's an empty map. Nothing to do. */
1318 break;
1319 }
1320 uStart1 = uStart;
1321 uStart2 = uStart1 + uLen1;
1322 bSwapped = false;
1323
1324 while(1) {
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001325 uLen2 = QCBOREncode_Private_DecodeNextInMap(pMe, uStart2);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001326 if(uLen2 == 0) {
1327 break;
1328 }
1329
1330 nComparison = UsefulOutBuf_Compare(&(pMe->OutBuf), uStart1, uStart2);
1331 if(nComparison < 0) {
1332 UsefulOutBuf_Swap(&(pMe->OutBuf), uStart1, uStart2, uStart2 + uLen2);
1333 uStart1 = uStart1 + uLen2;
1334 bSwapped = true;
1335 } else {
1336 uStart1 = uStart2;
1337 }
1338 uStart2 = uStart2 + uLen2;
1339 }
1340 } while(bSwapped);
1341}
1342
1343
1344/*
1345 * Public functions for closing sorted maps. See qcbor/qcbor_encode.h
1346 */
1347void QCBOREncode_CloseAndSortMap(QCBOREncodeContext *pMe)
1348{
1349 uint32_t uStart;
1350
1351 /* The Header for the map we are about to sort hasn't been
1352 * inserted yet, so uStart is the position of the first item
1353 * and the end out the UsefulOutBuf data is the end of the
1354 * items we are about to sort.
1355 */
1356 uStart = Nesting_GetStartPos(&(pMe->nesting));
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001357 QCBOREncode_Private_SortMap(pMe, uStart);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001358
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001359 QCBOREncode_Private_InsertCBORHead(pMe, CBOR_MAJOR_TYPE_MAP, Nesting_GetCount(&(pMe->nesting)));
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001360}
1361
1362
1363/*
1364 * Public functions for closing sorted maps. See qcbor/qcbor_encode.h
1365 */
1366void QCBOREncode_CloseAndSortMapIndef(QCBOREncodeContext *pMe)
1367{
1368 uint32_t uStart;
1369
1370 uStart = Nesting_GetStartPos(&(pMe->nesting));
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001371 QCBOREncode_Private_SortMap(pMe, uStart);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001372
Laurence Lundblade3b703b82024-01-27 20:17:20 -07001373 QCBOREncode_Private_CloseMapOrArrayIndefiniteLength(pMe, CBOR_MAJOR_NONE_TYPE_MAP_INDEFINITE_LEN);
Laurence Lundbladed6e13022023-11-26 10:14:02 -07001374}
1375
1376
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001377/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001378 * Public functions for closing bstr wrapping. See qcbor/qcbor_encode.h
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001379 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001380void
1381QCBOREncode_CloseBstrWrap2(QCBOREncodeContext *pMe,
1382 const bool bIncludeCBORHead,
1383 UsefulBufC *pWrappedCBOR)
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001384{
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001385 const size_t uInsertPosition = Nesting_GetStartPos(&(pMe->nesting));
1386 const size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(pMe->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001387
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001388 /* This subtraction can't go negative because the UsefulOutBuf
1389 * always only grows and never shrinks. UsefulOutBut itself also
1390 * has defenses such that it won't write where it should not even
1391 * if given incorrect input lengths.
1392 */
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001393 const size_t uBstrLen = uEndPosition - uInsertPosition;
1394
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001395 /* Actually insert */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001396 QCBOREncode_Private_InsertCBORHead(pMe, CBOR_MAJOR_TYPE_BYTE_STRING, uBstrLen);
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001397
1398 if(pWrappedCBOR) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001399 /* Return pointer and length to the enclosed encoded CBOR. The
1400 * intended use is for it to be hashed (e.g., SHA-256) in a COSE
1401 * implementation. This must be used right away, as the pointer
1402 * and length go invalid on any subsequent calls to this
1403 * function because there might be calls to
1404 * InsertEncodedTypeAndNumber() that slides data to the right.
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001405 */
1406 size_t uStartOfNew = uInsertPosition;
1407 if(!bIncludeCBORHead) {
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001408 /* Skip over the CBOR head to just get the inserted bstr */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001409 const size_t uNewEndPosition = UsefulOutBuf_GetEndPosition(&(pMe->OutBuf));
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001410 uStartOfNew += uNewEndPosition - uEndPosition;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001411 }
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001412 const UsefulBufC PartialResult = UsefulOutBuf_OutUBuf(&(pMe->OutBuf));
Laurence Lundbladec9f0fbc2020-02-07 10:48:33 +00001413 *pWrappedCBOR = UsefulBuf_Tail(PartialResult, uStartOfNew);
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001414 }
1415}
1416
Laurence Lundbladeee851742020-01-08 08:37:05 -08001417
Jan Jongboom4a93a662019-07-25 08:44:58 +02001418/*
Laurence Lundblade8d3b8552021-06-10 11:11:54 -07001419 * Public function for canceling a bstr wrap. See qcbor/qcbor_encode.h
1420 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001421void
1422QCBOREncode_CancelBstrWrap(QCBOREncodeContext *pMe)
Laurence Lundblade8d3b8552021-06-10 11:11:54 -07001423{
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001424 if(QCBOREncode_Private_CheckDecreaseNesting(pMe, CBOR_MAJOR_TYPE_BYTE_STRING)) {
Laurence Lundblade274ddef2022-05-17 09:12:23 -07001425 return;
1426 }
1427
Laurence Lundblade8d3b8552021-06-10 11:11:54 -07001428#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade274ddef2022-05-17 09:12:23 -07001429 const size_t uCurrent = UsefulOutBuf_GetEndPosition(&(pMe->OutBuf));
1430 if(pMe->nesting.pCurrentNesting->uStart != uCurrent) {
1431 pMe->uError = QCBOR_ERR_CANNOT_CANCEL;
1432 return;
Laurence Lundblade8d3b8552021-06-10 11:11:54 -07001433 }
1434 /* QCBOREncode_CancelBstrWrap() can't correctly undo
1435 * QCBOREncode_BstrWrapInMap() or QCBOREncode_BstrWrapInMapN(). It
1436 * can't undo the labels they add. It also doesn't catch the error
1437 * of using it this way. QCBOREncode_CancelBstrWrap() is used
1438 * infrequently and the the result is incorrect CBOR, not a
1439 * security hole, so no extra code or state is added to handle this
1440 * condition.
1441 */
1442#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
1443
1444 Nesting_Decrease(&(pMe->nesting));
1445 Nesting_Decrement(&(pMe->nesting));
1446}
1447
1448
1449/*
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001450 * Public function for opening a byte string. See qcbor/qcbor_encode.h
1451 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001452void
1453QCBOREncode_OpenBytes(QCBOREncodeContext *pMe, UsefulBuf *pPlace)
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001454{
1455 *pPlace = UsefulOutBuf_GetOutPlace(&(pMe->OutBuf));
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001456#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Paul Liétar79789772022-07-26 20:33:18 +01001457 // TODO: is this right?
1458 uint8_t uMajorType = Nesting_GetMajorType(&(pMe->nesting));
1459 if(uMajorType == CBOR_MAJOR_NONE_TYPE_OPEN_BSTR) {
1460 pMe->uError = QCBOR_ERR_OPEN_BYTE_STRING;
1461 return;
1462 }
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001463#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
1464
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001465 QCBOREncode_Private_OpenMapOrArray(pMe, CBOR_MAJOR_NONE_TYPE_OPEN_BSTR);
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001466}
1467
1468
1469/*
1470 * Public function for closing a byte string. See qcbor/qcbor_encode.h
1471 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001472void
1473QCBOREncode_CloseBytes(QCBOREncodeContext *pMe, const size_t uAmount)
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001474{
1475 UsefulOutBuf_Advance(&(pMe->OutBuf), uAmount);
1476 if(UsefulOutBuf_GetError(&(pMe->OutBuf))) {
1477 /* Advance too far. Normal off-end error handling in effect here. */
1478 return;
1479 }
1480
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001481 QCBOREncode_Private_InsertCBORHead(pMe, CBOR_MAJOR_NONE_TYPE_OPEN_BSTR, uAmount);
Laurence Lundbladeb24faef2022-04-26 11:03:08 -06001482}
1483
1484
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001485/**
1486 * @brief Semi-private method to close a map, array with indefinite length
1487 *
1488 * @param[in] pMe The context to add to.
1489 * @param[in] uMajorType The major CBOR type to close.
1490 *
1491 * Call QCBOREncode_CloseArrayIndefiniteLength() or
1492 * QCBOREncode_CloseMapIndefiniteLength() instead of this.
Jan Jongboom4a93a662019-07-25 08:44:58 +02001493 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001494void
1495QCBOREncode_Private_CloseMapOrArrayIndefiniteLength(QCBOREncodeContext *pMe,
1496 const uint8_t uMajorType)
Jan Jongboom4a93a662019-07-25 08:44:58 +02001497{
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001498 if(QCBOREncode_Private_CheckDecreaseNesting(pMe, uMajorType)) {
Laurence Lundblade274ddef2022-05-17 09:12:23 -07001499 return;
Jan Jongboom4a93a662019-07-25 08:44:58 +02001500 }
Laurence Lundbladedaefdec2020-11-02 20:22:03 -08001501
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001502 /* Append the break marker (0xff for both arrays and maps) */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001503 QCBOREncode_Private_AppendCBORHead(pMe, CBOR_MAJOR_NONE_TYPE_SIMPLE_BREAK, CBOR_SIMPLE_BREAK, 0);
Laurence Lundblade274ddef2022-05-17 09:12:23 -07001504 Nesting_Decrease(&(pMe->nesting));
Jan Jongboom4a93a662019-07-25 08:44:58 +02001505}
1506
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001507
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001508/*
Laurence Lundblade8d3b8552021-06-10 11:11:54 -07001509 * Public function to finish and get the encoded result. See qcbor/qcbor_encode.h
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001510 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001511QCBORError
1512QCBOREncode_Finish(QCBOREncodeContext *pMe, UsefulBufC *pEncodedCBOR)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001513{
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001514 QCBORError uReturn = QCBOREncode_GetErrorState(pMe);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001515
Laurence Lundblade067035b2018-11-28 17:35:25 -08001516 if(uReturn != QCBOR_SUCCESS) {
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001517 goto Done;
Laurence Lundblade067035b2018-11-28 17:35:25 -08001518 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001519
Laurence Lundbladedaefdec2020-11-02 20:22:03 -08001520#ifndef QCBOR_DISABLE_ENCODE_USAGE_GUARDS
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001521 if(Nesting_IsInNest(&(pMe->nesting))) {
Laurence Lundblade067035b2018-11-28 17:35:25 -08001522 uReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001523 goto Done;
1524 }
Laurence Lundbladee2c893c2020-12-26 17:41:53 -08001525#endif /* QCBOR_DISABLE_ENCODE_USAGE_GUARDS */
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001526
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001527 *pEncodedCBOR = UsefulOutBuf_OutUBuf(&(pMe->OutBuf));
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001528
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001529Done:
Laurence Lundblade067035b2018-11-28 17:35:25 -08001530 return uReturn;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001531}
1532
Laurence Lundblade0595e932018-11-02 22:22:47 +07001533
Laurence Lundblade067035b2018-11-28 17:35:25 -08001534/*
Laurence Lundblade1fa579b2020-11-25 00:31:37 -08001535 * Public functions to get size of the encoded result. See qcbor/qcbor_encode.h
Laurence Lundblade067035b2018-11-28 17:35:25 -08001536 */
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001537QCBORError
1538QCBOREncode_FinishGetSize(QCBOREncodeContext *pMe, size_t *puEncodedLen)
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001539{
Laurence Lundbladeda3f0822018-09-18 19:49:02 -07001540 UsefulBufC Enc;
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001541
Laurence Lundblade8e36f812024-01-26 10:59:29 -07001542 QCBORError nReturn = QCBOREncode_Finish(pMe, &Enc);
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001543
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001544 if(nReturn == QCBOR_SUCCESS) {
Laurence Lundbladeda3f0822018-09-18 19:49:02 -07001545 *puEncodedLen = Enc.len;
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001546 }
Laurence Lundblade3aee3a32018-12-17 16:17:45 -08001547
Laurence Lundbladeb69cad72018-09-13 11:09:01 -07001548 return nReturn;
1549}