blob: 40b08e89f3aae6ecb19020ff229946eb2f3f0a1c [file] [log] [blame]
Michael Eckel5c531332020-03-02 01:35:30 +01001/*==============================================================================
2 Copyright (c) 2016-2018, The Linux Foundation.
3 Copyright (c) 2018-2020, Laurence Lundblade.
4 All rights reserved.
5
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/*=============================================================================
35 FILE: qcbor.h
36
37 DESCRIPTION: This is the full public API and data structures for QCBOR
38
39 EDIT HISTORY FOR FILE:
40
41 This section contains comments describing changes made to the module.
42 Notice that changes are listed in reverse chronological order.
43
44 when who what, where, why
45 -------- ---- ---------------------------------------------------
46 02/07/2020 llundblade QCBOREncode_EncodeHead() and other for bstr hashing.
47 01/25/2020 llundblade Cleaner handling of too-long encoded string input.
48 01/08/2020 llundblade Documentation corrections & improved code formatting.
49 12/30/19 llundblade Add support for decimal fractions and bigfloats.
50 08/7/19 llundblade Better handling of not well-formed encode and decode.
51 07/31/19 llundblade New error code for better end of data handling.
52 7/25/19 janjongboom Add indefinite length encoding for maps and arrays.
53 05/26/19 llundblade Add QCBOREncode_GetErrorState() and _IsBufferNULL().
54 04/26/19 llundblade Big documentation & style update. No interface change.
55 02/16/19 llundblade Redesign MemPool to fix memory access alignment bug.
56 12/18/18 llundblade Move decode malloc optional code to separate repo.
57 12/13/18 llundblade Documentatation improvements.
58 11/29/18 llundblade Rework to simpler handling of tags and labels.
59 11/9/18 llundblade Error codes are now enums.
60 11/1/18 llundblade Floating support.
61 10/31/18 llundblade Switch to one license that is almost BSD-3.
62 10/15/18 llundblade indefinite-length maps and arrays supported
63 10/8/18 llundblade indefinite-length strings supported
64 09/28/18 llundblade Added bstr wrapping feature for COSE implementation.
65 07/05/17 llundbla Add bstr wrapping of maps/arrays for COSE.
66 03/01/17 llundbla More data types; decoding improvements and fixes.
67 11/13/16 llundbla Integrate most TZ changes back into github version.
68 09/30/16 gkanike Porting to TZ.
69 03/15/16 llundbla Initial Version.
70
71 =============================================================================*/
72
73#ifndef __QCBOR__qcbor__
74#define __QCBOR__qcbor__
75
76
77/* ===========================================================================
78 BEGINNING OF PRIVATE PART OF THIS FILE
79
80 Caller of QCBOR should not reference any of the details below up until
81 the start of the public part.
82 ========================================================================== */
83
84/*
85 Standard integer types are used in the interface to be precise about
86 sizes to be better at preventing underflow/overflow errors.
87 */
88#include <stdint.h>
89#include <stdbool.h>
90#include "UsefulBuf.h"
91
92#ifdef __cplusplus
93extern "C" {
94#ifdef 0
95} // Keep editor indention formatting happy
96#endif
97#endif
98
99/*
100 The maxium nesting of arrays and maps when encoding or decoding.
101 (Further down in the file there is a definition that refers to this
102 that is public. This is done this way so there can be a nice
103 separation of public and private parts in this file.
104*/
105#define QCBOR_MAX_ARRAY_NESTING1 15 // Do not increase this over 255
106
107
108/* The largest offset to the start of an array or map. It is slightly
109 less than UINT32_MAX so the error condition can be tests on 32-bit machines.
110 UINT32_MAX comes from uStart in QCBORTrackNesting being a uin32_t.
111
112 This will cause trouble on a machine where size_t is less than 32-bits.
113 */
114#define QCBOR_MAX_ARRAY_OFFSET (UINT32_MAX - 100)
115
116/*
117 PRIVATE DATA STRUCTURE
118
119 Holds the data for tracking array and map nesting during encoding. Pairs up
120 with the Nesting_xxx functions to make an "object" to handle nesting encoding.
121
122 uStart is a uint32_t instead of a size_t to keep the size of this
123 struct down so it can be on the stack without any concern. It would be about
124 double if size_t was used instead.
125
126 Size approximation (varies with CPU/compiler):
127 64-bit machine: (15 + 1) * (4 + 2 + 1 + 1 pad) + 8 = 136 bytes
128 32-bit machine: (15 + 1) * (4 + 2 + 1 + 1 pad) + 4 = 132 bytes
129*/
130typedef struct __QCBORTrackNesting {
131 // PRIVATE DATA STRUCTURE
132 struct {
133 // See function QCBOREncode_OpenMapOrArray() for details on how this works
134 uint32_t uStart; // uStart is the byte position where the array starts
135 uint16_t uCount; // Number of items in the arrary or map; counts items
136 // in a map, not pairs of items
137 uint8_t uMajorType; // Indicates if item is a map or an array
138 } pArrays[QCBOR_MAX_ARRAY_NESTING1+1], // stored state for the nesting levels
139 *pCurrentNesting; // the current nesting level
140} QCBORTrackNesting;
141
142
143/*
144 PRIVATE DATA STRUCTURE
145
146 Context / data object for encoding some CBOR. Used by all encode functions to
147 form a public "object" that does the job of encdoing.
148
149 Size approximation (varies with CPU/compiler):
150 64-bit machine: 27 + 1 (+ 4 padding) + 136 = 32 + 136 = 168 bytes
151 32-bit machine: 15 + 1 + 132 = 148 bytes
152*/
153struct _QCBOREncodeContext {
154 // PRIVATE DATA STRUCTURE
155 UsefulOutBuf OutBuf; // Pointer to output buffer, its length and
156 // position in it
157 uint8_t uError; // Error state, always from QCBORError enum
158 QCBORTrackNesting nesting; // Keep track of array and map nesting
159};
160
161
162/*
163 PRIVATE DATA STRUCTURE
164
165 Holds the data for array and map nesting for decoding work. This structure
166 and the DecodeNesting_xxx functions form an "object" that does the work
167 for arrays and maps.
168
169 Size approximation (varies with CPU/compiler):
170 64-bit machine: 4 * 16 + 8 = 72
171 32-bit machine: 4 * 16 + 4 = 68
172 */
173typedef struct __QCBORDecodeNesting {
174 // PRIVATE DATA STRUCTURE
175 struct {
176 uint16_t uCount;
177 uint8_t uMajorType;
178 } pMapsAndArrays[QCBOR_MAX_ARRAY_NESTING1+1],
179 *pCurrent;
180} QCBORDecodeNesting;
181
182
183typedef struct {
184 // PRIVATE DATA STRUCTURE
185 void *pAllocateCxt;
186 UsefulBuf (* pfAllocator)(void *pAllocateCxt, void *pOldMem, size_t uNewSize);
187} QCORInternalAllocator;
188
189
190/*
191 PRIVATE DATA STRUCTURE
192
193 The decode context. This data structure plus the public QCBORDecode_xxx
194 functions form an "object" that does CBOR decoding.
195
196 Size approximation (varies with CPU/compiler):
197 64-bit machine: 32 + 1 + 1 + 6 bytes padding + 72 + 16 + 8 + 8 = 144 bytes
198 32-bit machine: 16 + 1 + 1 + 2 bytes padding + 68 + 8 + 8 + 4 = 108 bytes
199 */
200struct _QCBORDecodeContext {
201 // PRIVATE DATA STRUCTURE
202 UsefulInputBuf InBuf;
203
204 uint8_t uDecodeMode;
205 uint8_t bStringAllocateAll;
206
207 QCBORDecodeNesting nesting;
208
209 // If a string allocator is configured for indefinite-length
210 // strings, it is configured here.
211 QCORInternalAllocator StringAllocator;
212
213 // These are special for the internal MemPool allocator.
214 // They are not used otherwise. We tried packing these
215 // in the MemPool itself, but there are issues
216 // with memory alignment.
217 uint32_t uMemPoolSize;
218 uint32_t uMemPoolFreeOffset;
219
220 // This is NULL or points to QCBORTagList.
221 // It is type void for the same reason as above.
222 const void *pCallerConfiguredTagList;
223};
224
225// Used internally in the impementation here
226// Must not conflict with any of the official CBOR types
227#define CBOR_MAJOR_NONE_TYPE_RAW 9
228#define CBOR_MAJOR_NONE_TAG_LABEL_REORDER 10
229#define CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY 11
230#define CBOR_MAJOR_NONE_TYPE_ARRAY_INDEFINITE_LEN 12
231#define CBOR_MAJOR_NONE_TYPE_MAP_INDEFINITE_LEN 13
232
233
234/* ==========================================================================
235 END OF PRIVATE PART OF THIS FILE
236
237 BEGINNING OF PUBLIC PART OF THIS FILE
238 ========================================================================== */
239
240
241
242/* ==========================================================================
243 BEGINNING OF CONSTANTS THAT COME FROM THE CBOR STANDARD, RFC 7049
244
245 It is not necessary to use these directly when encoding or decoding
246 CBOR with this implementation.
247 ========================================================================== */
248
249/* Standard CBOR Major type for positive integers of various lengths */
250#define CBOR_MAJOR_TYPE_POSITIVE_INT 0
251
252/* Standard CBOR Major type for negative integer of various lengths */
253#define CBOR_MAJOR_TYPE_NEGATIVE_INT 1
254
255/* Standard CBOR Major type for an array of arbitrary 8-bit bytes. */
256#define CBOR_MAJOR_TYPE_BYTE_STRING 2
257
258/* Standard CBOR Major type for a UTF-8 string. Note this is true 8-bit UTF8
259 with no encoding and no NULL termination */
260#define CBOR_MAJOR_TYPE_TEXT_STRING 3
261
262/* Standard CBOR Major type for an ordered array of other CBOR data items */
263#define CBOR_MAJOR_TYPE_ARRAY 4
264
265/* Standard CBOR Major type for CBOR MAP. Maps an array of pairs. The
266 first item in the pair is the "label" (key, name or identfier) and the second
267 item is the value. */
268#define CBOR_MAJOR_TYPE_MAP 5
269
270/* Standard CBOR optional tagging. This tags things like dates and URLs */
271#define CBOR_MAJOR_TYPE_OPTIONAL 6
272
273/* Standard CBOR extra simple types like floats and the values true and false */
274#define CBOR_MAJOR_TYPE_SIMPLE 7
275
276
277/*
278 These are special values for the AdditionalInfo bits that are part of
279 the first byte. Mostly they encode the length of the data item.
280 */
281#define LEN_IS_ONE_BYTE 24
282#define LEN_IS_TWO_BYTES 25
283#define LEN_IS_FOUR_BYTES 26
284#define LEN_IS_EIGHT_BYTES 27
285#define ADDINFO_RESERVED1 28
286#define ADDINFO_RESERVED2 29
287#define ADDINFO_RESERVED3 30
288#define LEN_IS_INDEFINITE 31
289
290
291/*
292 24 is a special number for CBOR. Integers and lengths
293 less than it are encoded in the same byte as the major type.
294 */
295#define CBOR_TWENTY_FOUR 24
296
297
298/*
299 Tags that are used with CBOR_MAJOR_TYPE_OPTIONAL. These
300 are types defined in RFC 7049 and some additional ones
301 in the IANA CBOR tags registry.
302 */
303/** See QCBOREncode_AddDateString(). */
304#define CBOR_TAG_DATE_STRING 0
305/** See QCBOREncode_AddDateEpoch(). */
306#define CBOR_TAG_DATE_EPOCH 1
307/** See QCBOREncode_AddPositiveBignum(). */
308#define CBOR_TAG_POS_BIGNUM 2
309/** See QCBOREncode_AddNegativeBignum(). */
310#define CBOR_TAG_NEG_BIGNUM 3
311/** CBOR tag for a two-element array representing a fraction with a
312 mantissa and base-10 scaling factor. See QCBOREncode_AddDecimalFraction()
313 and @ref expAndMantissa.
314 */
315#define CBOR_TAG_DECIMAL_FRACTION 4
316/** CBOR tag for a two-element array representing a fraction with a
317 mantissa and base-2 scaling factor. See QCBOREncode_AddBigFloat()
318 and @ref expAndMantissa. */
319#define CBOR_TAG_BIGFLOAT 5
320/** Tag for COSE format encryption with no recipient
321 identification. See [RFC 8152, COSE]
322 (https://tools.ietf.org/html/rfc8152). No API is provided for this
323 tag. */
324#define CBOR_TAG_COSE_ENCRYPTO 16
325/** Tag for COSE format MAC'd data with no recipient
326 identification. See [RFC 8152, COSE]
327 (https://tools.ietf.org/html/rfc8152). No API is provided for this
328 tag.*/
329#define CBOR_TAG_COSE_MAC0 17
330/** Tag for COSE format single signature signing. No API is provided
331 for this tag. See [RFC 8152, COSE]
332 (https://tools.ietf.org/html/rfc8152). */
333#define CBOR_TAG_COSE_SIGN1 18
334/** A hint that the following byte string should be encoded in
335 Base64URL when converting to JSON or similar text-based
336 representations. Call @c
337 QCBOREncode_AddTag(pCtx,CBOR_TAG_ENC_AS_B64URL) before the call to
338 QCBOREncode_AddBytes(). */
339#define CBOR_TAG_ENC_AS_B64URL 21
340/** A hint that the following byte string should be encoded in Base64
341 when converting to JSON or similar text-based
342 representations. Call @c
343 QCBOREncode_AddTag(pCtx,CBOR_TAG_ENC_AS_B64) before the call to
344 QCBOREncode_AddBytes(). */
345#define CBOR_TAG_ENC_AS_B64 22
346/** A hint that the following byte string should be encoded in base-16
347 format per [RFC 4648] (https://tools.ietf.org/html/rfc4648) when
348 converting to JSON or similar text-based
349 representations. Essentially, Base-16 encoding is the standard
350 case- insensitive hex encoding and may be referred to as
351 "hex". Call @c QCBOREncode_AddTag(pCtx,CBOR_TAG_ENC_AS_B16) before
352 the call to QCBOREncode_AddBytes(). */
353#define CBOR_TAG_ENC_AS_B16 23
354/** Tag to indicate a byte string contains encoded CBOR. No API is
355 provided for this tag. */
356#define CBOR_TAG_CBOR 24
357/** See QCBOREncode_AddURI(). */
358#define CBOR_TAG_URI 32
359/** See QCBOREncode_AddB64URLText(). */
360#define CBOR_TAG_B64URL 33
361/** See QCBOREncode_AddB64Text(). */
362#define CBOR_TAG_B64 34
363/** See QCBOREncode_AddRegex(). */
364#define CBOR_TAG_REGEX 35
365/** See QCBOREncode_AddMIMEData(). */
366#define CBOR_TAG_MIME 36
367/** See QCBOREncode_AddBinaryUUID(). */
368#define CBOR_TAG_BIN_UUID 37
369/** The data is a CBOR Web Token per [RFC 8392]
370 (https://tools.ietf.org/html/rfc8932). No API is provided for this
371 tag. */
372#define CBOR_TAG_CWT 61
373/** Tag for COSE format encryption. See [RFC 8152, COSE]
374 (https://tools.ietf.org/html/rfc8152). No API is provided for this
375 tag. */
376#define CBOR_TAG_ENCRYPT 96
377/** Tag for COSE format MAC. See [RFC 8152, COSE]
378 (https://tools.ietf.org/html/rfc8152). No API is provided for this
379 tag. */
380#define CBOR_TAG_MAC 97
381/** Tag for COSE format signed data. See [RFC 8152, COSE]
382 (https://tools.ietf.org/html/rfc8152). No API is provided for this
383 tag. */
384#define CBOR_TAG_SIGN 98
385/** World geographic coordinates. See ISO 6709, [RFC 5870]
386 (https://tools.ietf.org/html/rfc5870) and WGS-84. No API is
387 provided for this tag. */
388#define CBOR_TAG_GEO_COORD 103
389/** The magic number, self-described CBOR. No API is provided for this
390 tag. */
391#define CBOR_TAG_CBOR_MAGIC 55799
392
393#define CBOR_TAG_NONE UINT64_MAX
394
395
396/*
397 Values for the 5 bits for items of major type 7
398 */
399#define CBOR_SIMPLEV_FALSE 20
400#define CBOR_SIMPLEV_TRUE 21
401#define CBOR_SIMPLEV_NULL 22
402#define CBOR_SIMPLEV_UNDEF 23
403#define CBOR_SIMPLEV_ONEBYTE 24
404#define HALF_PREC_FLOAT 25
405#define SINGLE_PREC_FLOAT 26
406#define DOUBLE_PREC_FLOAT 27
407#define CBOR_SIMPLE_BREAK 31
408#define CBOR_SIMPLEV_RESERVED_START CBOR_SIMPLEV_ONEBYTE
409#define CBOR_SIMPLEV_RESERVED_END CBOR_SIMPLE_BREAK
410
411
412
413/* ===========================================================================
414
415 END OF CONSTANTS THAT COME FROM THE CBOR STANDARD, RFC 7049
416
417 BEGINNING OF PUBLIC INTERFACE FOR QCBOR ENCODER / DECODER
418
419 =========================================================================== */
420
421/**
422
423 @file qcbor.h
424
425 Q C B O R E n c o d e / D e c o d e
426
427 This implements CBOR -- Concise Binary Object Representation as
428 defined in [RFC 7049] (https://tools.ietf.org/html/rfc7049). More
429 info is at http://cbor.io. This is a near-complete implementation of
430 the specification. Limitations are listed further down.
431
432 CBOR is intentionally designed to be translatable to JSON, but not
433 all CBOR can convert to JSON. See RFC 7049 for more info on how to
434 construct CBOR that is the most JSON friendly.
435
436 The memory model for encoding and decoding is that encoded CBOR must
437 be in a contiguous buffer in memory. During encoding the caller must
438 supply an output buffer and if the encoding would go off the end of
439 the buffer an error is returned. During decoding the caller supplies
440 the encoded CBOR in a contiguous buffer and the decoder returns
441 pointers and lengths into that buffer for strings.
442
443 This implementation does not require malloc. All data structures
444 passed in/out of the APIs can fit on the stack.
445
446 Decoding of indefinite-length strings is a special case that requires
447 a "string allocator" to allocate memory into which the segments of
448 the string are coalesced. Without this, decoding will error out if an
449 indefinite-length string is encountered (indefinite-length maps and
450 arrays do not require the string allocator). A simple string
451 allocator called MemPool is built-in and will work if supplied with a
452 block of memory to allocate. The string allocator can optionally use
453 malloc() or some other custom scheme.
454
455 Here are some terms and definitions:
456
457 - "Item", "Data Item": An integer or string or such. The basic "thing" that
458 CBOR is about. An array is an item itself that contains some items.
459
460 - "Array": An ordered sequence of items, the same as JSON.
461
462 - "Map": A collection of label/value pairs. Each pair is a data
463 item. A JSON "object" is the same as a CBOR "map".
464
465 - "Label": The data item in a pair in a map that names or identifies
466 the pair, not the value. This implementation refers to it as a
467 "label". JSON refers to it as the "name". The CBOR RFC refers to it
468 this as a "key". This implementation chooses label instead because
469 key is too easily confused with a cryptographic key. The COSE
470 standard, which uses CBOR, has also chosen to use the term "label"
471 rather than "key" for this same reason.
472
473 - "Key": See "Label" above.
474
475 - "Tag": Optional integer that can be added before each data item
476 usually to indicate it is new or more specific data type. For
477 example, a tag can indicate an integer is a date, or that a map is to
478 be considered a type (analogous to a typedef in C).
479
480 - "Initial Byte": The first byte of an encoded item. Encoding and
481 decoding of this byte is taken care of by the implementation.
482
483 - "Additional Info": In addition to the major type, all data items
484 have some other info. This is usually the length of the data but can
485 be several other things. Encoding and decoding of this is taken care
486 of by the implementation.
487
488 CBOR has two mechanisms for tagging and labeling the data values like
489 integers and strings. For example, an integer that represents
490 someone's birthday in epoch seconds since Jan 1, 1970 could be
491 encoded like this:
492
493 - First it is CBOR_MAJOR_TYPE_POSITIVE_INT (@ref QCBOR_TYPE_INT64),
494 the primitive positive integer.
495
496 - Next it has a "tag" @ref CBOR_TAG_DATE_EPOCH indicating the integer
497 represents a date in the form of the number of seconds since Jan 1,
498 1970.
499
500 - Last it has a string "label" like "BirthDate" indicating the
501 meaning of the data.
502
503 The encoded binary looks like this:
504
505 a1 # Map of 1 item
506 69 # Indicates text string of 9 bytes
507 426972746844617465 # The text "BirthDate"
508 c1 # Tags next integer as epoch date
509 1a # Indicates a 4-byte integer
510 580d4172 # unsigned integer date 1477263730
511
512 Implementors using this API will primarily work with
513 labels. Generally, tags are only needed for making up new data
514 types. This implementation covers most of the data types defined in
515 the RFC using tags. It also, allows for the use of custom tags if
516 necessary.
517
518 This implementation explicitly supports labels that are text strings
519 and integers. Text strings translate nicely into JSON objects and are
520 very readable. Integer labels are much less readable but can be very
521 compact. If they are in the range of 0 to 23, they take up only one
522 byte.
523
524 CBOR allows a label to be any type of data including an array or a
525 map. It is possible to use this API to construct and parse such
526 labels, but it is not explicitly supported.
527
528 A common encoding usage mode is to invoke the encoding twice. First
529 with no output buffer to compute the length of the needed output
530 buffer. Then the correct sized output buffer is allocated. Last the
531 encoder is invoked again, this time with the output buffer.
532
533 The double invocation is not required if the maximum output buffer
534 size can be predicted. This is usually possible for simple CBOR
535 structures. If the double invocation is implemented, it can be in a
536 loop or function as in the example code so that the code doesn't have
537 to actually be written twice, saving code size.
538
539 If a buffer too small to hold the encoded output is given, the error
540 @ref QCBOR_ERR_BUFFER_TOO_SMALL will be returned. Data will never be
541 written off the end of the output buffer no matter which functions
542 here are called or what parameters are passed to them.
543
544 The encoding error handling is simple. The only possible errors are
545 trying to encode structures that are too large or too complex. There
546 are no internal malloc calls so there will be no failures for out of
547 memory. The error state is tracked internally, so there is no need
548 to check for errors when encoding. Only the return code from
549 QCBOREncode_Finish() need be checked as once an error happens, the
550 encoder goes into an error state and calls to it to add more data
551 will do nothing. An error check is not needed after every data item
552 is added.
553
554 Encoding generally proceeds by calling QCBOREncode_Init(), calling
555 lots of @c QCBOREncode_AddXxx() functions and calling
556 QCBOREncode_Finish(). There are many @c QCBOREncode_AddXxx()
557 functions for various data types. The input buffers need only to be
558 valid during the @c QCBOREncode_AddXxx() calls as the data is copied
559 into the output buffer.
560
561 There are three `Add` functions for each data type. The first / main
562 one for the type is for adding the data item to an array. The second
563 one's name ends in `ToMap`, is used for adding data items to maps and
564 takes a string argument that is its label in the map. The third one
565 ends in `ToMapN`, is also used for adding data items to maps, and
566 takes an integer argument that is its label in the map.
567
568 The simplest aggregate type is an array, which is a simple ordered
569 set of items without labels the same as JSON arrays. Call
570 QCBOREncode_OpenArray() to open a new array, then various @c
571 QCBOREncode_AddXxx() functions to put items in the array and then
572 QCBOREncode_CloseArray(). Nesting to the limit @ref
573 QCBOR_MAX_ARRAY_NESTING is allowed. All opens must be matched by
574 closes or an encoding error will be returned.
575
576 The other aggregate type is a map which does use labels. The `Add`
577 functions that end in `ToMap` and `ToMapN` are convenient ways to add
578 labeled data items to a map. You can also call any type of `Add`
579 function once to add a label of any time and then call any type of
580 `Add` again to add its value.
581
582 Note that when you nest arrays or maps in a map, the nested array or
583 map has a label.
584
585 @anchor Tags-Overview
586 Any CBOR data item can be tagged to add semantics, define a new data
587 type or such. Some tags are fully standardized and some are just
588 registered. Others are not registered and used in a proprietary way.
589
590 Encoding and decoding of many of the registered tags is fully
591 implemented by QCBOR. It is also possible to encode and decode tags
592 that are not directly supported. For many use cases the built-in tag
593 support should be adequate.
594
595 For example, the registered epoch date tag is supported in encoding
596 by QCBOREncode_AddDateEpoch() and in decoding by @ref
597 QCBOR_TYPE_DATE_EPOCH and the @c epochDate member of @ref
598 QCBORItem. This is typical of the built-in tag support. There is an
599 API to encode data for it and a @c QCBOR_TYPE_XXX when it is decoded.
600
601 Tags are registered in the [IANA CBOR Tags Registry]
602 (https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml). There
603 are roughly three options to create a new tag. First, a public
604 specification can be created and the new tag registered with IANA.
605 This is the most formal. Second, the new tag can be registered with
606 IANA with just a short description rather than a full specification.
607 These tags must be greater than 256. Third, a tag can be used without
608 any IANA registration, though the registry should be checked to see
609 that the new value doesn't collide with one that is registered. The
610 value of these tags must be 256 or larger.
611
612 The encoding side of tags not built-in is handled by
613 QCBOREncode_AddTag() and is relatively simple. Tag decoding is more
614 complex and mainly handled by QCBORDecode_GetNext(). Decoding of the
615 structure of tagged data not built-in (if there is any) has to be
616 implemented by the caller.
617
618 Summary Limits of this implementation:
619 - The entire encoded CBOR must fit into contiguous memory.
620 - Max size of encoded / decoded CBOR data is @c UINT32_MAX (4GB).
621 - Max array / map nesting level when encoding / decoding is
622 @ref QCBOR_MAX_ARRAY_NESTING (this is typically 15).
623 - Max items in an array or map when encoding / decoding is
624 @ref QCBOR_MAX_ITEMS_IN_ARRAY (typically 65,536).
625 - Does not directly support labels in maps other than text strings & integers.
626 - Does not directly support integer labels greater than @c INT64_MAX.
627 - Epoch dates limited to @c INT64_MAX (+/- 292 billion years).
628 - Exponents for bigfloats and decimal integers are limited to @c INT64_MAX.
629 - Tags on labels are ignored during decoding.
630 - There is no duplicate detection of map labels (but duplicates are passed on).
631 - Works only on 32- and 64-bit CPUs (modifications could make it work
632 on 16-bit CPUs).
633
634 The public interface uses @c size_t for all lengths. Internally the
635 implementation uses 32-bit lengths by design to use less memory and
636 fit structures on the stack. This limits the encoded CBOR it can work
637 with to size @c UINT32_MAX (4GB) which should be enough.
638
639 This implementation assumes two's compliment integer machines. @c
640 <stdint.h> also requires this. It is possible to modify this
641 implementation for another integer representation, but all modern
642 machines seem to be two's compliment.
643
644 */
645
646
647/**
648 The maximum number of items in a single array or map when encoding of
649 decoding.
650*/
651// -1 is because the value UINT16_MAX is used to track indefinite-length arrays
652#define QCBOR_MAX_ITEMS_IN_ARRAY (UINT16_MAX-1)
653
654/**
655 The maximum nesting of arrays and maps when encoding or decoding. The
656 error @ref QCBOR_ERR_ARRAY_NESTING_TOO_DEEP will be returned on
657 encoding of decoding if it is exceeded.
658*/
659#define QCBOR_MAX_ARRAY_NESTING QCBOR_MAX_ARRAY_NESTING1
660
661/**
662 The maximum number of tags that can be in @ref QCBORTagListIn and passed to
663 QCBORDecode_SetCallerConfiguredTagList()
664 */
665#define QCBOR_MAX_CUSTOM_TAGS 16
666
667/*
668 The size of the buffer to be passed to QCBOREncode_EncodeHead(). It is one
669 byte larger than sizeof(uint64_t) + 1, the actual maximum size of the
670 head of a CBOR data item. because QCBOREncode_EncodeHead() needs
671 one extra byte to work.
672 */
673#define QCBOR_HEAD_BUFFER_SIZE (sizeof(uint64_t) + 2)
674
675/**
676 Error codes returned by QCBOR Encoder and Decoder.
677 */
678typedef enum {
679 /** The encode or decode completely correctly. */
680 QCBOR_SUCCESS = 0,
681
682 /** The buffer provided for the encoded output when doing encoding
683 was too small and the encoded output will not fit. Also, when
684 the buffer given to QCBORDecode_SetMemPool() is too small. */
685 QCBOR_ERR_BUFFER_TOO_SMALL = 1,
686
687 /** During encoding or decoding, the array or map nesting was
688 deeper than this implementation can handle. Note that in the
689 interest of code size and memory use, this implementation has a
690 hard limit on array nesting. The limit is defined as the
691 constant @ref QCBOR_MAX_ARRAY_NESTING. */
692 QCBOR_ERR_ARRAY_NESTING_TOO_DEEP = 2,
693
694 /** During decoding or encoding, the array or map had too many
695 items in it. This limit @ref QCBOR_MAX_ITEMS_IN_ARRAY,
696 typically 65,535. */
697 QCBOR_ERR_ARRAY_TOO_LONG = 3,
698
699 /** During encoding, more arrays or maps were closed than
700 opened. This is a coding error on the part of the caller of the
701 encoder. */
702 QCBOR_ERR_TOO_MANY_CLOSES = 4,
703
704 /** During decoding, some CBOR construct was encountered that this
705 decoder doesn't support, primarily this is the reserved
706 additional info values, 28 through 30. During encoding,
707 an attempt to create simple value between 24 and 31. */
708 QCBOR_ERR_UNSUPPORTED = 5,
709
710 /** During decoding, hit the end of the given data to decode. For
711 example, a byte string of 100 bytes was expected, but the end
712 of the input was hit before finding those 100 bytes. Corrupted
713 CBOR input will often result in this error. See also @ref
714 QCBOR_ERR_NO_MORE_ITEMS.
715 */
716 QCBOR_ERR_HIT_END = 6,
717
718 /** During encoding, the length of the encoded CBOR exceeded @c
719 UINT32_MAX. */
720 QCBOR_ERR_BUFFER_TOO_LARGE = 7,
721
722 /** During decoding, an integer smaller than INT64_MIN was received
723 (CBOR can represent integers smaller than INT64_MIN, but C
724 cannot). */
725 QCBOR_ERR_INT_OVERFLOW = 8,
726
727 /** During decoding, the label for a map entry is bad. What causes
728 this error depends on the decoding mode. */
729 QCBOR_ERR_MAP_LABEL_TYPE = 9,
730
731 /** During encoding or decoding, the number of array or map opens
732 was not matched by the number of closes. */
733 QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN = 10,
734
735 /** During decoding, a date greater than +- 292 billion years from
736 Jan 1 1970 encountered during parsing. */
737 QCBOR_ERR_DATE_OVERFLOW = 11,
738
739 /** During decoding, the CBOR is not valid, primarily a simple type
740 is encoded in a prohibited way. */
741 QCBOR_ERR_BAD_TYPE_7 = 12,
742
743 /** Optional tagging that doesn't make sense (an integer is tagged
744 as a date string) or can't be handled. */
745 QCBOR_ERR_BAD_OPT_TAG = 13,
746
747 /** Returned by QCBORDecode_Finish() if all the inputs bytes have
748 not been consumed. */
749 QCBOR_ERR_EXTRA_BYTES = 14,
750
751 /** During encoding, @c QCBOREncode_CloseXxx() called with a
752 different type than is currently open. */
753 QCBOR_ERR_CLOSE_MISMATCH = 15,
754
755 /** Unable to decode an indefinite-length string because no string
756 allocator was configured. See QCBORDecode_SetMemPool() or
757 QCBORDecode_SetUpAllocator(). */
758 QCBOR_ERR_NO_STRING_ALLOCATOR = 16,
759
760 /** One of the chunks in an indefinite-length string is not of the
761 type of the start of the string. */
762 QCBOR_ERR_INDEFINITE_STRING_CHUNK = 17,
763
764 /** Error allocating space for a string, usually for an
765 indefinite-length string. */
766 QCBOR_ERR_STRING_ALLOCATE = 18,
767
768 /** During decoding, a break occurred outside an indefinite-length
769 item. */
770 QCBOR_ERR_BAD_BREAK = 19,
771
772 /** During decoding, too many tags in the caller-configured tag
773 list, or not enough space in @ref QCBORTagListOut. */
774 QCBOR_ERR_TOO_MANY_TAGS = 20,
775
776 /** An integer type is encoded with a bad length (an indefinite length) */
777 QCBOR_ERR_BAD_INT = 21,
778
779 /** All well-formed data items have been consumed and there are no
780 more. If parsing a CBOR stream this indicates the non-error
781 end of the stream. If parsing a CBOR stream / sequence, this
782 probably indicates that some data items expected are not present.
783 See also @ref QCBOR_ERR_HIT_END. */
784 QCBOR_ERR_NO_MORE_ITEMS = 22,
785
786 /** Something is wrong with a decimal fraction or bigfloat such as
787 it not consisting of an array with two integers */
788 QCBOR_ERR_BAD_EXP_AND_MANTISSA = 23,
789
790 /** When decoding, a string's size is greater than size_t. In all but some
791 very strange situations this is because of corrupt input CBOR and
792 should be treated as such. The strange situation is a CPU with a very
793 small size_t (e.g., a 16-bit CPU) and a large string (e.g., > 65KB).
794 */
795 QCBOR_ERR_STRING_TOO_LONG = 24
796
797} QCBORError;
798
799
800/**
801 The decode mode options.
802 */
803typedef enum {
804 /** See QCBORDecode_Init() */
805 QCBOR_DECODE_MODE_NORMAL = 0,
806 /** See QCBORDecode_Init() */
807 QCBOR_DECODE_MODE_MAP_STRINGS_ONLY = 1,
808 /** See QCBORDecode_Init() */
809 QCBOR_DECODE_MODE_MAP_AS_ARRAY = 2
810} QCBORDecodeMode;
811
812
813
814
815
816/* Do not renumber these. Code depends on some of these values. */
817/** The data type is unknown, unset or invalid. */
818#define QCBOR_TYPE_NONE 0
819/** Type for an integer that decoded either between @c INT64_MIN and
820 @c INT32_MIN or @c INT32_MAX and @c INT64_MAX. Data is in member
821 @c val.int64. */
822#define QCBOR_TYPE_INT64 2
823/** Type for an integer that decoded to a more than @c INT64_MAX and
824 @c UINT64_MAX. Data is in member @c val.uint64. */
825#define QCBOR_TYPE_UINT64 3
826/** Type for an array. The number of items in the array is in @c
827 val.uCount. */
828#define QCBOR_TYPE_ARRAY 4
829/** Type for a map; number of items in map is in @c val.uCount. */
830#define QCBOR_TYPE_MAP 5
831/** Type for a buffer full of bytes. Data is in @c val.string. */
832#define QCBOR_TYPE_BYTE_STRING 6
833/** Type for a UTF-8 string. It is not NULL-terminated. Data is in @c
834 val.string. */
835#define QCBOR_TYPE_TEXT_STRING 7
836/** Type for a positive big number. Data is in @c val.bignum, a
837 pointer and a length. */
838#define QCBOR_TYPE_POSBIGNUM 9
839/** Type for a negative big number. Data is in @c val.bignum, a
840 pointer and a length. */
841#define QCBOR_TYPE_NEGBIGNUM 10
842/** Type for [RFC 3339] (https://tools.ietf.org/html/rfc3339) date
843 string, possibly with time zone. Data is in @c val.dateString */
844#define QCBOR_TYPE_DATE_STRING 11
845/** Type for integer seconds since Jan 1970 + floating-point
846 fraction. Data is in @c val.epochDate */
847#define QCBOR_TYPE_DATE_EPOCH 12
848/** A simple type that this CBOR implementation doesn't know about;
849 Type is in @c val.uSimple. */
850#define QCBOR_TYPE_UKNOWN_SIMPLE 13
851
852/** A decimal fraction made of decimal exponent and integer mantissa.
853 See @ref expAndMantissa and QCBOREncode_AddDecimalFraction(). */
854#define QCBOR_TYPE_DECIMAL_FRACTION 14
855
856/** A decimal fraction made of decimal exponent and positive big
857 number mantissa. See @ref expAndMantissa and
858 QCBOREncode_AddDecimalFractionBigNum(). */
859#define QCBOR_TYPE_DECIMAL_FRACTION_POS_BIGNUM 15
860
861/** A decimal fraction made of decimal exponent and negative big
862 number mantissa. See @ref expAndMantissa and
863 QCBOREncode_AddDecimalFractionBigNum(). */
864#define QCBOR_TYPE_DECIMAL_FRACTION_NEG_BIGNUM 16
865
866/** A floating-point number made of base-2 exponent and integer
867 mantissa. See @ref expAndMantissa and
868 QCBOREncode_AddBigFloat(). */
869#define QCBOR_TYPE_BIGFLOAT 17
870
871/** A floating-point number made of base-2 exponent and positive big
872 number mantissa. See @ref expAndMantissa and
873 QCBOREncode_AddBigFloatBigNum(). */
874#define QCBOR_TYPE_BIGFLOAT_POS_BIGNUM 18
875
876/** A floating-point number made of base-2 exponent and negative big
877 number mantissa. See @ref expAndMantissa and
878 QCBOREncode_AddBigFloatBigNum(). */
879#define QCBOR_TYPE_BIGFLOAT_NEG_BIGNUM 19
880
881/** Type for the value false. */
882#define QCBOR_TYPE_FALSE 20
883/** Type for the value true. */
884#define QCBOR_TYPE_TRUE 21
885/** Type for the value null. */
886#define QCBOR_TYPE_NULL 22
887/** Type for the value undef. */
888#define QCBOR_TYPE_UNDEF 23
889/** Type for a floating-point number. Data is in @c val.float. */
890#define QCBOR_TYPE_FLOAT 26
891/** Type for a double floating-point number. Data is in @c val.double. */
892#define QCBOR_TYPE_DOUBLE 27
893/** For @ref QCBOR_DECODE_MODE_MAP_AS_ARRAY decode mode, a map that is
894 being traversed as an array. See QCBORDecode_Init() */
895#define QCBOR_TYPE_MAP_AS_ARRAY 32
896
897#define QCBOR_TYPE_BREAK 31 // Used internally; never returned
898
899#define QCBOR_TYPE_OPTTAG 254 // Used internally; never returned
900
901
902
903/*
904 Approx Size of this:
905 8 + 8 + 1 + 1 + 1 + (1 padding) + (4 padding) = 24 for first part
906 (20 on a 32-bit machine)
907 16 bytes for the val union
908 16 bytes for label union
909 total = 56 bytes (52 bytes on 32-bit machine)
910 */
911
912/**
913 The main data structure that holds the type, value and other info for
914 a decoded item returned by QCBORDecode_GetNext() and
915 QCBORDecode_GetNextWithTags().
916 */
917typedef struct _QCBORItem {
918 /** Tells what element of the @c val union to use. One of @c
919 QCBOR_TYPE_XXXX */
920 uint8_t uDataType;
921 /** How deep the nesting from arrays and maps are. 0 is the top
922 level with no arrays or maps entered. */
923 uint8_t uNestingLevel;
924 /** Tells what element of the label union to use. */
925 uint8_t uLabelType;
926 /** 1 if allocated with string allocator, 0 if not. See
927 QCBORDecode_SetMemPool() or QCBORDecode_SetUpAllocator() */
928 uint8_t uDataAlloc;
929 /** Like @c uDataAlloc, but for label. */
930 uint8_t uLabelAlloc;
931 /** If not equal to @c uNestingLevel, this item closed out at least
932 one map/array */
933 uint8_t uNextNestLevel;
934
935 /** The union holding the item's value. Select union member based
936 on @c uDataType */
937 union {
938 /** The value for @c uDataType @ref QCBOR_TYPE_INT64. */
939 int64_t int64;
940 /** The value for uDataType @ref QCBOR_TYPE_UINT64. */
941 uint64_t uint64;
942 /** The value for @c uDataType @ref QCBOR_TYPE_BYTE_STRING and
943 @ref QCBOR_TYPE_TEXT_STRING. */
944 UsefulBufC string;
945 /** The "value" for @c uDataType @ref QCBOR_TYPE_ARRAY or @ref
946 QCBOR_TYPE_MAP -- the number of items in the array or map.
947 It is @c UINT16_MAX when decoding indefinite-lengths maps
948 and arrays. */
949 uint16_t uCount;
950 /** The value for @c uDataType @ref QCBOR_TYPE_DOUBLE. */
951 double dfnum;
952 /** The value for @c uDataType @ref QCBOR_TYPE_DATE_EPOCH. */
953 struct {
954 int64_t nSeconds;
955 double fSecondsFraction;
956 } epochDate;
957 /** The value for @c uDataType @ref QCBOR_TYPE_DATE_STRING. */
958 UsefulBufC dateString;
959 /** The value for @c uDataType @ref QCBOR_TYPE_POSBIGNUM and
960 @ref QCBOR_TYPE_NEGBIGNUM. */
961 UsefulBufC bigNum;
962 /** The integer value for unknown simple types. */
963 uint8_t uSimple;
964#ifndef QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA
965 /** @anchor expAndMantissa
966
967 The value for bigfloats and decimal fractions. The use of the
968 fields in this structure depend on @c uDataType.
969
970 When @c uDataType is a @c DECIMAL_FRACTION, the exponent is
971 base-10. When it is a @c BIG_FLOAT it is base-2.
972
973 When @c uDataType is a @c POS_BIGNUM or a @c NEG_BIGNUM then the
974 @c bigNum part of @c Mantissa is valid. Otherwise the
975 @c nInt part of @c Mantissa is valid.
976
977 See @ref QCBOR_TYPE_DECIMAL_FRACTION,
978 @ref QCBOR_TYPE_DECIMAL_FRACTION_POS_BIGNUM,
979 @ref QCBOR_TYPE_DECIMAL_FRACTION_NEG_BIGNUM,
980 @ref QCBOR_TYPE_BIGFLOAT, @ref QCBOR_TYPE_BIGFLOAT_POS_BIGNUM,
981 and @ref QCBOR_TYPE_BIGFLOAT_NEG_BIGNUM.
982
983 Also see QCBOREncode_AddDecimalFraction(), QCBOREncode_AddBigFloat(),
984 QCBOREncode_AddDecimalFractionBigNum() and
985 QCBOREncode_AddBigFloatBigNum().
986 */
987 struct {
988 int64_t nExponent;
989 union {
990 int64_t nInt;
991 UsefulBufC bigNum;
992 } Mantissa;
993 } expAndMantissa;
994#endif
995 uint64_t uTagV; // Used internally during decoding
996 } val;
997
998 /** Union holding the different label types selected based on @c
999 uLabelType */
1000 union {
1001 /** The label for @c uLabelType @ref QCBOR_TYPE_BYTE_STRING and
1002 @ref QCBOR_TYPE_TEXT_STRING */
1003 UsefulBufC string;
1004 /** The label for @c uLabelType for @ref QCBOR_TYPE_INT64 */
1005 int64_t int64;
1006 /** The label for @c uLabelType for @ref QCBOR_TYPE_UINT64 */
1007 uint64_t uint64;
1008 } label;
1009
1010 /** Bit indicating which tags (major type 6) on this item. See
1011 QCBORDecode_IsTagged(). */
1012 uint64_t uTagBits;
1013
1014} QCBORItem;
1015
1016
1017
1018/**
1019 @brief The type defining what a string allocator function must do.
1020
1021 @param[in] pAllocateCxt Pointer to context for the particular
1022 allocator implementation What is in the
1023 context is dependent on how a particular
1024 string allocator works. Typically, it
1025 will contain a pointer to the memory pool
1026 and some booking keeping data.
1027 @param[in] pOldMem Points to some memory allocated by the
1028 allocator that is either to be freed or
1029 to be reallocated to be larger. It is
1030 @c NULL for new allocations and when called as
1031 a destructor to clean up the whole
1032 allocation.
1033 @param[in] uNewSize Size of memory to be allocated or new
1034 size of chunk to be reallocated. Zero for
1035 a new allocation or when called as a
1036 destructor.
1037
1038 @return Either the allocated buffer is returned, or @ref
1039 NULLUsefulBufC. @ref NULLUsefulBufC is returned on a failed
1040 allocation and in the two cases where there is nothing to
1041 return.
1042
1043 This is called in one of four modes:
1044
1045 Allocate -- @c uNewSize is the amount to allocate. @c pOldMem is @c
1046 NULL.
1047
1048 Free -- @c uNewSize is 0. @c pOldMem points to the memory to be
1049 freed. When the decoder calls this, it will always be the most
1050 recent block that was either allocated or reallocated.
1051
1052 Reallocate -- @c pOldMem is the block to reallocate. @c uNewSize is
1053 its new size. When the decoder calls this, it will always be the
1054 most recent block that was either allocated or reallocated.
1055
1056 Destruct -- @c pOldMem is @c NULL and @c uNewSize is 0. This is called
1057 when the decoding is complete by QCBORDecode_Finish(). Usually the
1058 strings allocated by a string allocator are in use after the decoding
1059 is completed so this usually will not free those strings. Many string
1060 allocators will not need to do anything in this mode.
1061
1062 The strings allocated by this will have @c uDataAlloc set to true in
1063 the @ref QCBORItem when they are returned. The user of the strings
1064 will have to free them. How they free them, depends on the string
1065 allocator.
1066
1067 If QCBORDecode_SetMemPool() is called, the internal MemPool will be
1068 used. It has its own internal implementation of this function, so
1069 one does not need to be implemented.
1070 */
1071typedef UsefulBuf (* QCBORStringAllocate)(void *pAllocateCxt, void *pOldMem, size_t uNewSize);
1072
1073
1074/**
1075 This only matters if you use the built-in string allocator by setting
1076 it up with QCBORDecode_SetMemPool(). This is the size of the overhead
1077 needed by QCBORDecode_SetMemPool(). The amount of memory available
1078 for decoded strings will be the size of the buffer given to
1079 QCBORDecode_SetMemPool() less this amount.
1080
1081 If you write your own string allocator or use the separately
1082 available malloc based string allocator, this size will not apply.
1083 */
1084#define QCBOR_DECODE_MIN_MEM_POOL_SIZE 8
1085
1086
1087/**
1088 This is used by QCBORDecode_SetCallerConfiguredTagList() to set a
1089 list of tags beyond the built-in ones.
1090
1091 See also QCBORDecode_GetNext() for general description of tag
1092 decoding.
1093 */
1094typedef struct {
1095 /** The number of tags in the @c puTags. The maximum size is @ref
1096 QCBOR_MAX_CUSTOM_TAGS. */
1097 uint8_t uNumTags;
1098 /** An array of tags to add to recognize in addition to the
1099 built-in ones. */
1100 const uint64_t *puTags;
1101} QCBORTagListIn;
1102
1103
1104/**
1105 This is for QCBORDecode_GetNextWithTags() to be able to return the
1106 full list of tags on an item. It is not needed for most CBOR protocol
1107 implementations. Its primary use is for pretty-printing CBOR or
1108 protocol conversion to another format.
1109
1110 On input, @c puTags points to a buffer to be filled in and
1111 uNumAllocated is the number of @c uint64_t values in the buffer.
1112
1113 On output the buffer contains the tags for the item. @c uNumUsed
1114 tells how many there are.
1115 */
1116typedef struct {
1117 uint8_t uNumUsed;
1118 uint8_t uNumAllocated;
1119 uint64_t *puTags;
1120} QCBORTagListOut;
1121
1122
1123/**
1124 QCBOREncodeContext is the data type that holds context for all the
1125 encoding functions. It is less than 200 bytes, so it can go on the
1126 stack. The contents are opaque, and the caller should not access
1127 internal members. A context may be re used serially as long as it is
1128 re initialized.
1129 */
1130typedef struct _QCBOREncodeContext QCBOREncodeContext;
1131
1132
1133/**
1134 Initialize the encoder to prepare to encode some CBOR.
1135
1136 @param[in,out] pCtx The encoder context to initialize.
1137 @param[in] Storage The buffer into which this encoded result
1138 will be placed.
1139
1140 Call this once at the start of an encoding of a CBOR structure. Then
1141 call the various @c QCBOREncode_AddXxx() functions to add the data
1142 items. Then call QCBOREncode_Finish().
1143
1144 The maximum output buffer is @c UINT32_MAX (4GB). This is not a
1145 practical limit in any way and reduces the memory needed by the
1146 implementation. The error @ref QCBOR_ERR_BUFFER_TOO_LARGE will be
1147 returned by QCBOREncode_Finish() if a larger buffer length is passed
1148 in.
1149
1150 If this is called with @c Storage.ptr as @c NULL and @c Storage.len a
1151 large value like @c UINT32_MAX, all the QCBOREncode_AddXxx()
1152 functions and QCBOREncode_Finish() can still be called. No data will
1153 be encoded, but the length of what would be encoded will be
1154 calculated. The length of the encoded structure will be handed back
1155 in the call to QCBOREncode_Finish(). You can then allocate a buffer
1156 of that size and call all the encoding again, this time to fill in
1157 the buffer.
1158
1159 A @ref QCBOREncodeContext can be reused over and over as long as
1160 QCBOREncode_Init() is called.
1161 */
1162void QCBOREncode_Init(QCBOREncodeContext *pCtx, UsefulBuf Storage);
1163
1164
1165/**
1166 @brief Add a signed 64-bit integer to the encoded output.
1167
1168 @param[in] pCtx The encoding context to add the integer to.
1169 @param[in] nNum The integer to add.
1170
1171 The integer will be encoded and added to the CBOR output.
1172
1173 This function figures out the size and the sign and encodes in the
1174 correct minimal CBOR. Specifically, it will select CBOR major type 0
1175 or 1 based on sign and will encode to 1, 2, 4 or 8 bytes depending on
1176 the value of the integer. Values less than 24 effectively encode to
1177 one byte because they are encoded in with the CBOR major type. This
1178 is a neat and efficient characteristic of CBOR that can be taken
1179 advantage of when designing CBOR-based protocols. If integers like
1180 tags can be kept between -23 and 23 they will be encoded in one byte
1181 including the major type.
1182
1183 If you pass a smaller int, say an @c int16_t or a small value, say
1184 100, the encoding will still be CBOR's most compact that can
1185 represent the value. For example, CBOR always encodes the value 0 as
1186 one byte, 0x00. The representation as 0x00 includes identification of
1187 the type as an integer too as the major type for an integer is 0. See
1188 [RFC 7049] (https://tools.ietf.org/html/rfc7049) Appendix A for more
1189 examples of CBOR encoding. This compact encoding is also canonical
1190 CBOR as per section 3.9 in RFC 7049.
1191
1192 There are no functions to add @c int16_t or @c int32_t because they
1193 are not necessary because this always encodes to the smallest number
1194 of bytes based on the value (If this code is running on a 32-bit
1195 machine having a way to add 32-bit integers would reduce code size
1196 some).
1197
1198 If the encoding context is in an error state, this will do
1199 nothing. If an error occurs when adding this integer, the internal
1200 error flag will be set, and the error will be returned when
1201 QCBOREncode_Finish() is called.
1202
1203 See also QCBOREncode_AddUInt64().
1204 */
1205void QCBOREncode_AddInt64(QCBOREncodeContext *pCtx, int64_t nNum);
1206
1207static void QCBOREncode_AddInt64ToMap(QCBOREncodeContext *pCtx, const char *szLabel, int64_t uNum);
1208
1209static void QCBOREncode_AddInt64ToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, int64_t uNum);
1210
1211
1212/**
1213 @brief Add an unsigned 64-bit integer to the encoded output.
1214
1215 @param[in] pCtx The encoding context to add the integer to.
1216 @param[in] uNum The integer to add.
1217
1218 The integer will be encoded and added to the CBOR output.
1219
1220 The only reason so use this function is for integers larger than @c
1221 INT64_MAX and smaller than @c UINT64_MAX. Otherwise
1222 QCBOREncode_AddInt64() will work fine.
1223
1224 Error handling is the same as for QCBOREncode_AddInt64().
1225 */
1226void QCBOREncode_AddUInt64(QCBOREncodeContext *pCtx, uint64_t uNum);
1227
1228static void QCBOREncode_AddUInt64ToMap(QCBOREncodeContext *pCtx, const char *szLabel, uint64_t uNum);
1229
1230static void QCBOREncode_AddUInt64ToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, uint64_t uNum);
1231
1232
1233/**
1234 @brief Add a UTF-8 text string to the encoded output.
1235
1236 @param[in] pCtx The encoding context to add the text to.
1237 @param[in] Text Pointer and length of text to add.
1238
1239 The text passed in must be unencoded UTF-8 according to [RFC 3629]
1240 (https://tools.ietf.org/html/rfc3629). There is no NULL
1241 termination. The text is added as CBOR major type 3.
1242
1243 If called with @c nBytesLen equal to 0, an empty string will be
1244 added. When @c nBytesLen is 0, @c pBytes may be @c NULL.
1245
1246 Note that the restriction of the buffer length to a @c uint32_t is
1247 entirely intentional as this encoder is not capable of encoding
1248 lengths greater. This limit to 4GB for a text string should not be a
1249 problem.
1250
1251 Error handling is the same as QCBOREncode_AddInt64().
1252 */
1253static void QCBOREncode_AddText(QCBOREncodeContext *pCtx, UsefulBufC Text);
1254
1255static void QCBOREncode_AddTextToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Text);
1256
1257static void QCBOREncode_AddTextToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Text);
1258
1259
1260/**
1261 @brief Add a UTF-8 text string to the encoded output.
1262
1263 @param[in] pCtx The encoding context to add the text to.
1264 @param[in] szString Null-terminated text to add.
1265
1266 This works the same as QCBOREncode_AddText().
1267 */
1268static void QCBOREncode_AddSZString(QCBOREncodeContext *pCtx, const char *szString);
1269
1270static void QCBOREncode_AddSZStringToMap(QCBOREncodeContext *pCtx, const char *szLabel, const char *szString);
1271
1272static void QCBOREncode_AddSZStringToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, const char *szString);
1273
1274
1275/**
1276 @brief Add a floating-point number to the encoded output.
1277
1278 @param[in] pCtx The encoding context to add the double to.
1279 @param[in] dNum The double-precision number to add.
1280
1281 This outputs a floating-point number with CBOR major type 7.
1282
1283 This will selectively encode the double-precision floating-point
1284 number as either double-precision, single-precision or
1285 half-precision. It will always encode infinity, NaN and 0 has half
1286 precision. If no precision will be lost in the conversion to
1287 half-precision, then it will be converted and encoded. If not and no
1288 precision will be lost in conversion to single-precision, then it
1289 will be converted and encoded. If not, then no conversion is
1290 performed, and it encoded as a double.
1291
1292 Half-precision floating-point numbers take up 2 bytes, half that of
1293 single-precision, one quarter of double-precision
1294
1295 This automatically reduces the size of encoded messages a lot, maybe
1296 even by four if most of values are 0, infinity or NaN.
1297
1298 On decode, these will always be returned as a double.
1299
1300 Error handling is the same as QCBOREncode_AddInt64().
1301 */
1302void QCBOREncode_AddDouble(QCBOREncodeContext *pCtx, double dNum);
1303
1304static void QCBOREncode_AddDoubleToMap(QCBOREncodeContext *pCtx, const char *szLabel, double dNum);
1305
1306static void QCBOREncode_AddDoubleToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, double dNum);
1307
1308
1309/**
1310 @brief Add an optional tag.
1311
1312 @param[in] pCtx The encoding context to add the tag to.
1313 @param[in] uTag The tag to add
1314
1315 This outputs a CBOR major type 6 item that tags the next data item
1316 that is output usually to indicate it is some new data type.
1317
1318 For many of the common standard tags, a function to encode data using
1319 it is provided and this is not needed. For example,
1320 QCBOREncode_AddDateEpoch() already exists to output integers
1321 representing dates with the right tag.
1322
1323 The tag is applied to the next data item added to the encoded
1324 output. That data item that is to be tagged can be of any major CBOR
1325 type. Any number of tags can be added to a data item by calling this
1326 multiple times before the data item is added.
1327
1328 See @ref Tags-Overview for discussion of creating new non-standard
1329 tags. See QCBORDecode_GetNext() for discussion of decoding custom
1330 tags.
1331*/
1332void QCBOREncode_AddTag(QCBOREncodeContext *pCtx,uint64_t uTag);
1333
1334
1335/**
1336 @brief Add an epoch-based date.
1337
1338 @param[in] pCtx The encoding context to add the date to.
1339 @param[in] date Number of seconds since 1970-01-01T00:00Z in UTC time.
1340
1341 As per RFC 7049 this is similar to UNIX/Linux/POSIX dates. This is
1342 the most compact way to specify a date and time in CBOR. Note that
1343 this is always UTC and does not include the time zone. Use
1344 QCBOREncode_AddDateString() if you want to include the time zone.
1345
1346 The integer encoding rules apply here so the date will be encoded in
1347 a minimal number of bytes. Until about the year 2106 these dates will
1348 encode in 6 bytes -- one byte for the tag, one byte for the type and
1349 4 bytes for the integer. After that it will encode to 10 bytes.
1350
1351 Negative values are supported for dates before 1970.
1352
1353 If you care about leap-seconds and that level of accuracy, make sure
1354 the system you are running this code on does it correctly. This code
1355 just takes the value passed in.
1356
1357 This implementation cannot encode fractional seconds using float or
1358 double even though that is allowed by CBOR, but you can encode them
1359 if you want to by calling QCBOREncode_AddDouble() and
1360 QCBOREncode_AddTag().
1361
1362 Error handling is the same as QCBOREncode_AddInt64().
1363 */
1364static void QCBOREncode_AddDateEpoch(QCBOREncodeContext *pCtx, int64_t date);
1365
1366static void QCBOREncode_AddDateEpochToMap(QCBOREncodeContext *pCtx, const char *szLabel, int64_t date);
1367
1368static void QCBOREncode_AddDateEpochToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, int64_t date);
1369
1370
1371/**
1372 @brief Add a byte string to the encoded output.
1373
1374 @param[in] pCtx The encoding context to add the bytes to.
1375 @param[in] Bytes Pointer and length of the input data.
1376
1377 Simply adds the bytes to the encoded output as CBOR major type 2.
1378
1379 If called with @c Bytes.len equal to 0, an empty string will be
1380 added. When @c Bytes.len is 0, @c Bytes.ptr may be @c NULL.
1381
1382 Error handling is the same as QCBOREncode_AddInt64().
1383 */
1384static void QCBOREncode_AddBytes(QCBOREncodeContext *pCtx, UsefulBufC Bytes);
1385
1386static void QCBOREncode_AddBytesToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes);
1387
1388static void QCBOREncode_AddBytesToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes);
1389
1390
1391
1392/**
1393 @brief Add a binary UUID to the encoded output.
1394
1395 @param[in] pCtx The encoding context to add the UUID to.
1396 @param[in] Bytes Pointer and length of the binary UUID.
1397
1398 A binary UUID as defined in [RFC 4122]
1399 (https://tools.ietf.org/html/rfc4122) is added to the output.
1400
1401 It is output as CBOR major type 2, a binary string, with tag @ref
1402 CBOR_TAG_BIN_UUID indicating the binary string is a UUID.
1403 */
1404static void QCBOREncode_AddBinaryUUID(QCBOREncodeContext *pCtx, UsefulBufC Bytes);
1405
1406static void QCBOREncode_AddBinaryUUIDToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes);
1407
1408static void QCBOREncode_AddBinaryUUIDToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes);
1409
1410
1411/**
1412 @brief Add a positive big number to the encoded output.
1413
1414 @param[in] pCtx The encoding context to add the big number to.
1415 @param[in] Bytes Pointer and length of the big number.
1416
1417 Big numbers are integers larger than 64-bits. Their format is
1418 described in [RFC 7049] (https://tools.ietf.org/html/rfc7049).
1419
1420 It is output as CBOR major type 2, a binary string, with tag @ref
1421 CBOR_TAG_POS_BIGNUM indicating the binary string is a positive big
1422 number.
1423
1424 Often big numbers are used to represent cryptographic keys, however,
1425 COSE which defines representations for keys chose not to use this
1426 particular type.
1427 */
1428static void QCBOREncode_AddPositiveBignum(QCBOREncodeContext *pCtx, UsefulBufC Bytes);
1429
1430static void QCBOREncode_AddPositiveBignumToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes);
1431
1432static void QCBOREncode_AddPositiveBignumToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes);
1433
1434
1435/**
1436 @brief Add a negative big number to the encoded output.
1437
1438 @param[in] pCtx The encoding context to add the big number to.
1439 @param[in] Bytes Pointer and length of the big number.
1440
1441 Big numbers are integers larger than 64-bits. Their format is
1442 described in [RFC 7049] (https://tools.ietf.org/html/rfc7049).
1443
1444 It is output as CBOR major type 2, a binary string, with tag @ref
1445 CBOR_TAG_NEG_BIGNUM indicating the binary string is a negative big
1446 number.
1447
1448 Often big numbers are used to represent cryptographic keys, however,
1449 COSE which defines representations for keys chose not to use this
1450 particular type.
1451 */
1452static void QCBOREncode_AddNegativeBignum(QCBOREncodeContext *pCtx, UsefulBufC Bytes);
1453
1454static void QCBOREncode_AddNegativeBignumToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes);
1455
1456static void QCBOREncode_AddNegativeBignumToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes);
1457
1458
1459#ifndef QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA
1460/**
1461 @brief Add a decimal fraction to the encoded output.
1462
1463 @param[in] pCtx The encoding context to add the decimal fraction to.
1464 @param[in] nMantissa The mantissa.
1465 @param[in] nBase10Exponent The exponent.
1466
1467 The value is nMantissa * 10 ^ nBase10Exponent.
1468
1469 A decimal fraction is good for exact representation of some values
1470 that can't be represented exactly with standard C (IEEE 754)
1471 floating-point numbers. Much larger and much smaller numbers can
1472 also be represented than floating-point because of the larger number
1473 of bits in the exponent.
1474
1475 The decimal fraction is conveyed as two integers, a mantissa and a
1476 base-10 scaling factor.
1477
1478 For example, 273.15 is represented by the two integers 27315 and -2.
1479
1480 The exponent and mantissa have the range from @c INT64_MIN to
1481 @c INT64_MAX for both encoding and decoding (CBOR allows @c -UINT64_MAX
1482 to @c UINT64_MAX, but this implementation doesn't support this range to
1483 reduce code size and interface complexity a little).
1484
1485 CBOR Preferred encoding of the integers is used, thus they will be encoded
1486 in the smallest number of bytes possible.
1487
1488 See also QCBOREncode_AddDecimalFractionBigNum() for a decimal
1489 fraction with arbitrarily large precision and QCBOREncode_AddBigFloat().
1490
1491 There is no representation of positive or negative infinity or NaN
1492 (Not a Number). Use QCBOREncode_AddDouble() to encode them.
1493
1494 See @ref expAndMantissa for decoded representation.
1495 */
1496static void QCBOREncode_AddDecimalFraction(QCBOREncodeContext *pCtx,
1497 int64_t nMantissa,
1498 int64_t nBase10Exponent);
1499
1500static void QCBOREncode_AddDecimalFractionToMap(QCBOREncodeContext *pCtx,
1501 const char *szLabel,
1502 int64_t nMantissa,
1503 int64_t nBase10Exponent);
1504
1505static void QCBOREncode_AddDecimalFractionToMapN(QCBOREncodeContext *pCtx,
1506 int64_t nLabel,
1507 int64_t nMantissa,
1508 int64_t nBase10Exponent);
1509
1510/**
1511 @brief Add a decimal fraction with a big number mantissa to the encoded output.
1512
1513 @param[in] pCtx The encoding context to add the decimal fraction to.
1514 @param[in] Mantissa The mantissa.
1515 @param[in] bIsNegative false if mantissa is positive, true if negative.
1516 @param[in] nBase10Exponent The exponent.
1517
1518 This is the same as QCBOREncode_AddDecimalFraction() except the
1519 mantissa is a big number (See QCBOREncode_AddPositiveBignum())
1520 allowing for arbitrarily large precision.
1521
1522 See @ref expAndMantissa for decoded representation.
1523 */
1524static void QCBOREncode_AddDecimalFractionBigNum(QCBOREncodeContext *pCtx,
1525 UsefulBufC Mantissa,
1526 bool bIsNegative,
1527 int64_t nBase10Exponent);
1528
1529static void QCBOREncode_AddDecimalFractionBigNumToMap(QCBOREncodeContext *pCtx,
1530 const char *szLabel,
1531 UsefulBufC Mantissa,
1532 bool bIsNegative,
1533 int64_t nBase10Exponent);
1534
1535static void QCBOREncode_AddDecimalFractionBigNumToMapN(QCBOREncodeContext *pCtx,
1536 int64_t nLabel,
1537 UsefulBufC Mantissa,
1538 bool bIsNegative,
1539 int64_t nBase10Exponent);
1540
1541/**
1542 @brief Add a big floating-point number to the encoded output.
1543
1544 @param[in] pCtx The encoding context to add the bigfloat to.
1545 @param[in] nMantissa The mantissa.
1546 @param[in] nBase2Exponent The exponent.
1547
1548 The value is nMantissa * 2 ^ nBase2Exponent.
1549
1550 "Bigfloats", as CBOR terms them, are similar to IEEE floating-point
1551 numbers in having a mantissa and base-2 exponent, but they are not
1552 supported by hardware or encoded the same. They explicitly use two
1553 CBOR-encoded integers to convey the mantissa and exponent, each of which
1554 can be 8, 16, 32 or 64 bits. With both the mantissa and exponent
1555 64 bits they can express more precision and a larger range than an
1556 IEEE double floating-point number. See
1557 QCBOREncode_AddBigFloatBigNum() for even more precision.
1558
1559 For example, 1.5 would be represented by a mantissa of 3 and an
1560 exponent of -1.
1561
1562 The exponent and mantissa have the range from @c INT64_MIN to
1563 @c INT64_MAX for both encoding and decoding (CBOR allows @c -UINT64_MAX
1564 to @c UINT64_MAX, but this implementation doesn't support this range to
1565 reduce code size and interface complexity a little).
1566
1567 CBOR Preferred encoding of the integers is used, thus they will be encoded
1568 in the smallest number of bytes possible.
1569
1570 This can also be used to represent floating-point numbers in
1571 environments that don't support IEEE 754.
1572
1573 See @ref expAndMantissa for decoded representation.
1574 */
1575static void QCBOREncode_AddBigFloat(QCBOREncodeContext *pCtx,
1576 int64_t nMantissa,
1577 int64_t nBase2Exponent);
1578
1579static void QCBOREncode_AddBigFloatToMap(QCBOREncodeContext *pCtx,
1580 const char *szLabel,
1581 int64_t nMantissa,
1582 int64_t nBase2Exponent);
1583
1584static void QCBOREncode_AddBigFloatToMapN(QCBOREncodeContext *pCtx,
1585 int64_t nLabel,
1586 int64_t nMantissa,
1587 int64_t nBase2Exponent);
1588
1589
1590/**
1591 @brief Add a big floating-point number with a big number mantissa to
1592 the encoded output.
1593
1594 @param[in] pCtx The encoding context to add the bigfloat to.
1595 @param[in] Mantissa The mantissa.
1596 @param[in] bIsNegative false if mantissa is positive, true if negative.
1597 @param[in] nBase2Exponent The exponent.
1598
1599 This is the same as QCBOREncode_AddBigFloat() except the mantissa is
1600 a big number (See QCBOREncode_AddPositiveBignum()) allowing for
1601 arbitrary precision.
1602
1603 See @ref expAndMantissa for decoded representation.
1604 */
1605static void QCBOREncode_AddBigFloatBigNum(QCBOREncodeContext *pCtx,
1606 UsefulBufC Mantissa,
1607 bool bIsNegative,
1608 int64_t nBase2Exponent);
1609
1610static void QCBOREncode_AddBigFloatBigNumToMap(QCBOREncodeContext *pCtx,
1611 const char *szLabel,
1612 UsefulBufC Mantissa,
1613 bool bIsNegative,
1614 int64_t nBase2Exponent);
1615
1616static void QCBOREncode_AddBigFloatBigNumToMapN(QCBOREncodeContext *pCtx,
1617 int64_t nLabel,
1618 UsefulBufC Mantissa,
1619 bool bIsNegative,
1620 int64_t nBase2Exponent);
1621#endif /* QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA */
1622
1623
1624/**
1625 @brief Add a text URI to the encoded output.
1626
1627 @param[in] pCtx The encoding context to add the URI to.
1628 @param[in] URI Pointer and length of the URI.
1629
1630 The format of URI must be per [RFC 3986]
1631 (https://tools.ietf.org/html/rfc3986).
1632
1633 It is output as CBOR major type 3, a text string, with tag @ref
1634 CBOR_TAG_URI indicating the text string is a URI.
1635
1636 A URI in a NULL-terminated string, @c szURI, can be easily added with
1637 this code:
1638
1639 QCBOREncode_AddURI(pCtx, UsefulBuf_FromSZ(szURI));
1640 */
1641static void QCBOREncode_AddURI(QCBOREncodeContext *pCtx, UsefulBufC URI);
1642
1643static void QCBOREncode_AddURIToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC URI);
1644
1645static void QCBOREncode_AddURIToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC URI);
1646
1647
1648/**
1649 @brief Add Base64-encoded text to encoded output.
1650
1651 @param[in] pCtx The encoding context to add the base-64 text to.
1652 @param[in] B64Text Pointer and length of the base-64 encoded text.
1653
1654 The text content is Base64 encoded data per [RFC 4648]
1655 (https://tools.ietf.org/html/rfc4648).
1656
1657 It is output as CBOR major type 3, a text string, with tag @ref
1658 CBOR_TAG_B64 indicating the text string is Base64 encoded.
1659 */
1660static void QCBOREncode_AddB64Text(QCBOREncodeContext *pCtx, UsefulBufC B64Text);
1661
1662static void QCBOREncode_AddB64TextToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC B64Text);
1663
1664static void QCBOREncode_AddB64TextToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC B64Text);
1665
1666
1667/**
1668 @brief Add base64url encoded data to encoded output.
1669
1670 @param[in] pCtx The encoding context to add the base64url to.
1671 @param[in] B64Text Pointer and length of the base64url encoded text.
1672
1673 The text content is base64URL encoded text as per [RFC 4648]
1674 (https://tools.ietf.org/html/rfc4648).
1675
1676 It is output as CBOR major type 3, a text string, with tag @ref
1677 CBOR_TAG_B64URL indicating the text string is a Base64url encoded.
1678 */
1679static void QCBOREncode_AddB64URLText(QCBOREncodeContext *pCtx, UsefulBufC B64Text);
1680
1681static void QCBOREncode_AddB64URLTextToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC B64Text);
1682
1683static void QCBOREncode_AddB64URLTextToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC B64Text);
1684
1685
1686/**
1687 @brief Add Perl Compatible Regular Expression.
1688
1689 @param[in] pCtx The encoding context to add the regular expression to.
1690 @param[in] Regex Pointer and length of the regular expression.
1691
1692 The text content is Perl Compatible Regular
1693 Expressions (PCRE) / JavaScript syntax [ECMA262].
1694
1695 It is output as CBOR major type 3, a text string, with tag @ref
1696 CBOR_TAG_REGEX indicating the text string is a regular expression.
1697 */
1698static void QCBOREncode_AddRegex(QCBOREncodeContext *pCtx, UsefulBufC Regex);
1699
1700static void QCBOREncode_AddRegexToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Regex);
1701
1702static void QCBOREncode_AddRegexToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Regex);
1703
1704
1705/**
1706 @brief MIME encoded text to the encoded output.
1707
1708 @param[in] pCtx The encoding context to add the MIME data to.
1709 @param[in] MIMEData Pointer and length of the regular expression.
1710
1711 The text content is in MIME format per [RFC 2045]
1712 (https://tools.ietf.org/html/rfc2045) including the headers. Note
1713 that this only supports text-format MIME. Binary MIME is not
1714 supported.
1715
1716 It is output as CBOR major type 3, a text string, with tag
1717 @ref CBOR_TAG_MIME indicating the text string is MIME data.
1718 */
1719static void QCBOREncode_AddMIMEData(QCBOREncodeContext *pCtx, UsefulBufC MIMEData);
1720
1721static void QCBOREncode_AddMIMEDataToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC MIMEData);
1722
1723static void QCBOREncode_AddMIMEDataToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC MIMEData);
1724
1725
1726/**
1727 @brief Add an RFC 3339 date string
1728
1729 @param[in] pCtx The encoding context to add the date to.
1730 @param[in] szDate Null-terminated string with date to add.
1731
1732 The string szDate should be in the form of [RFC 3339]
1733 (https://tools.ietf.org/html/rfc3339) as defined by section 3.3 in
1734 [RFC 4287] (https://tools.ietf.org/html/rfc4287). This is as
1735 described in section 2.4.1 in [RFC 7049]
1736 (https://tools.ietf.org/html/rfc7049).
1737
1738 Note that this function doesn't validate the format of the date string
1739 at all. If you add an incorrect format date string, the generated
1740 CBOR will be incorrect and the receiver may not be able to handle it.
1741
1742 Error handling is the same as QCBOREncode_AddInt64().
1743 */
1744static void QCBOREncode_AddDateString(QCBOREncodeContext *pCtx, const char *szDate);
1745
1746static void QCBOREncode_AddDateStringToMap(QCBOREncodeContext *pCtx, const char *szLabel, const char *szDate);
1747
1748static void QCBOREncode_AddDateStringToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, const char *szDate);
1749
1750
1751/**
1752 @brief Add a standard Boolean.
1753
1754 @param[in] pCtx The encoding context to add the Boolean to.
1755 @param[in] b true or false from @c <stdbool.h>.
1756
1757 Adds a Boolean value as CBOR major type 7.
1758
1759 Error handling is the same as QCBOREncode_AddInt64().
1760 */
1761static void QCBOREncode_AddBool(QCBOREncodeContext *pCtx, bool b);
1762
1763static void QCBOREncode_AddBoolToMap(QCBOREncodeContext *pCtx, const char *szLabel, bool b);
1764
1765static void QCBOREncode_AddBoolToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, bool b);
1766
1767
1768
1769/**
1770 @brief Add a NULL to the encoded output.
1771
1772 @param[in] pCtx The encoding context to add the NULL to.
1773
1774 Adds the NULL value as CBOR major type 7.
1775
1776 This NULL doesn't have any special meaning in CBOR such as a
1777 terminating value for a string or an empty value.
1778
1779 Error handling is the same as QCBOREncode_AddInt64().
1780 */
1781static void QCBOREncode_AddNULL(QCBOREncodeContext *pCtx);
1782
1783static void QCBOREncode_AddNULLToMap(QCBOREncodeContext *pCtx, const char *szLabel);
1784
1785static void QCBOREncode_AddNULLToMapN(QCBOREncodeContext *pCtx, int64_t nLabel);
1786
1787
1788/**
1789 @brief Add an "undef" to the encoded output.
1790
1791 @param[in] pCtx The encoding context to add the "undef" to.
1792
1793 Adds the undef value as CBOR major type 7.
1794
1795 Note that this value will not translate to JSON.
1796
1797 This Undef doesn't have any special meaning in CBOR such as a
1798 terminating value for a string or an empty value.
1799
1800 Error handling is the same as QCBOREncode_AddInt64().
1801 */
1802static void QCBOREncode_AddUndef(QCBOREncodeContext *pCtx);
1803
1804static void QCBOREncode_AddUndefToMap(QCBOREncodeContext *pCtx, const char *szLabel);
1805
1806static void QCBOREncode_AddUndefToMapN(QCBOREncodeContext *pCtx, int64_t nLabel);
1807
1808
1809/**
1810 @brief Indicates that the next items added are in an array.
1811
1812 @param[in] pCtx The encoding context to open the array in.
1813
1814 Arrays are the basic CBOR aggregate or structure type. Call this
1815 function to start or open an array. Then call the various @c
1816 QCBOREncode_AddXxx() functions to add the items that go into the
1817 array. Then call QCBOREncode_CloseArray() when all items have been
1818 added. The data items in the array can be of any type and can be of
1819 mixed types.
1820
1821 Nesting of arrays and maps is allowed and supported just by calling
1822 QCBOREncode_OpenArray() again before calling
1823 QCBOREncode_CloseArray(). While CBOR has no limit on nesting, this
1824 implementation does in order to keep it smaller and simpler. The
1825 limit is @ref QCBOR_MAX_ARRAY_NESTING. This is the max number of
1826 times this can be called without calling
1827 QCBOREncode_CloseArray(). QCBOREncode_Finish() will return @ref
1828 QCBOR_ERR_ARRAY_NESTING_TOO_DEEP when it is called as this function
1829 just sets an error state and returns no value when this occurs.
1830
1831 If you try to add more than @ref QCBOR_MAX_ITEMS_IN_ARRAY items to a
1832 single array or map, @ref QCBOR_ERR_ARRAY_TOO_LONG will be returned
1833 when QCBOREncode_Finish() is called.
1834
1835 An array itself must have a label if it is being added to a map.
1836 Note that array elements do not have labels (but map elements do).
1837
1838 An array itself may be tagged by calling QCBOREncode_AddTag() before this call.
1839 */
1840static void QCBOREncode_OpenArray(QCBOREncodeContext *pCtx);
1841
1842static void QCBOREncode_OpenArrayInMap(QCBOREncodeContext *pCtx, const char *szLabel);
1843
1844static void QCBOREncode_OpenArrayInMapN(QCBOREncodeContext *pCtx, int64_t nLabel);
1845
1846
1847/**
1848 @brief Close an open array.
1849
1850 @param[in] pCtx The encoding context to close the array in.
1851
1852 The closes an array opened by QCBOREncode_OpenArray(). It reduces
1853 nesting level by one. All arrays (and maps) must be closed before
1854 calling QCBOREncode_Finish().
1855
1856 When an error occurs as a result of this call, the encoder records
1857 the error and enters the error state. The error will be returned when
1858 QCBOREncode_Finish() is called.
1859
1860 If this has been called more times than QCBOREncode_OpenArray(), then
1861 @ref QCBOR_ERR_TOO_MANY_CLOSES will be returned when QCBOREncode_Finish()
1862 is called.
1863
1864 If this is called and it is not an array that is currently open, @ref
1865 QCBOR_ERR_CLOSE_MISMATCH will be returned when QCBOREncode_Finish()
1866 is called.
1867 */
1868static void QCBOREncode_CloseArray(QCBOREncodeContext *pCtx);
1869
1870
1871/**
1872 @brief Indicates that the next items added are in a map.
1873
1874 @param[in] pCtx The encoding context to open the map in.
1875
1876 See QCBOREncode_OpenArray() for more information, particularly error
1877 handling.
1878
1879 CBOR maps are an aggregate type where each item in the map consists
1880 of a label and a value. They are similar to JSON objects.
1881
1882 The value can be any CBOR type including another map.
1883
1884 The label can also be any CBOR type, but in practice they are
1885 typically, integers as this gives the most compact output. They might
1886 also be text strings which gives readability and translation to JSON.
1887
1888 Every @c QCBOREncode_AddXxx() call has one version that ends with @c
1889 InMap for adding items to maps with string labels and one that ends
1890 with @c InMapN that is for adding with integer labels.
1891
1892 RFC 7049 uses the term "key" instead of "label".
1893
1894 If you wish to use map labels that are neither integer labels nor
1895 text strings, then just call the QCBOREncode_AddXxx() function
1896 explicitly to add the label. Then call it again to add the value.
1897
1898 See the [RFC 7049] (https://tools.ietf.org/html/rfc7049) for a lot
1899 more information on creating maps.
1900 */
1901static void QCBOREncode_OpenMap(QCBOREncodeContext *pCtx);
1902
1903static void QCBOREncode_OpenMapInMap(QCBOREncodeContext *pCtx, const char *szLabel);
1904
1905static void QCBOREncode_OpenMapInMapN(QCBOREncodeContext *pCtx, int64_t nLabel);
1906
1907
1908
1909/**
1910 @brief Close an open map.
1911
1912 @param[in] pCtx The encoding context to close the map in .
1913
1914 This closes a map opened by QCBOREncode_OpenMap(). It reduces nesting
1915 level by one.
1916
1917 When an error occurs as a result of this call, the encoder records
1918 the error and enters the error state. The error will be returned when
1919 QCBOREncode_Finish() is called.
1920
1921 If this has been called more times than QCBOREncode_OpenMap(),
1922 then @ref QCBOR_ERR_TOO_MANY_CLOSES will be returned when
1923 QCBOREncode_Finish() is called.
1924
1925 If this is called and it is not a map that is currently open, @ref
1926 QCBOR_ERR_CLOSE_MISMATCH will be returned when QCBOREncode_Finish()
1927 is called.
1928 */
1929static void QCBOREncode_CloseMap(QCBOREncodeContext *pCtx);
1930
1931
1932/**
1933 @brief Indicate start of encoded CBOR to be wrapped in a bstr.
1934
1935 @param[in] pCtx The encoding context to open the bstr-wrapped CBOR in.
1936
1937 All added encoded items between this call and a call to
1938 QCBOREncode_CloseBstrWrap2() will be wrapped in a bstr. They will
1939 appear in the final output as a byte string. That byte string will
1940 contain encoded CBOR. This increases nesting level by one.
1941
1942 The typical use case is for encoded CBOR that is to be
1943 cryptographically hashed, as part of a [RFC 8152, COSE]
1944 (https://tools.ietf.org/html/rfc8152) implementation.
1945
1946 Using QCBOREncode_BstrWrap() and QCBOREncode_CloseBstrWrap2() avoids
1947 having to encode the items first in one buffer (e.g., the COSE
1948 payload) and then add that buffer as a bstr to another encoding
1949 (e.g. the COSE to-be-signed bytes, the @c Sig_structure) potentially
1950 halving the memory needed.
1951
1952 RFC 7049 states the purpose of this wrapping is to prevent code
1953 relaying the signed data but not verifying it from tampering with the
1954 signed data thus making the signature unverifiable. It is also quite
1955 beneficial for the signature verification code. Standard CBOR
1956 decoders usually do not give access to partially decoded CBOR as
1957 would be needed to check the signature of some CBOR. With this
1958 wrapping, standard CBOR decoders can be used to get to all the data
1959 needed for a signature verification.
1960 */
1961static void QCBOREncode_BstrWrap(QCBOREncodeContext *pCtx);
1962
1963static void QCBOREncode_BstrWrapInMap(QCBOREncodeContext *pCtx, const char *szLabel);
1964
1965static void QCBOREncode_BstrWrapInMapN(QCBOREncodeContext *pCtx, int64_t nLabel);
1966
1967
1968/**
1969 @brief Close a wrapping bstr.
1970
1971 @param[in] pCtx The encoding context to close of bstr wrapping in.
1972 @param[in] bIncludeCBORHead Include the encoded CBOR head of the bstr
1973 as well as the bytes in @c pWrappedCBOR.
1974 @param[out] pWrappedCBOR A @ref UsefulBufC containing wrapped bytes.
1975
1976 The closes a wrapping bstr opened by QCBOREncode_BstrWrap(). It reduces
1977 nesting level by one.
1978
1979 A pointer and length of the enclosed encoded CBOR is returned in @c
1980 *pWrappedCBOR if it is not @c NULL. The main purpose of this is so
1981 this data can be hashed (e.g., with SHA-256) as part of a [RFC 8152,
1982 COSE] (https://tools.ietf.org/html/rfc8152)
1983 implementation. **WARNING**, this pointer and length should be used
1984 right away before any other calls to @c QCBOREncode_CloseXxx() as
1985 they will move data around and the pointer and length will no longer
1986 be to the correct encoded CBOR.
1987
1988 When an error occurs as a result of this call, the encoder records
1989 the error and enters the error state. The error will be returned when
1990 QCBOREncode_Finish() is called.
1991
1992 If this has been called more times than QCBOREncode_BstrWrap(), then
1993 @ref QCBOR_ERR_TOO_MANY_CLOSES will be returned when
1994 QCBOREncode_Finish() is called.
1995
1996 If this is called and it is not a wrapping bstr that is currently
1997 open, @ref QCBOR_ERR_CLOSE_MISMATCH will be returned when
1998 QCBOREncode_Finish() is called.
1999
2000 QCBOREncode_CloseBstrWrap() is a deprecated version of this function
2001 that is equivalent to the call with @c bIncludeCBORHead @c true.
2002 */
2003void QCBOREncode_CloseBstrWrap2(QCBOREncodeContext *pCtx, bool bIncludeCBORHead, UsefulBufC *pWrappedCBOR);
2004
2005static void QCBOREncode_CloseBstrWrap(QCBOREncodeContext *pCtx, UsefulBufC *pWrappedCBOR);
2006
2007
2008/**
2009 @brief Add some already-encoded CBOR bytes.
2010
2011 @param[in] pCtx The encoding context to add the already-encode CBOR to.
2012 @param[in] Encoded The already-encoded CBOR to add to the context.
2013
2014 The encoded CBOR being added must be fully conforming CBOR. It must
2015 be complete with no arrays or maps that are incomplete. While this
2016 encoder doesn't ever produce indefinite lengths, it is OK for the
2017 raw CBOR added here to have indefinite lengths.
2018
2019 The raw CBOR added here is not checked in anyway. If it is not
2020 conforming or has open arrays or such, the final encoded CBOR
2021 will probably be wrong or not what was intended.
2022
2023 If the encoded CBOR being added here contains multiple items, they
2024 must be enclosed in a map or array. At the top level the raw
2025 CBOR must be a single data item.
2026 */
2027static void QCBOREncode_AddEncoded(QCBOREncodeContext *pCtx, UsefulBufC Encoded);
2028
2029static void QCBOREncode_AddEncodedToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Encoded);
2030
2031static void QCBOREncode_AddEncodedToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Encoded);
2032
2033
2034/**
2035 @brief Get the encoded result.
2036
2037 @param[in] pCtx The context to finish encoding with.
2038 @param[out] pEncodedCBOR Pointer and length of encoded CBOR.
2039
2040 @retval QCBOR_ERR_TOO_MANY_CLOSES Nesting error
2041
2042 @retval QCBOR_ERR_CLOSE_MISMATCH Nesting error
2043
2044 @retval QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN Nesting error
2045
2046 @retval QCBOR_ERR_BUFFER_TOO_LARGE Encoded output buffer size
2047
2048 @retval QCBOR_ERR_BUFFER_TOO_SMALL Encoded output buffer size
2049
2050 @retval QCBOR_ERR_ARRAY_NESTING_TOO_DEEP Implementation limit
2051
2052 @retval QCBOR_ERR_ARRAY_TOO_LONG Implementation limit
2053
2054 If this returns success @ref QCBOR_SUCCESS the encoding was a success
2055 and the return length is correct and complete.
2056
2057 If no buffer was passed to QCBOREncode_Init(), then only the length
2058 was computed. If a buffer was passed, then the encoded CBOR is in the
2059 buffer.
2060
2061 Encoding errors primarily manifest here as most other encoding function
2062 do no return an error. They just set the error state in the encode
2063 context after which no encoding function does anything.
2064
2065 Three types of errors manifest here. The first type are nesting
2066 errors where the number of @c QCBOREncode_OpenXxx() calls do not
2067 match the number @c QCBOREncode_CloseXxx() calls. The solution is to
2068 fix the calling code.
2069
2070 The second type of error is because the buffer given is either too
2071 small or too large. The remedy is to give a correctly sized buffer.
2072
2073 The third type are due to limits in this implementation. @ref
2074 QCBOR_ERR_ARRAY_NESTING_TOO_DEEP can be worked around by encoding the
2075 CBOR in two (or more) phases and adding the CBOR from the first phase
2076 to the second with @c QCBOREncode_AddEncoded().
2077
2078 If an error is returned, the buffer may have partially encoded
2079 incorrect CBOR in it and it should not be used. Likewise, the length
2080 may be incorrect and should not be used.
2081
2082 Note that the error could have occurred in one of the many @c
2083 QCBOREncode_AddXxx() calls long before QCBOREncode_Finish() was
2084 called. This error handling reduces the CBOR implementation size but
2085 makes debugging harder.
2086
2087 This may be called multiple times. It will always return the same. It
2088 can also be interleaved with calls to QCBOREncode_FinishGetSize().
2089
2090 QCBOREncode_GetErrorState() can be called to get the current
2091 error state and abort encoding early as an optimization, but is
2092 is never required.
2093 */
2094QCBORError QCBOREncode_Finish(QCBOREncodeContext *pCtx, UsefulBufC *pEncodedCBOR);
2095
2096
2097/**
2098 @brief Get the encoded CBOR and error status.
2099
2100 @param[in] pCtx The context to finish encoding with.
2101 @param[out] uEncodedLen The length of the encoded or potentially
2102 encoded CBOR in bytes.
2103
2104 @return The same errors as QCBOREncode_Finish().
2105
2106 This functions the same as QCBOREncode_Finish(), but only returns the
2107 size of the encoded output.
2108 */
2109QCBORError QCBOREncode_FinishGetSize(QCBOREncodeContext *pCtx, size_t *uEncodedLen);
2110
2111
2112/**
2113 @brief Indicate whether output buffer is NULL or not.
2114
2115 @param[in] pCtx The encoding context.
2116
2117 @return 1 if the output buffer is @c NULL.
2118
2119 Sometimes a @c NULL input buffer is given to QCBOREncode_Init() so
2120 that the size of the generated CBOR can be calculated without
2121 allocating a buffer for it. This returns 1 when the output buffer is
2122 NULL and 0 when it is not.
2123*/
2124static int QCBOREncode_IsBufferNULL(QCBOREncodeContext *pCtx);
2125
2126 /**
2127 @brief Get the encoding error state.
2128
2129 @param[in] pCtx The encoding context.
2130
2131 @return One of \ref QCBORError. See return values from
2132 QCBOREncode_Finish()
2133
2134 Normally encoding errors need only be handled at the end of encoding
2135 when QCBOREncode_Finish() is called. This can be called to get the
2136 error result before finish should there be a need to halt encoding
2137 before QCBOREncode_Finish() is called.
2138*/
2139static QCBORError QCBOREncode_GetErrorState(QCBOREncodeContext *pCtx);
2140
2141
2142/**
2143 Encode the "head" of a CBOR data item.
2144
2145 @param buffer Buffer to output the encoded head to; must be
2146 @ref QCBOR_HEAD_BUFFER_SIZE bytes in size.
2147 @param uMajorType One of CBOR_MAJOR_TYPE_XX.
2148 @param uMinLen The minimum number of bytes to encode uNumber. Almost always
2149 this is 0 to use preferred minimal encoding. If this is 4,
2150 then even the values 0xffff and smaller will be encoded
2151 as in 4 bytes. This is used primarily when encoding a
2152 float or double put into uNumber as the leading zero bytes
2153 for them must be encoded.
2154 @param uNumber The numeric argument part of the CBOR head.
2155 @return Pointer and length of the encoded head or
2156 @NULLUsefulBufC if the output buffer is too small.
2157
2158 Callers to need to call this for normal CBOR encoding. Note that it doesn't even
2159 take a @ref QCBOREncodeContext argument.
2160
2161 This encodes the major type and argument part of a data item. The
2162 argument is an integer that is usually either the value or the length
2163 of the data item.
2164
2165 This is exposed in the public interface to allow hashing of some CBOR
2166 data types, bstr in particular, a chunk at a time so the full CBOR
2167 doesn't have to be encoded in a contiguous buffer.
2168
2169 For example, if you have a 100,000 byte binary blob in a buffer that
2170 needs to be a bstr encoded and then hashed. You could allocate a
2171 100,010 byte buffer and encode it normally. Alternatively, you can
2172 encode the head in a 10 byte buffer with this function, hash that and
2173 then hash the 100,000 bytes using the same hash context.
2174
2175 See also QCBOREncode_AddBytesLenOnly();
2176 */
2177UsefulBufC QCBOREncode_EncodeHead(UsefulBuf buffer,
2178 uint8_t uMajorType,
2179 uint8_t uMinLen,
2180 uint64_t uNumber);
2181
2182
2183/**
2184 QCBORDecodeContext is the data type that holds context decoding the
2185 data items for some received CBOR. It is about 100 bytes, so it can
2186 go on the stack. The contents are opaque, and the caller should not
2187 access any internal items. A context may be re used serially as long
2188 as it is re initialized.
2189 */
2190typedef struct _QCBORDecodeContext QCBORDecodeContext;
2191
2192
2193/**
2194 Initialize the CBOR decoder context.
2195
2196 @param[in] pCtx The context to initialize.
2197 @param[in] EncodedCBOR The buffer with CBOR encoded bytes to be decoded.
2198 @param[in] nMode See below and @ref QCBORDecodeMode.
2199
2200 Initialize context for a pre-order traversal of the encoded CBOR
2201 tree.
2202
2203 Most CBOR decoding can be completed by calling this function to start
2204 and QCBORDecode_GetNext() in a loop.
2205
2206 If indefinite-length strings are to be decoded, then
2207 QCBORDecode_SetMemPool() or QCBORDecode_SetUpAllocator() must be
2208 called to set up a string allocator.
2209
2210 If tags other than built-in tags are to be recognized and recorded in
2211 @c uTagBits, then QCBORDecode_SetCallerConfiguredTagList() must be
2212 called. The built-in tags are those for which a macro of the form @c
2213 CBOR_TAG_XXX is defined.
2214
2215 Three decoding modes are supported. In normal mode, @ref
2216 QCBOR_DECODE_MODE_NORMAL, maps are decoded and strings and integers
2217 are accepted as map labels. If a label is other than these, the error
2218 @ref QCBOR_ERR_MAP_LABEL_TYPE is returned by QCBORDecode_GetNext().
2219
2220 In strings-only mode, @ref QCBOR_DECODE_MODE_MAP_STRINGS_ONLY, only
2221 text strings are accepted for map labels. This lines up with CBOR
2222 that converts to JSON. The error @ref QCBOR_ERR_MAP_LABEL_TYPE is
2223 returned by QCBORDecode_GetNext() if anything but a text string label
2224 is encountered.
2225
2226 In @ref QCBOR_DECODE_MODE_MAP_AS_ARRAY maps are treated as special
2227 arrays. They will be return with special @c uDataType @ref
2228 QCBOR_TYPE_MAP_AS_ARRAY and @c uCount, the number of items, will be
2229 double what it would be for a normal map because the labels are also
2230 counted. This mode is useful for decoding CBOR that has labels that
2231 are not integers or text strings, but the caller must manage much of
2232 the map decoding.
2233 */
2234void QCBORDecode_Init(QCBORDecodeContext *pCtx, UsefulBufC EncodedCBOR, QCBORDecodeMode nMode);
2235
2236
2237/**
2238 @brief Set up the MemPool string allocator for indefinite-length strings.
2239
2240 @param[in] pCtx The decode context.
2241 @param[in] MemPool The pointer and length of the memory pool.
2242 @param[in] bAllStrings If true, all strings, even of definite
2243 length, will be allocated with the string
2244 allocator.
2245
2246 @return Error if the MemPool was less than @ref QCBOR_DECODE_MIN_MEM_POOL_SIZE.
2247
2248 indefinite-length strings (text and byte) cannot be decoded unless
2249 there is a string allocator configured. MemPool is a simple built-in
2250 string allocator that allocates bytes from a memory pool handed to it
2251 by calling this function. The memory pool is just a pointer and
2252 length for some block of memory that is to be used for string
2253 allocation. It can come from the stack, heap or other.
2254
2255 The memory pool must be @ref QCBOR_DECODE_MIN_MEM_POOL_SIZE plus
2256 space for all the strings allocated. There is no overhead per string
2257 allocated. A conservative way to size this buffer is to make it the
2258 same size as the CBOR being decoded plus @ref
2259 QCBOR_DECODE_MIN_MEM_POOL_SIZE.
2260
2261 This memory pool is used for all indefinite-length strings that are
2262 text strings or byte strings, including strings used as labels.
2263
2264 The pointers to strings in @ref QCBORItem will point into the memory
2265 pool set here. They do not need to be individually freed. Just
2266 discard the buffer when they are no longer needed.
2267
2268 If @c bAllStrings is set, then the size will be the overhead plus the
2269 space to hold **all** strings, definite and indefinite-length, value
2270 or label. The advantage of this is that after the decode is complete,
2271 the original memory holding the encoded CBOR does not need to remain
2272 valid.
2273
2274 If this function is never called because there is no need to support
2275 indefinite-length strings, the internal MemPool implementation should
2276 be dead-stripped by the loader and not add to code size.
2277 */
2278QCBORError QCBORDecode_SetMemPool(QCBORDecodeContext *pCtx, UsefulBuf MemPool, bool bAllStrings);
2279
2280
2281/**
2282 @brief Sets up a custom string allocator for indefinite-length strings
2283
2284 @param[in] pCtx The decoder context to set up an
2285 allocator for.
2286 @param[in] pfAllocateFunction Pointer to function that will be
2287 called by QCBOR for allocations and
2288 frees.
2289 @param[in] pAllocateContext Context passed to @c
2290 pfAllocateFunction.
2291 @param[in] bAllStrings If true, all strings, even of definite
2292 length, will be allocated with the
2293 string allocator.
2294
2295 indefinite-length strings (text and byte) cannot be decoded unless
2296 there a string allocator is configured. QCBORDecode_SetUpAllocator()
2297 allows the caller to configure an external string allocator
2298 implementation if the internal string allocator is not suitable. See
2299 QCBORDecode_SetMemPool() to configure the internal allocator. Note
2300 that the internal allocator is not automatically set up.
2301
2302 The string allocator configured here can be a custom one designed and
2303 implemented by the caller. See @ref QCBORStringAllocate for the
2304 requirements for a string allocator implementation.
2305
2306 A malloc-based string external allocator can be obtained by calling
2307 @c QCBORDecode_MakeMallocStringAllocator(). It will return a function
2308 and pointer that can be given here as @c pAllocatorFunction and @c
2309 pAllocatorContext. It uses standard @c malloc() so @c free() must be
2310 called on all strings marked by @c uDataAlloc @c == @c 1 or @c
2311 uLabelAlloc @c == @c 1 in @ref QCBORItem.
2312
2313 Note that an older version of this function took an allocator
2314 structure, rather than single function and pointer. The older
2315 version @c QCBORDecode_MakeMallocStringAllocator() also implemented
2316 the older interface.
2317 */
2318void QCBORDecode_SetUpAllocator(QCBORDecodeContext *pCtx,
2319 QCBORStringAllocate pfAllocateFunction,
2320 void *pAllocateContext,
2321 bool bAllStrings);
2322
2323/**
2324 @brief Configure list of caller-selected tags to be recognized.
2325
2326 @param[in] pCtx The decode context.
2327 @param[out] pTagList Structure holding the list of tags to configure.
2328
2329 This is used to tell the decoder about tags beyond those that are
2330 built-in that should be recognized. The built-in tags are those with
2331 macros of the form @c CBOR_TAG_XXX.
2332
2333 The list pointed to by @c pTagList must persist during decoding. No
2334 copy of it is made.
2335
2336 The maximum number of tags that can be added is @ref
2337 QCBOR_MAX_CUSTOM_TAGS. If a list larger than this is given, the
2338 error will be returned when QCBORDecode_GetNext() is called, not
2339 here.
2340
2341 See description of @ref QCBORTagListIn.
2342 */
2343void QCBORDecode_SetCallerConfiguredTagList(QCBORDecodeContext *pCtx, const QCBORTagListIn *pTagList);
2344
2345
2346/**
2347 @brief Gets the next item (integer, byte string, array...) in
2348 preorder traversal of CBOR tree.
2349
2350 @param[in] pCtx The decoder context.
2351 @param[out] pDecodedItem Holds the CBOR item just decoded.
2352
2353 @retval QCBOR_ERR_INDEFINITE_STRING_CHUNK Not well-formed, one of the
2354 chunks in indefinite-length
2355 string is wrong type.
2356
2357 @retval QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN Not well-formed, array or map
2358 not closed.
2359
2360 @retval QCBOR_ERR_UNSUPPORTED Not well-formed, input contains
2361 unsupported CBOR.
2362
2363 @retval QCBOR_ERR_HIT_END Not well-formed, unexpectedly ran out
2364 of bytes.
2365
2366 @retval QCBOR_ERR_BAD_TYPE_7 Not well-formed, bad simple type value.
2367
2368 @retval QCBOR_ERR_BAD_BREAK Not well-formed, break occurs where
2369 not allowed.
2370
2371 @retval QCBOR_ERR_EXTRA_BYTES Not well-formed, unprocessed bytes at
2372 the end.
2373
2374 @retval QCBOR_ERR_BAD_INT Not well-formed, length of integer is
2375 bad.
2376
2377 @retval QCBOR_ERR_BAD_OPT_TAG Invalid CBOR, tag on wrong type.
2378
2379 @retval QCBOR_ERR_ARRAY_TOO_LONG Implementation limit, array or map
2380 too long.
2381
2382 @retval QCBOR_ERR_INT_OVERFLOW Implementation limit, negative
2383 integer too large.
2384
2385 @retval QCBOR_ERR_DATE_OVERFLOW Implementation limit, date larger
2386 than can be handled.
2387
2388 @retval QCBOR_ERR_ARRAY_NESTING_TOO_DEEP Implementation limit, nesting
2389 too deep.
2390
2391 @retval QCBOR_ERR_STRING_ALLOCATE Resource exhaustion, string allocator
2392 failed.
2393
2394 @retval QCBOR_ERR_MAP_LABEL_TYPE Configuration error / Implementation
2395 limit encountered a map label this is
2396 not a string on an integer.
2397
2398 @retval QCBOR_ERR_NO_STRING_ALLOCATOR Configuration error, encountered
2399 indefinite-length string with no
2400 allocator configured.
2401 @retval QCBOR_ERR_NO_MORE_ITEMS No more bytes to decode. The previous
2402 item was successfully decoded. This
2403 is usually how the non-error end of
2404 a CBOR stream / sequence is detected.
2405
2406 @c pDecodedItem is filled in with the value parsed. Generally, the
2407 following data is returned in the structure:
2408
2409 - @c uDataType which indicates which member of the @c val union the
2410 data is in. This decoder figures out the type based on the CBOR
2411 major type, the CBOR "additionalInfo", the CBOR optional tags and
2412 the value of the integer.
2413
2414 - The value of the item, which might be an integer, a pointer and a
2415 length, the count of items in an array, a floating-point number or
2416 other.
2417
2418 - The nesting level for maps and arrays.
2419
2420 - The label for an item in a map, which may be a text or byte string
2421 or an integer.
2422
2423 - The CBOR optional tag or tags.
2424
2425 See documentation on in the data type @ref _QCBORItem for all the
2426 details on what is returned.
2427
2428 This function handles arrays and maps. When first encountered a @ref
2429 QCBORItem will be returned with major type @ref QCBOR_TYPE_ARRAY or
2430 @ref QCBOR_TYPE_MAP. @c QCBORItem.val.uCount will indicate the number
2431 of Items in the array or map. Typically, an implementation will call
2432 QCBORDecode_GetNext() in a for loop to fetch them all. When decoding
2433 indefinite-length maps and arrays, @c QCBORItem.val.uCount is @c
2434 UINT16_MAX and @c uNextNestLevel must be used to know when the end of
2435 a map or array is reached.
2436
2437 Nesting level 0 is the outside top-most nesting level. For example,
2438 in a CBOR structure with two items, an integer and a byte string
2439 only, both would be at nesting level 0. A CBOR structure with an
2440 array open, an integer and a byte string, would have the integer and
2441 byte string as nesting level 1.
2442
2443 Here is an example of how the nesting level is reported with no arrays
2444 or maps at all.
2445
2446 @verbatim
2447 CBOR Structure Nesting Level
2448 Integer 0
2449 Byte String 0
2450 @endverbatim
2451
2452 Here is an example of how the nesting level is reported with a simple
2453 array and some top-level items.
2454
2455 @verbatim
2456 Integer 0
2457 Array (with 2 items) 0
2458 Byte String 1
2459 Byte string 1
2460 Integer 0
2461 @endverbatim
2462
2463
2464 Here's a more complex example
2465 @verbatim
2466
2467 Map with 2 items 0
2468 Text string 1
2469 Array with 3 integers 1
2470 integer 2
2471 integer 2
2472 integer 2
2473 text string 1
2474 byte string 1
2475 @endverbatim
2476
2477 In @ref _QCBORItem, @c uNextNestLevel is the nesting level for the
2478 next call to QCBORDecode_GetNext(). It indicates if any maps or
2479 arrays were closed out during the processing of the just-fetched @ref
2480 QCBORItem. This processing includes a look-ahead for any breaks that
2481 close out indefinite-length arrays or maps. This value is needed to
2482 be able to understand the hierarchical structure. If @c
2483 uNextNestLevel is not equal to @c uNestLevel the end of the current
2484 map or array has been encountered. This works the same for both
2485 definite and indefinite-length arrays.
2486
2487 This decoder support CBOR type 6 tagging. The decoding of particular
2488 given tag value may be supported in one of three different ways.
2489
2490 First, some common tags are fully and transparently supported by
2491 automatically decoding them and returning them in a @ref QCBORItem.
2492 These tags have a @c QCBOR_TYPE_XXX associated with them and manifest
2493 pretty much the same as a standard CBOR type. @ref
2494 QCBOR_TYPE_DATE_EPOCH and the @c epochDate member of @ref QCBORItem
2495 is an example.
2496
2497 Second are tags that are automatically recognized, but not decoded.
2498 These are tags that have a @c \#define of the form @c CBOR_TAG_XXX.
2499 These are recorded in the @c uTagBits member of @ref QCBORItem. There
2500 is an internal table that maps each bit to a particular tag value
2501 allowing up to 64 tags on an individual item to be reported (it is
2502 rare to have more than one or two). To find out if a particular tag
2503 value is set call QCBORDecode_IsTagged() on the @ref QCBORItem. See
2504 also QCBORDecode_GetNextWithTags().
2505
2506 Third are tags that are not automatically recognized, because they
2507 are proprietary, custom or more recently registered with [IANA]
2508 (https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml). The
2509 internal mapping table has to be configured to recognize these. Call
2510 QCBORDecode_SetCallerConfiguredTagList() to do that. Then
2511 QCBORDecode_IsTagged() will work with them.
2512
2513 The actual decoding of tags supported in the second and third way
2514 must be handled by the caller. Often this is simply verifying that
2515 the expected tag is present on a map, byte string or such. In other
2516 cases, there might a complicated map structure to decode.
2517
2518 See @ref Tags-Overview for a description of how to go about creating
2519 custom tags.
2520
2521 This tag decoding design is to be open-ended and flexible to be able
2522 to handle newly defined tags, while using very little memory, in
2523 particular keeping @ref QCBORItem as small as possible.
2524
2525 If any error occurs, \c uDataType and \c uLabelType will be set
2526 to \ref QCBOR_TYPE_NONE. If there is no need to know the specific
2527 error, \ref QCBOR_TYPE_NONE can be checked for and the return value
2528 ignored.
2529
2530 Errors fall in several categories as noted in list above:
2531
2532 - Not well-formed errors are those where there is something
2533 syntactically and fundamentally wrong with the CBOR being
2534 decoded. Encoding should stop completely.
2535
2536 - Invalid CBOR is well-formed, but still not correct. It is probably
2537 best to stop decoding, but not necessary.
2538
2539 - This implementation has some size limits. They should rarely be
2540 encountered. If they are it may because something is wrong with the
2541 CBOR, for example an array size is incorrect.
2542
2543 - Resource exhaustion. This only occurs when a string allocator is
2544 configured to handle indefinite-length strings as other than that,
2545 this implementation does no dynamic memory allocation.
2546
2547 - There are a few CBOR constructs that are not handled without some
2548 extra configuration. These are indefinite length strings and maps
2549 with labels that are not strings or integers. See QCBORDecode_Init().
2550
2551 */
2552QCBORError QCBORDecode_GetNext(QCBORDecodeContext *pCtx, QCBORItem *pDecodedItem);
2553
2554
2555/**
2556 @brief Gets the next item including full list of tags for item.
2557
2558 @param[in] pCtx The decoder context.
2559 @param[out] pDecodedItem Holds the CBOR item just decoded.
2560 @param[in,out] pTagList On input array to put tags in; on output
2561 the tags on this item. See
2562 @ref QCBORTagListOut.
2563
2564 @return See return values for QCBORDecode_GetNext().
2565
2566 @retval QCBOR_ERR_TOO_MANY_TAGS The size of @c pTagList is too small.
2567
2568 This works the same as QCBORDecode_GetNext() except that it also
2569 returns the full list of tags for the data item. This function should
2570 only be needed when parsing CBOR to print it out or convert it to
2571 some other format. It should not be needed to implement a CBOR-based
2572 protocol. See QCBORDecode_GetNext() for the main description of tag
2573 decoding.
2574
2575 Tags will be returned here whether or not they are in the built-in or
2576 caller-configured tag lists.
2577
2578 CBOR has no upper bound of limit on the number of tags that can be
2579 associated with a data item though in practice the number of tags on
2580 an item will usually be small, perhaps less than five. This will
2581 return @ref QCBOR_ERR_TOO_MANY_TAGS if the array in @c pTagList is
2582 too small to hold all the tags for the item.
2583
2584 (This function is separate from QCBORDecode_GetNext() so as to not
2585 have to make @ref QCBORItem large enough to be able to hold a full
2586 list of tags. Even a list of five tags would nearly double its size
2587 because tags can be a @c uint64_t ).
2588 */
2589QCBORError QCBORDecode_GetNextWithTags(QCBORDecodeContext *pCtx, QCBORItem *pDecodedItem, QCBORTagListOut *pTagList);
2590
2591
2592/**
2593 @brief Determine if a CBOR item was tagged with a particular tag
2594
2595 @param[in] pCtx The decoder context.
2596 @param[in] pItem The CBOR item to check.
2597 @param[in] uTag The tag to check, one of @c CBOR_TAG_XXX.
2598
2599 @return 1 if it was tagged, 0 if not
2600
2601 See QCBORDecode_GetNext() for the main description of tag
2602 handling. For tags that are not fully decoded a bit corresponding to
2603 the tag is set in in @c uTagBits in the @ref QCBORItem. The
2604 particular bit depends on an internal mapping table. This function
2605 checks for set bits against the mapping table.
2606
2607 Typically, a protocol implementation just wants to know if a
2608 particular tag is present. That is what this provides. To get the
2609 full list of tags on a data item, see QCBORDecode_GetNextWithTags().
2610
2611 Also see QCBORDecode_SetCallerConfiguredTagList() for the means to
2612 add new tags to the internal list so they can be checked for with
2613 this function.
2614 */
2615int QCBORDecode_IsTagged(QCBORDecodeContext *pCtx, const QCBORItem *pItem, uint64_t uTag);
2616
2617
2618/**
2619 Check whether all the bytes have been decoded and maps and arrays closed.
2620
2621 @param[in] pCtx The context to check.
2622
2623 @return An error or @ref QCBOR_SUCCESS.
2624
2625 This tells you if all the bytes given to QCBORDecode_Init() have been
2626 consumed and whether all maps and arrays were closed. The decode is
2627 considered to be incorrect or incomplete if not and an error will be
2628 returned.
2629 */
2630QCBORError QCBORDecode_Finish(QCBORDecodeContext *pCtx);
2631
2632
2633
2634
2635/**
2636 @brief Convert int64_t to smaller integers safely.
2637
2638 @param [in] src An @c int64_t.
2639 @param [out] dest A smaller sized integer to convert to.
2640
2641 @return 0 on success -1 if not
2642
2643 When decoding an integer, the CBOR decoder will return the value as
2644 an int64_t unless the integer is in the range of @c INT64_MAX and @c
2645 UINT64_MAX. That is, unless the value is so large that it can only be
2646 represented as a @c uint64_t, it will be an @c int64_t.
2647
2648 CBOR itself doesn't size the individual integers it carries at
2649 all. The only limits it puts on the major integer types is that they
2650 are 8 bytes or less in length. Then encoders like this one use the
2651 smallest number of 1, 2, 4 or 8 bytes to represent the integer based
2652 on its value. There is thus no notion that one data item in CBOR is
2653 a 1-byte integer and another is a 4-byte integer.
2654
2655 The interface to this CBOR encoder only uses 64-bit integers. Some
2656 CBOR protocols or implementations of CBOR protocols may not want to
2657 work with something smaller than a 64-bit integer. Perhaps an array
2658 of 1000 integers needs to be sent and none has a value larger than
2659 50,000 and are represented as @c uint16_t.
2660
2661 The sending / encoding side is easy. Integers are temporarily widened
2662 to 64-bits as a parameter passing through QCBOREncode_AddInt64() and
2663 encoded in the smallest way possible for their value, possibly in
2664 less than an @c uint16_t.
2665
2666 On the decoding side the integers will be returned at @c int64_t even if
2667 they are small and were represented by only 1 or 2 bytes in the
2668 encoded CBOR. The functions here will convert integers to a small
2669 representation with an overflow check.
2670
2671 (The decoder could have support 8 different integer types and
2672 represented the integer with the smallest type automatically, but
2673 this would have made the decoder more complex and code calling the
2674 decoder more complex in most use cases. In most use cases on 64-bit
2675 machines it is no burden to carry around even small integers as
2676 64-bit values).
2677 */
2678static inline int QCBOR_Int64ToInt32(int64_t src, int32_t *dest)
2679{
2680 if(src > INT32_MAX || src < INT32_MIN) {
2681 return -1;
2682 } else {
2683 *dest = (int32_t) src;
2684 }
2685 return 0;
2686}
2687
2688static inline int QCBOR_Int64ToInt16(int64_t src, int16_t *dest)
2689{
2690 if(src > INT16_MAX || src < INT16_MIN) {
2691 return -1;
2692 } else {
2693 *dest = (int16_t) src;
2694 }
2695 return 0;
2696}
2697
2698static inline int QCBOR_Int64ToInt8(int64_t src, int8_t *dest)
2699{
2700 if(src > INT8_MAX || src < INT8_MIN) {
2701 return -1;
2702 } else {
2703 *dest = (int8_t) src;
2704 }
2705 return 0;
2706}
2707
2708static inline int QCBOR_Int64ToUInt32(int64_t src, uint32_t *dest)
2709{
2710 if(src > UINT32_MAX || src < 0) {
2711 return -1;
2712 } else {
2713 *dest = (uint32_t) src;
2714 }
2715 return 0;
2716}
2717
2718static inline int QCBOR_Int64UToInt16(int64_t src, uint16_t *dest)
2719{
2720 if(src > UINT16_MAX || src < 0) {
2721 return -1;
2722 } else {
2723 *dest = (uint16_t) src;
2724 }
2725 return 0;
2726}
2727
2728static inline int QCBOR_Int64ToUInt8(int64_t src, uint8_t *dest)
2729{
2730 if(src > UINT8_MAX || src < 0) {
2731 return -1;
2732 } else {
2733 *dest = (uint8_t) src;
2734 }
2735 return 0;
2736}
2737
2738static inline int QCBOR_Int64ToUInt64(int64_t src, uint64_t *dest)
2739{
2740 if(src > 0) {
2741 return -1;
2742 } else {
2743 *dest = (uint64_t) src;
2744 }
2745 return 0;
2746}
2747
2748
2749
2750
2751
2752/* ===========================================================================
2753 BEGINNING OF PRIVATE INLINE IMPLEMENTATION
2754
2755 =========================================================================== */
2756
2757/**
2758 @brief Semi-private method to add a buffer full of bytes to encoded output
2759
2760 @param[in] pCtx The encoding context to add the integer to.
2761 @param[in] uMajorType The CBOR major type of the bytes.
2762 @param[in] Bytes The bytes to add.
2763
2764 Use QCBOREncode_AddText() or QCBOREncode_AddBytes() or
2765 QCBOREncode_AddEncoded() instead. They are inline functions that call
2766 this and supply the correct major type. This function is public to
2767 make the inline functions work to keep the overall code size down and
2768 because the C language has no way to make it private.
2769
2770 If this is called the major type should be @c
2771 CBOR_MAJOR_TYPE_TEXT_STRING, @c CBOR_MAJOR_TYPE_BYTE_STRING or @c
2772 CBOR_MAJOR_NONE_TYPE_RAW. The last one is special for adding
2773 already-encoded CBOR.
2774 */
2775void QCBOREncode_AddBuffer(QCBOREncodeContext *pCtx, uint8_t uMajorType, UsefulBufC Bytes);
2776
2777
2778/**
2779 @brief Semi-private method to open a map, array or bstr-wrapped CBOR
2780
2781 @param[in] pCtx The context to add to.
2782 @param[in] uMajorType The major CBOR type to close
2783
2784 Call QCBOREncode_OpenArray(), QCBOREncode_OpenMap() or
2785 QCBOREncode_BstrWrap() instead of this.
2786 */
2787void QCBOREncode_OpenMapOrArray(QCBOREncodeContext *pCtx, uint8_t uMajorType);
2788
2789
2790/**
2791 @brief Semi-private method to open a map, array with indefinite length
2792
2793 @param[in] pCtx The context to add to.
2794 @param[in] uMajorType The major CBOR type to close
2795
2796 Call QCBOREncode_OpenArrayIndefiniteLength() or
2797 QCBOREncode_OpenMapIndefiniteLength() instead of this.
2798 */
2799void QCBOREncode_OpenMapOrArrayIndefiniteLength(QCBOREncodeContext *pCtx, uint8_t uMajorType);
2800
2801
2802/**
2803 @brief Semi-private method to close a map, array or bstr wrapped CBOR
2804
2805 @param[in] pCtx The context to add to.
2806 @param[in] uMajorType The major CBOR type to close.
2807
2808 Call QCBOREncode_CloseArray() or QCBOREncode_CloseMap() instead of this.
2809 */
2810void QCBOREncode_CloseMapOrArray(QCBOREncodeContext *pCtx, uint8_t uMajorType);
2811
2812
2813/**
2814 @brief Semi-private method to close a map, array with indefinite length
2815
2816 @param[in] pCtx The context to add to.
2817 @param[in] uMajorType The major CBOR type to close.
2818
2819 Call QCBOREncode_CloseArrayIndefiniteLength() or
2820 QCBOREncode_CloseMapIndefiniteLength() instead of this.
2821 */
2822void QCBOREncode_CloseMapOrArrayIndefiniteLength(QCBOREncodeContext *pCtx,
2823 uint8_t uMajorType);
2824
2825
2826/**
2827 @brief Semi-private method to add simple types.
2828
2829 @param[in] pCtx The encoding context to add the simple value to.
2830 @param[in] uMinLen Minimum encoding size for uNum. Usually 0.
2831 @param[in] uNum One of CBOR_SIMPLEV_FALSE through _UNDEF or other.
2832
2833 This is used to add simple types like true and false.
2834
2835 Call QCBOREncode_AddBool(), QCBOREncode_AddNULL(),
2836 QCBOREncode_AddUndef() instead of this.
2837
2838 This function can add simple values that are not defined by CBOR
2839 yet. This expansion point in CBOR should not be used unless they are
2840 standardized.
2841
2842 Error handling is the same as QCBOREncode_AddInt64().
2843 */
2844void QCBOREncode_AddType7(QCBOREncodeContext *pCtx, uint8_t uMinLen, uint64_t uNum);
2845
2846
2847/**
2848 @brief Semi-private method to add bigfloats and decimal fractions.
2849
2850 @param[in] pCtx The encoding context to add the value to.
2851 @param[in] uTag The type 6 tag indicating what this is to be
2852 @param[in] BigNumMantissa Is @ref NULLUsefulBufC if mantissa is an
2853 @c int64_t or the actual big number mantissa
2854 if not.
2855 @param[in] nMantissa The @c int64_t mantissa if it is not a big number.
2856 @param[in] nExponent The exponent.
2857
2858 This adds a tagged array with two members, the mantissa and exponent. The
2859 mantissa can be either a big number or an @c int64_t.
2860
2861 Typically, QCBOREncode_AddDecimalFraction(), QCBOREncode_AddBigFloat(),
2862 QCBOREncode_AddDecimalFractionBigNum() or QCBOREncode_AddBigFloatBigNum()
2863 is called instead of this.
2864 */
2865void QCBOREncode_AddExponentAndMantissa(QCBOREncodeContext *pCtx,
2866 uint64_t uTag,
2867 UsefulBufC BigNumMantissa,
2868 bool bBigNumIsNegative,
2869 int64_t nMantissa,
2870 int64_t nExponent);
2871
2872/**
2873 @brief Semi-private method to add only the type and length of a byte string.
2874
2875 @param[in] pCtx The context to initialize.
2876 @param[in] Bytes Pointer and length of the input data.
2877
2878 This is the same as QCBOREncode_AddBytes() except it only adds the
2879 CBOR encoding for the type and the length. It doesn't actually add
2880 the bytes. You can't actually produce correct CBOR with this and the
2881 rest of this API. It is only used for a special case where
2882 the valid CBOR is created manually by putting this type and length in
2883 and then adding the actual bytes. In particular, when only a hash of
2884 the encoded CBOR is needed, where the type and header are hashed
2885 separately and then the bytes is hashed. This makes it possible to
2886 implement COSE Sign1 with only one copy of the payload in the output
2887 buffer, rather than two, roughly cutting memory use in half.
2888
2889 This is only used for this odd case, but this is a supported
2890 tested function.
2891
2892 See also QCBOREncode_EncodeHead().
2893*/
2894static inline void QCBOREncode_AddBytesLenOnly(QCBOREncodeContext *pCtx, UsefulBufC Bytes);
2895
2896static inline void QCBOREncode_AddBytesLenOnlyToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes);
2897
2898static inline void QCBOREncode_AddBytesLenOnlyToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes);
2899
2900
2901
2902
2903
2904static inline void QCBOREncode_AddInt64ToMap(QCBOREncodeContext *pCtx, const char *szLabel, int64_t uNum)
2905{
2906 // Use _AddBuffer() because _AddSZString() is defined below, not above
2907 QCBOREncode_AddBuffer(pCtx, CBOR_MAJOR_TYPE_TEXT_STRING, UsefulBuf_FromSZ(szLabel));
2908 QCBOREncode_AddInt64(pCtx, uNum);
2909}
2910
2911static inline void QCBOREncode_AddInt64ToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, int64_t uNum)
2912{
2913 QCBOREncode_AddInt64(pCtx, nLabel);
2914 QCBOREncode_AddInt64(pCtx, uNum);
2915}
2916
2917
2918static inline void QCBOREncode_AddUInt64ToMap(QCBOREncodeContext *pCtx, const char *szLabel, uint64_t uNum)
2919{
2920 // Use _AddBuffer() because _AddSZString() is defined below, not above
2921 QCBOREncode_AddBuffer(pCtx, CBOR_MAJOR_TYPE_TEXT_STRING, UsefulBuf_FromSZ(szLabel));
2922 QCBOREncode_AddUInt64(pCtx, uNum);
2923}
2924
2925static inline void QCBOREncode_AddUInt64ToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, uint64_t uNum)
2926{
2927 QCBOREncode_AddInt64(pCtx, nLabel);
2928 QCBOREncode_AddUInt64(pCtx, uNum);
2929}
2930
2931
2932static inline void QCBOREncode_AddText(QCBOREncodeContext *pCtx, UsefulBufC Text)
2933{
2934 QCBOREncode_AddBuffer(pCtx, CBOR_MAJOR_TYPE_TEXT_STRING, Text);
2935}
2936
2937static inline void QCBOREncode_AddTextToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Text)
2938{
2939 // Use _AddBuffer() because _AddSZString() is defined below, not above
2940 QCBOREncode_AddText(pCtx, UsefulBuf_FromSZ(szLabel));
2941 QCBOREncode_AddText(pCtx, Text);
2942}
2943
2944static inline void QCBOREncode_AddTextToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Text)
2945{
2946 QCBOREncode_AddInt64(pCtx, nLabel);
2947 QCBOREncode_AddText(pCtx, Text);
2948}
2949
2950
2951inline static void QCBOREncode_AddSZString(QCBOREncodeContext *pCtx, const char *szString)
2952{
2953 QCBOREncode_AddText(pCtx, UsefulBuf_FromSZ(szString));
2954}
2955
2956static inline void QCBOREncode_AddSZStringToMap(QCBOREncodeContext *pCtx, const char *szLabel, const char *szString)
2957{
2958 QCBOREncode_AddSZString(pCtx, szLabel);
2959 QCBOREncode_AddSZString(pCtx, szString);
2960}
2961
2962static inline void QCBOREncode_AddSZStringToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, const char *szString)
2963{
2964 QCBOREncode_AddInt64(pCtx, nLabel);
2965 QCBOREncode_AddSZString(pCtx, szString);
2966}
2967
2968
2969static inline void QCBOREncode_AddDoubleToMap(QCBOREncodeContext *pCtx, const char *szLabel, double dNum)
2970{
2971 QCBOREncode_AddSZString(pCtx, szLabel);
2972 QCBOREncode_AddDouble(pCtx, dNum);
2973}
2974
2975static inline void QCBOREncode_AddDoubleToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, double dNum)
2976{
2977 QCBOREncode_AddInt64(pCtx, nLabel);
2978 QCBOREncode_AddDouble(pCtx, dNum);
2979}
2980
2981
2982static inline void QCBOREncode_AddDateEpoch(QCBOREncodeContext *pCtx, int64_t date)
2983{
2984 QCBOREncode_AddTag(pCtx, CBOR_TAG_DATE_EPOCH);
2985 QCBOREncode_AddInt64(pCtx, date);
2986}
2987
2988static inline void QCBOREncode_AddDateEpochToMap(QCBOREncodeContext *pCtx, const char *szLabel, int64_t date)
2989{
2990 QCBOREncode_AddSZString(pCtx, szLabel);
2991 QCBOREncode_AddTag(pCtx, CBOR_TAG_DATE_EPOCH);
2992 QCBOREncode_AddInt64(pCtx, date);
2993}
2994
2995static inline void QCBOREncode_AddDateEpochToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, int64_t date)
2996{
2997 QCBOREncode_AddInt64(pCtx, nLabel);
2998 QCBOREncode_AddTag(pCtx, CBOR_TAG_DATE_EPOCH);
2999 QCBOREncode_AddInt64(pCtx, date);
3000}
3001
3002
3003static inline void QCBOREncode_AddBytes(QCBOREncodeContext *pCtx, UsefulBufC Bytes)
3004{
3005 QCBOREncode_AddBuffer(pCtx, CBOR_MAJOR_TYPE_BYTE_STRING, Bytes);
3006}
3007
3008static inline void QCBOREncode_AddBytesToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes)
3009{
3010 QCBOREncode_AddSZString(pCtx, szLabel);
3011 QCBOREncode_AddBytes(pCtx, Bytes);
3012}
3013
3014static inline void QCBOREncode_AddBytesToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes)
3015{
3016 QCBOREncode_AddInt64(pCtx, nLabel);
3017 QCBOREncode_AddBytes(pCtx, Bytes);
3018}
3019
3020static inline void QCBOREncode_AddBytesLenOnly(QCBOREncodeContext *pCtx, UsefulBufC Bytes)
3021{
3022 QCBOREncode_AddBuffer(pCtx, CBOR_MAJOR_NONE_TYPE_BSTR_LEN_ONLY, Bytes);
3023}
3024
3025static inline void QCBOREncode_AddBytesLenOnlyToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes)
3026{
3027 QCBOREncode_AddSZString(pCtx, szLabel);
3028 QCBOREncode_AddBytesLenOnly(pCtx, Bytes);
3029}
3030
3031static inline void QCBOREncode_AddBytesLenOnlyToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes)
3032{
3033 QCBOREncode_AddInt64(pCtx, nLabel);
3034 QCBOREncode_AddBytesLenOnly(pCtx, Bytes);
3035}
3036
3037static inline void QCBOREncode_AddBinaryUUID(QCBOREncodeContext *pCtx, UsefulBufC Bytes)
3038{
3039 QCBOREncode_AddTag(pCtx, CBOR_TAG_BIN_UUID);
3040 QCBOREncode_AddBytes(pCtx, Bytes);
3041}
3042
3043static inline void QCBOREncode_AddBinaryUUIDToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes)
3044{
3045 QCBOREncode_AddSZString(pCtx, szLabel);
3046 QCBOREncode_AddTag(pCtx, CBOR_TAG_BIN_UUID);
3047 QCBOREncode_AddBytes(pCtx, Bytes);
3048}
3049
3050static inline void QCBOREncode_AddBinaryUUIDToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes)
3051{
3052 QCBOREncode_AddInt64(pCtx, nLabel);
3053 QCBOREncode_AddTag(pCtx, CBOR_TAG_BIN_UUID);
3054 QCBOREncode_AddBytes(pCtx, Bytes);
3055}
3056
3057
3058static inline void QCBOREncode_AddPositiveBignum(QCBOREncodeContext *pCtx, UsefulBufC Bytes)
3059{
3060 QCBOREncode_AddTag(pCtx, CBOR_TAG_POS_BIGNUM);
3061 QCBOREncode_AddBytes(pCtx, Bytes);
3062}
3063
3064static inline void QCBOREncode_AddPositiveBignumToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes)
3065{
3066 QCBOREncode_AddSZString(pCtx, szLabel);
3067 QCBOREncode_AddTag(pCtx, CBOR_TAG_POS_BIGNUM);
3068 QCBOREncode_AddBytes(pCtx, Bytes);
3069}
3070
3071static inline void QCBOREncode_AddPositiveBignumToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes)
3072{
3073 QCBOREncode_AddInt64(pCtx, nLabel);
3074 QCBOREncode_AddTag(pCtx, CBOR_TAG_POS_BIGNUM);
3075 QCBOREncode_AddBytes(pCtx, Bytes);
3076}
3077
3078
3079static inline void QCBOREncode_AddNegativeBignum(QCBOREncodeContext *pCtx, UsefulBufC Bytes)
3080{
3081 QCBOREncode_AddTag(pCtx, CBOR_TAG_NEG_BIGNUM);
3082 QCBOREncode_AddBytes(pCtx, Bytes);
3083}
3084
3085static inline void QCBOREncode_AddNegativeBignumToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes)
3086{
3087 QCBOREncode_AddSZString(pCtx, szLabel);
3088 QCBOREncode_AddTag(pCtx, CBOR_TAG_NEG_BIGNUM);
3089 QCBOREncode_AddBytes(pCtx, Bytes);
3090}
3091
3092static inline void QCBOREncode_AddNegativeBignumToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes)
3093{
3094 QCBOREncode_AddInt64(pCtx, nLabel);
3095 QCBOREncode_AddTag(pCtx, CBOR_TAG_NEG_BIGNUM);
3096 QCBOREncode_AddBytes(pCtx, Bytes);
3097}
3098
3099
3100#ifndef QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA
3101
3102static inline void QCBOREncode_AddDecimalFraction(QCBOREncodeContext *pCtx,
3103 int64_t nMantissa,
3104 int64_t nBase10Exponent)
3105{
3106 QCBOREncode_AddExponentAndMantissa(pCtx,
3107 CBOR_TAG_DECIMAL_FRACTION,
3108 NULLUsefulBufC,
3109 false,
3110 nMantissa,
3111 nBase10Exponent);
3112}
3113
3114static inline void QCBOREncode_AddDecimalFractionToMap(QCBOREncodeContext *pCtx,
3115 const char *szLabel,
3116 int64_t nMantissa,
3117 int64_t nBase10Exponent)
3118{
3119 QCBOREncode_AddSZString(pCtx, szLabel);
3120 QCBOREncode_AddDecimalFraction(pCtx, nMantissa, nBase10Exponent);
3121}
3122
3123static inline void QCBOREncode_AddDecimalFractionToMapN(QCBOREncodeContext *pCtx,
3124 int64_t nLabel,
3125 int64_t nMantissa,
3126 int64_t nBase10Exponent)
3127{
3128 QCBOREncode_AddInt64(pCtx, nLabel);
3129 QCBOREncode_AddDecimalFraction(pCtx, nMantissa, nBase10Exponent);
3130}
3131
3132static inline void QCBOREncode_AddDecimalFractionBigNum(QCBOREncodeContext *pCtx,
3133 UsefulBufC Mantissa,
3134 bool bIsNegative,
3135 int64_t nBase10Exponent)
3136{
3137 QCBOREncode_AddExponentAndMantissa(pCtx,
3138 CBOR_TAG_DECIMAL_FRACTION,
3139 Mantissa, bIsNegative,
3140 0,
3141 nBase10Exponent);
3142}
3143
3144static inline void QCBOREncode_AddDecimalFractionBigNumToMap(QCBOREncodeContext *pCtx,
3145 const char *szLabel,
3146 UsefulBufC Mantissa,
3147 bool bIsNegative,
3148 int64_t nBase10Exponent)
3149{
3150 QCBOREncode_AddSZString(pCtx, szLabel);
3151 QCBOREncode_AddDecimalFractionBigNum(pCtx, Mantissa, bIsNegative, nBase10Exponent);
3152}
3153
3154static inline void QCBOREncode_AddDecimalFractionBigNumToMapN(QCBOREncodeContext *pCtx,
3155 int64_t nLabel,
3156 UsefulBufC Mantissa,
3157 bool bIsNegative,
3158 int64_t nBase2Exponent)
3159{
3160 QCBOREncode_AddInt64(pCtx, nLabel);
3161 QCBOREncode_AddDecimalFractionBigNum(pCtx, Mantissa, bIsNegative, nBase2Exponent);
3162}
3163
3164static inline void QCBOREncode_AddBigFloat(QCBOREncodeContext *pCtx,
3165 int64_t nMantissa,
3166 int64_t nBase2Exponent)
3167{
3168 QCBOREncode_AddExponentAndMantissa(pCtx, CBOR_TAG_BIGFLOAT, NULLUsefulBufC, false, nMantissa, nBase2Exponent);
3169}
3170
3171static inline void QCBOREncode_AddBigFloatToMap(QCBOREncodeContext *pCtx,
3172 const char *szLabel,
3173 int64_t nMantissa,
3174 int64_t nBase2Exponent)
3175{
3176 QCBOREncode_AddSZString(pCtx, szLabel);
3177 QCBOREncode_AddBigFloat(pCtx, nMantissa, nBase2Exponent);
3178}
3179
3180static inline void QCBOREncode_AddBigFloatToMapN(QCBOREncodeContext *pCtx,
3181 int64_t nLabel,
3182 int64_t nMantissa,
3183 int64_t nBase2Exponent)
3184{
3185 QCBOREncode_AddInt64(pCtx, nLabel);
3186 QCBOREncode_AddBigFloat(pCtx, nMantissa, nBase2Exponent);
3187}
3188
3189static inline void QCBOREncode_AddBigFloatBigNum(QCBOREncodeContext *pCtx,
3190 UsefulBufC Mantissa,
3191 bool bIsNegative,
3192 int64_t nBase2Exponent)
3193{
3194 QCBOREncode_AddExponentAndMantissa(pCtx, CBOR_TAG_BIGFLOAT, Mantissa, bIsNegative, 0, nBase2Exponent);
3195}
3196
3197static inline void QCBOREncode_AddBigFloatBigNumToMap(QCBOREncodeContext *pCtx,
3198 const char *szLabel,
3199 UsefulBufC Mantissa,
3200 bool bIsNegative,
3201 int64_t nBase2Exponent)
3202{
3203 QCBOREncode_AddSZString(pCtx, szLabel);
3204 QCBOREncode_AddBigFloatBigNum(pCtx, Mantissa, bIsNegative, nBase2Exponent);
3205}
3206
3207static inline void QCBOREncode_AddBigFloatBigNumToMapN(QCBOREncodeContext *pCtx,
3208 int64_t nLabel,
3209 UsefulBufC Mantissa,
3210 bool bIsNegative,
3211 int64_t nBase2Exponent)
3212{
3213 QCBOREncode_AddInt64(pCtx, nLabel);
3214 QCBOREncode_AddBigFloatBigNum(pCtx, Mantissa, bIsNegative, nBase2Exponent);
3215}
3216#endif /* QCBOR_CONFIG_DISABLE_EXP_AND_MANTISSA */
3217
3218
3219static inline void QCBOREncode_AddURI(QCBOREncodeContext *pCtx, UsefulBufC URI)
3220{
3221 QCBOREncode_AddTag(pCtx, CBOR_TAG_URI);
3222 QCBOREncode_AddText(pCtx, URI);
3223}
3224
3225static inline void QCBOREncode_AddURIToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC URI)
3226{
3227 QCBOREncode_AddSZString(pCtx, szLabel);
3228 QCBOREncode_AddTag(pCtx, CBOR_TAG_URI);
3229 QCBOREncode_AddText(pCtx, URI);
3230}
3231
3232static inline void QCBOREncode_AddURIToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC URI)
3233{
3234 QCBOREncode_AddInt64(pCtx, nLabel);
3235 QCBOREncode_AddTag(pCtx, CBOR_TAG_URI);
3236 QCBOREncode_AddText(pCtx, URI);
3237}
3238
3239
3240
3241static inline void QCBOREncode_AddB64Text(QCBOREncodeContext *pCtx, UsefulBufC B64Text)
3242{
3243 QCBOREncode_AddTag(pCtx, CBOR_TAG_B64);
3244 QCBOREncode_AddText(pCtx, B64Text);
3245}
3246
3247static inline void QCBOREncode_AddB64TextToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC B64Text)
3248{
3249 QCBOREncode_AddSZString(pCtx, szLabel);
3250 QCBOREncode_AddTag(pCtx, CBOR_TAG_B64);
3251 QCBOREncode_AddText(pCtx, B64Text);
3252}
3253
3254static inline void QCBOREncode_AddB64TextToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC B64Text)
3255{
3256 QCBOREncode_AddInt64(pCtx, nLabel);
3257 QCBOREncode_AddTag(pCtx, CBOR_TAG_B64);
3258 QCBOREncode_AddText(pCtx, B64Text);
3259}
3260
3261
3262static inline void QCBOREncode_AddB64URLText(QCBOREncodeContext *pCtx, UsefulBufC B64Text)
3263{
3264 QCBOREncode_AddTag(pCtx, CBOR_TAG_B64URL);
3265 QCBOREncode_AddText(pCtx, B64Text);
3266}
3267
3268static inline void QCBOREncode_AddB64URLTextToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC B64Text)
3269{
3270 QCBOREncode_AddSZString(pCtx, szLabel);
3271 QCBOREncode_AddTag(pCtx, CBOR_TAG_B64URL);
3272 QCBOREncode_AddText(pCtx, B64Text);
3273}
3274
3275static inline void QCBOREncode_AddB64URLTextToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC B64Text)
3276{
3277 QCBOREncode_AddInt64(pCtx, nLabel);
3278 QCBOREncode_AddTag(pCtx, CBOR_TAG_B64URL);
3279 QCBOREncode_AddText(pCtx, B64Text);
3280}
3281
3282
3283static inline void QCBOREncode_AddRegex(QCBOREncodeContext *pCtx, UsefulBufC Bytes)
3284{
3285 QCBOREncode_AddTag(pCtx, CBOR_TAG_REGEX);
3286 QCBOREncode_AddText(pCtx, Bytes);
3287}
3288
3289static inline void QCBOREncode_AddRegexToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Bytes)
3290{
3291 QCBOREncode_AddSZString(pCtx, szLabel);
3292 QCBOREncode_AddTag(pCtx, CBOR_TAG_REGEX);
3293 QCBOREncode_AddText(pCtx, Bytes);
3294}
3295
3296static inline void QCBOREncode_AddRegexToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Bytes)
3297{
3298 QCBOREncode_AddInt64(pCtx, nLabel);
3299 QCBOREncode_AddTag(pCtx, CBOR_TAG_REGEX);
3300 QCBOREncode_AddText(pCtx, Bytes);
3301}
3302
3303
3304static inline void QCBOREncode_AddMIMEData(QCBOREncodeContext *pCtx, UsefulBufC MIMEData)
3305{
3306 QCBOREncode_AddTag(pCtx, CBOR_TAG_MIME);
3307 QCBOREncode_AddText(pCtx, MIMEData);
3308}
3309
3310static inline void QCBOREncode_AddMIMEDataToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC MIMEData)
3311{
3312 QCBOREncode_AddSZString(pCtx, szLabel);
3313 QCBOREncode_AddTag(pCtx, CBOR_TAG_MIME);
3314 QCBOREncode_AddText(pCtx, MIMEData);
3315}
3316
3317static inline void QCBOREncode_AddMIMEDataToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC MIMEData)
3318{
3319 QCBOREncode_AddInt64(pCtx, nLabel);
3320 QCBOREncode_AddTag(pCtx, CBOR_TAG_MIME);
3321 QCBOREncode_AddText(pCtx, MIMEData);
3322}
3323
3324
3325static inline void QCBOREncode_AddDateString(QCBOREncodeContext *pCtx, const char *szDate)
3326{
3327 QCBOREncode_AddTag(pCtx, CBOR_TAG_DATE_STRING);
3328 QCBOREncode_AddSZString(pCtx, szDate);
3329}
3330
3331static inline void QCBOREncode_AddDateStringToMap(QCBOREncodeContext *pCtx, const char *szLabel, const char *szDate)
3332{
3333 QCBOREncode_AddSZString(pCtx, szLabel);
3334 QCBOREncode_AddTag(pCtx, CBOR_TAG_DATE_STRING);
3335 QCBOREncode_AddSZString(pCtx, szDate);
3336}
3337
3338static inline void QCBOREncode_AddDateStringToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, const char *szDate)
3339{
3340 QCBOREncode_AddInt64(pCtx, nLabel);
3341 QCBOREncode_AddTag(pCtx, CBOR_TAG_DATE_STRING);
3342 QCBOREncode_AddSZString(pCtx, szDate);
3343}
3344
3345
3346static inline void QCBOREncode_AddSimple(QCBOREncodeContext *pCtx, uint64_t uNum)
3347{
3348 QCBOREncode_AddType7(pCtx, 0, uNum);
3349}
3350
3351static inline void QCBOREncode_AddSimpleToMap(QCBOREncodeContext *pCtx, const char *szLabel, uint8_t uSimple)
3352{
3353 QCBOREncode_AddSZString(pCtx, szLabel);
3354 QCBOREncode_AddSimple(pCtx, uSimple);
3355}
3356
3357static inline void QCBOREncode_AddSimpleToMapN(QCBOREncodeContext *pCtx, int nLabel, uint8_t uSimple)
3358{
3359 QCBOREncode_AddInt64(pCtx, nLabel);
3360 QCBOREncode_AddSimple(pCtx, uSimple);
3361}
3362
3363
3364static inline void QCBOREncode_AddBool(QCBOREncodeContext *pCtx, bool b)
3365{
3366 uint8_t uSimple = CBOR_SIMPLEV_FALSE;
3367 if(b) {
3368 uSimple = CBOR_SIMPLEV_TRUE;
3369 }
3370 QCBOREncode_AddSimple(pCtx, uSimple);
3371}
3372
3373static inline void QCBOREncode_AddBoolToMap(QCBOREncodeContext *pCtx, const char *szLabel, bool b)
3374{
3375 QCBOREncode_AddSZString(pCtx, szLabel);
3376 QCBOREncode_AddBool(pCtx, b);
3377}
3378
3379static inline void QCBOREncode_AddBoolToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, bool b)
3380{
3381 QCBOREncode_AddInt64(pCtx, nLabel);
3382 QCBOREncode_AddBool(pCtx, b);
3383}
3384
3385
3386static inline void QCBOREncode_AddNULL(QCBOREncodeContext *pCtx)
3387{
3388 QCBOREncode_AddSimple(pCtx, CBOR_SIMPLEV_NULL);
3389}
3390
3391static inline void QCBOREncode_AddNULLToMap(QCBOREncodeContext *pCtx, const char *szLabel)
3392{
3393 QCBOREncode_AddSZString(pCtx, szLabel);
3394 QCBOREncode_AddNULL(pCtx);
3395}
3396
3397static inline void QCBOREncode_AddNULLToMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3398{
3399 QCBOREncode_AddInt64(pCtx, nLabel);
3400 QCBOREncode_AddNULL(pCtx);
3401}
3402
3403
3404static inline void QCBOREncode_AddUndef(QCBOREncodeContext *pCtx)
3405{
3406 QCBOREncode_AddSimple(pCtx, CBOR_SIMPLEV_UNDEF);
3407}
3408
3409static inline void QCBOREncode_AddUndefToMap(QCBOREncodeContext *pCtx, const char *szLabel)
3410{
3411 QCBOREncode_AddSZString(pCtx, szLabel);
3412 QCBOREncode_AddUndef(pCtx);
3413}
3414
3415static inline void QCBOREncode_AddUndefToMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3416{
3417 QCBOREncode_AddInt64(pCtx, nLabel);
3418 QCBOREncode_AddUndef(pCtx);
3419}
3420
3421
3422static inline void QCBOREncode_OpenArray(QCBOREncodeContext *pCtx)
3423{
3424 QCBOREncode_OpenMapOrArray(pCtx, CBOR_MAJOR_TYPE_ARRAY);
3425}
3426
3427static inline void QCBOREncode_OpenArrayInMap(QCBOREncodeContext *pCtx, const char *szLabel)
3428{
3429 QCBOREncode_AddSZString(pCtx, szLabel);
3430 QCBOREncode_OpenArray(pCtx);
3431}
3432
3433static inline void QCBOREncode_OpenArrayInMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3434{
3435 QCBOREncode_AddInt64(pCtx, nLabel);
3436 QCBOREncode_OpenArray(pCtx);
3437}
3438
3439static inline void QCBOREncode_CloseArray(QCBOREncodeContext *pCtx)
3440{
3441 QCBOREncode_CloseMapOrArray(pCtx, CBOR_MAJOR_TYPE_ARRAY);
3442}
3443
3444
3445static inline void QCBOREncode_OpenMap(QCBOREncodeContext *pCtx)
3446{
3447 QCBOREncode_OpenMapOrArray(pCtx, CBOR_MAJOR_TYPE_MAP);
3448}
3449
3450static inline void QCBOREncode_OpenMapInMap(QCBOREncodeContext *pCtx, const char *szLabel)
3451{
3452 QCBOREncode_AddSZString(pCtx, szLabel);
3453 QCBOREncode_OpenMap(pCtx);
3454}
3455
3456static inline void QCBOREncode_OpenMapInMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3457{
3458 QCBOREncode_AddInt64(pCtx, nLabel);
3459 QCBOREncode_OpenMap(pCtx);
3460}
3461
3462static inline void QCBOREncode_CloseMap(QCBOREncodeContext *pCtx)
3463{
3464 QCBOREncode_CloseMapOrArray(pCtx, CBOR_MAJOR_TYPE_MAP);
3465}
3466
3467static inline void QCBOREncode_OpenArrayIndefiniteLength(QCBOREncodeContext *pCtx)
3468{
3469 QCBOREncode_OpenMapOrArrayIndefiniteLength(pCtx, CBOR_MAJOR_NONE_TYPE_ARRAY_INDEFINITE_LEN);
3470}
3471
3472static inline void QCBOREncode_OpenArrayIndefiniteLengthInMap(QCBOREncodeContext *pCtx, const char *szLabel)
3473{
3474 QCBOREncode_AddSZString(pCtx, szLabel);
3475 QCBOREncode_OpenArrayIndefiniteLength(pCtx);
3476}
3477
3478static inline void QCBOREncode_OpenArrayIndefiniteLengthInMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3479{
3480 QCBOREncode_AddInt64(pCtx, nLabel);
3481 QCBOREncode_OpenArrayIndefiniteLength(pCtx);
3482}
3483
3484static inline void QCBOREncode_CloseArrayIndefiniteLength(QCBOREncodeContext *pCtx)
3485{
3486 QCBOREncode_CloseMapOrArrayIndefiniteLength(pCtx, CBOR_MAJOR_NONE_TYPE_ARRAY_INDEFINITE_LEN);
3487}
3488
3489
3490static inline void QCBOREncode_OpenMapIndefiniteLength(QCBOREncodeContext *pCtx)
3491{
3492 QCBOREncode_OpenMapOrArrayIndefiniteLength(pCtx, CBOR_MAJOR_NONE_TYPE_MAP_INDEFINITE_LEN);
3493}
3494
3495static inline void QCBOREncode_OpenMapIndefiniteLengthInMap(QCBOREncodeContext *pCtx, const char *szLabel)
3496{
3497 QCBOREncode_AddSZString(pCtx, szLabel);
3498 QCBOREncode_OpenMapIndefiniteLength(pCtx);
3499}
3500
3501static inline void QCBOREncode_OpenMapIndefiniteLengthInMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3502{
3503 QCBOREncode_AddInt64(pCtx, nLabel);
3504 QCBOREncode_OpenMapIndefiniteLength(pCtx);
3505}
3506
3507static inline void QCBOREncode_CloseMapIndefiniteLength(QCBOREncodeContext *pCtx)
3508{
3509 QCBOREncode_CloseMapOrArrayIndefiniteLength(pCtx, CBOR_MAJOR_NONE_TYPE_MAP_INDEFINITE_LEN);
3510}
3511
3512
3513static inline void QCBOREncode_BstrWrap(QCBOREncodeContext *pCtx)
3514{
3515 QCBOREncode_OpenMapOrArray(pCtx, CBOR_MAJOR_TYPE_BYTE_STRING);
3516}
3517
3518static inline void QCBOREncode_BstrWrapInMap(QCBOREncodeContext *pCtx, const char *szLabel)
3519{
3520 QCBOREncode_AddSZString(pCtx, szLabel);
3521 QCBOREncode_BstrWrap(pCtx);
3522}
3523
3524static inline void QCBOREncode_BstrWrapInMapN(QCBOREncodeContext *pCtx, int64_t nLabel)
3525{
3526 QCBOREncode_AddInt64(pCtx, nLabel);
3527 QCBOREncode_BstrWrap(pCtx);
3528}
3529
3530static inline void QCBOREncode_CloseBstrWrap(QCBOREncodeContext *pCtx, UsefulBufC *pWrappedCBOR)
3531{
3532 QCBOREncode_CloseBstrWrap2(pCtx, true, pWrappedCBOR);
3533}
3534
3535
3536static inline void QCBOREncode_AddEncoded(QCBOREncodeContext *pCtx, UsefulBufC Encoded)
3537{
3538 QCBOREncode_AddBuffer(pCtx, CBOR_MAJOR_NONE_TYPE_RAW, Encoded);
3539}
3540
3541static inline void QCBOREncode_AddEncodedToMap(QCBOREncodeContext *pCtx, const char *szLabel, UsefulBufC Encoded)
3542{
3543 QCBOREncode_AddSZString(pCtx, szLabel);
3544 QCBOREncode_AddEncoded(pCtx, Encoded);
3545}
3546
3547static inline void QCBOREncode_AddEncodedToMapN(QCBOREncodeContext *pCtx, int64_t nLabel, UsefulBufC Encoded)
3548{
3549 QCBOREncode_AddInt64(pCtx, nLabel);
3550 QCBOREncode_AddEncoded(pCtx, Encoded);
3551}
3552
3553
3554static inline int QCBOREncode_IsBufferNULL(QCBOREncodeContext *pCtx)
3555{
3556 return UsefulOutBuf_IsBufferNULL(&(pCtx->OutBuf));
3557}
3558
3559static inline QCBORError QCBOREncode_GetErrorState(QCBOREncodeContext *pCtx)
3560{
3561 if(UsefulOutBuf_GetError(&(pCtx->OutBuf))) {
3562 // Items didn't fit in the buffer.
3563 // This check catches this condition for all the appends and inserts
3564 // so checks aren't needed when the appends and inserts are performed.
3565 // And of course UsefulBuf will never overrun the input buffer given
3566 // to it. No complex analysis of the error handling in this file is
3567 // needed to know that is true. Just read the UsefulBuf code.
3568 pCtx->uError = QCBOR_ERR_BUFFER_TOO_SMALL;
3569 // QCBOR_ERR_BUFFER_TOO_SMALL masks other errors, but that is
3570 // OK. Once the caller fixes this, they'll be unmasked.
3571 }
3572
3573 return (QCBORError)pCtx->uError;
3574}
3575
3576
3577/* ===========================================================================
3578 END OF PRIVATE INLINE IMPLEMENTATION
3579
3580 =========================================================================== */
3581
3582#ifdef __cplusplus
3583}
3584#endif
3585
3586#endif /* defined(__QCBOR__qcbor__) */