QCBOR: Add CBOR encoder / decoder library
QCBOR supports encoding and decoding of most
of the CBOR standard, RFC 7049. QCBOR is open
source maintained at
https://github.com/laurencelundblade/QCBOR
Change-Id: I5632379e4a1fdb16e0df7f03dfa2374160b7ed7f
Signed-off-by: Laurence Lundblade <lgl@securitytheory.com>
diff --git a/lib/ext/qcbor/src/UsefulBuf.c b/lib/ext/qcbor/src/UsefulBuf.c
new file mode 100644
index 0000000..5a7d37b
--- /dev/null
+++ b/lib/ext/qcbor/src/UsefulBuf.c
@@ -0,0 +1,329 @@
+/*==============================================================================
+ Copyright (c) 2016-2018, The Linux Foundation.
+ Copyright (c) 2018-2019, Laurence Lundblade.
+ All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of The Linux Foundation nor the names of its
+ contributors, nor the name "Laurence Lundblade" may be used to
+ endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ==============================================================================*/
+
+/*===================================================================================
+ FILE: UsefulBuf.c
+
+ DESCRIPTION: General purpose input and output buffers
+
+ EDIT HISTORY FOR FILE:
+
+ This section contains comments describing changes made to the module.
+ Notice that changes are listed in reverse chronological order.
+
+ when who what, where, why
+ -------- ---- ---------------------------------------------------
+ 09/07/17 llundbla Fix critical bug in UsefulBuf_Find() -- a read off
+ the end of memory when the bytes to find is longer
+ than the bytes to search.
+ 06/27/17 llundbla Fix UsefulBuf_Compare() bug. Only affected comparison
+ for < or > for unequal length buffers. Added
+ UsefulBuf_Set() function.
+ 05/30/17 llundbla Functions for NULL UsefulBufs and const / unconst
+ 11/13/16 llundbla Initial Version.
+
+ =====================================================================================*/
+
+#include "UsefulBuf.h"
+
+#define USEFUL_OUT_BUF_MAGIC (0x0B0F) // used to catch use of uninitialized or corrupted UOBs
+
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+UsefulBufC UsefulBuf_CopyOffset(UsefulBuf Dest, size_t uOffset, const UsefulBufC Src)
+{
+ // Do this with subtraction so it doesn't give erroneous result if uOffset + Src.len overflows
+ if(uOffset > Dest.len || Src.len > Dest.len - uOffset) { // uOffset + Src.len > Dest.len
+ return NULLUsefulBufC;
+ }
+
+ memcpy((uint8_t *)Dest.ptr + uOffset, Src.ptr, Src.len);
+
+ return (UsefulBufC){Dest.ptr, Src.len + uOffset};
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+int UsefulBuf_Compare(const UsefulBufC UB1, const UsefulBufC UB2)
+{
+ // use the comparisons rather than subtracting lengths to
+ // return an int instead of a size_t
+ if(UB1.len < UB2.len) {
+ return -1;
+ } else if (UB1.len > UB2.len) {
+ return 1;
+ } // else UB1.len == UB2.len
+
+ return memcmp(UB1.ptr, UB2.ptr, UB1.len);
+}
+
+
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+size_t UsefulBuf_FindBytes(UsefulBufC BytesToSearch, UsefulBufC BytesToFind)
+{
+ if(BytesToSearch.len < BytesToFind.len) {
+ return SIZE_MAX;
+ }
+
+ for(size_t uPos = 0; uPos <= BytesToSearch.len - BytesToFind.len; uPos++) {
+ if(!UsefulBuf_Compare((UsefulBufC){((uint8_t *)BytesToSearch.ptr) + uPos, BytesToFind.len}, BytesToFind)) {
+ return uPos;
+ }
+ }
+
+ return SIZE_MAX;
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+ */
+void UsefulOutBuf_Init(UsefulOutBuf *me, UsefulBuf Storage)
+{
+ me->magic = USEFUL_OUT_BUF_MAGIC;
+ UsefulOutBuf_Reset(me);
+ me->UB = Storage;
+
+#if 0
+ // This check is off by default.
+
+ // The following check fails on ThreadX
+
+ // Sanity check on the pointer and size to be sure we are not
+ // passed a buffer that goes off the end of the address space.
+ // Given this test, we know that all unsigned lengths less than
+ // me->size are valid and won't wrap in any pointer additions
+ // based off of pStorage in the rest of this code.
+ const uintptr_t ptrM = UINTPTR_MAX - Storage.len;
+ if(Storage.ptr && (uintptr_t)Storage.ptr > ptrM) // Check #0
+ me->err = 1;
+#endif
+}
+
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ The core of UsefulOutBuf -- put some bytes in the buffer without writing off the end of it.
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+
+ This function inserts the source buffer, NewData, into the destination buffer, me->UB.ptr.
+
+ Destination is represented as:
+ me->UB.ptr -- start of the buffer
+ me->UB.len -- size of the buffer UB.ptr
+ me->data_len -- length of value data in UB
+
+ Source is data:
+ NewData.ptr -- start of source buffer
+ NewData.len -- length of source buffer
+
+ Insertion point:
+ uInsertionPos.
+
+ Steps:
+
+ 0. Corruption checks on UsefulOutBuf
+
+ 1. Figure out if the new data will fit or not
+
+ 2. Is insertion position in the range of valid data?
+
+ 3. If insertion point is not at the end, slide data to the right of the insertion point to the right
+
+ 4. Put the new data in at the insertion position.
+
+ */
+void UsefulOutBuf_InsertUsefulBuf(UsefulOutBuf *me, UsefulBufC NewData, size_t uInsertionPos)
+{
+ if(me->err) {
+ // Already in error state.
+ return;
+ }
+
+ /* 0. Sanity check the UsefulOutBuf structure */
+ // A "counter measure". If magic number is not the right number it
+ // probably means me was not initialized or it was corrupted. Attackers
+ // can defeat this, but it is a hurdle and does good with very
+ // little code.
+ if(me->magic != USEFUL_OUT_BUF_MAGIC) {
+ me->err = 1;
+ return; // Magic number is wrong due to uninitalization or corrption
+ }
+
+ // Make sure valid data is less than buffer size. This would only occur
+ // if there was corruption of me, but it is also part of the checks to
+ // be sure there is no pointer arithmatic under/overflow.
+ if(me->data_len > me->UB.len) { // Check #1
+ me->err = 1;
+ return; // Offset of valid data is off the end of the UsefulOutBuf due to uninitialization or corruption
+ }
+
+ /* 1. Will it fit? */
+ // WillItFit() is the same as: NewData.len <= (me->size - me->data_len)
+ // Check #1 makes sure subtraction in RoomLeft will not wrap around
+ if(! UsefulOutBuf_WillItFit(me, NewData.len)) { // Check #2
+ // The new data will not fit into the the buffer.
+ me->err = 1;
+ return;
+ }
+
+ /* 2. Check the Insertion Position */
+ // This, with Check #1, also confirms that uInsertionPos <= me->data_len
+ if(uInsertionPos > me->data_len) { // Check #3
+ // Off the end of the valid data in the buffer.
+ me->err = 1;
+ return;
+ }
+
+ /* 3. Slide existing data to the right */
+ uint8_t *pSourceOfMove = ((uint8_t *)me->UB.ptr) + uInsertionPos; // PtrMath #1
+ size_t uNumBytesToMove = me->data_len - uInsertionPos; // PtrMath #2
+ uint8_t *pDestinationOfMove = pSourceOfMove + NewData.len; // PtrMath #3
+
+ if(uNumBytesToMove && me->UB.ptr) {
+ // To know memmove won't go off end of destination, see PtrMath #4
+ memmove(pDestinationOfMove, pSourceOfMove, uNumBytesToMove);
+ }
+
+ /* 4. Put the new data in */
+ uint8_t *pInsertionPoint = ((uint8_t *)me->UB.ptr) + uInsertionPos; // PtrMath #5
+ if(me->UB.ptr) {
+ // To know memmove won't go off end of destination, see PtrMath #6
+ memmove(pInsertionPoint, NewData.ptr, NewData.len);
+ }
+ me->data_len += NewData.len ;
+}
+
+
+/*
+ Rationale that describes why the above pointer math is safe
+
+ PtrMath #1 will never wrap around over because
+ Check #0 in UsefulOutBuf_Init makes sure me->UB.ptr + me->UB.len doesn't wrap
+ Check #1 makes sure me->data_len is less than me->UB.len
+ Check #3 makes sure uInsertionPos is less than me->data_len
+
+ PtrMath #2 will never wrap around under because
+ Check #3 makes sure uInsertionPos is less than me->data_len
+
+ PtrMath #3 will never wrap around over because todo
+ PtrMath #1 is checked resulting in pSourceOfMove being between me->UB.ptr and a maximum valid ptr
+ Check #2 that NewData.len will fit
+
+ PtrMath #4 will never wrap under because
+ Calculation for extent or memmove is uRoomInDestination = me->UB.len - (uInsertionPos + NewData.len)
+ Check #3 makes sure uInsertionPos is less than me->data_len
+ Check #3 allows Check #2 to be refactored as NewData.Len > (me->size - uInsertionPos)
+ This algebraically rearranges to me->size > uInsertionPos + NewData.len
+
+ PtrMath #5 is exactly the same as PtrMath #1
+
+ PtrMath #6 will never wrap under because
+ Calculation for extent of memove is uRoomInDestination = me->UB.len - uInsertionPos;
+ Check #1 makes sure me->data_len is less than me->size
+ Check #3 makes sure uInsertionPos is less than me->data_len
+ */
+
+
+/*
+ Public function -- see UsefulBuf.h
+ */
+UsefulBufC UsefulOutBuf_OutUBuf(UsefulOutBuf *me)
+{
+ if(me->err) {
+ return NULLUsefulBufC;
+ }
+
+ if(me->magic != USEFUL_OUT_BUF_MAGIC) {
+ me->err = 1;
+ return NULLUsefulBufC;
+ }
+
+ return (UsefulBufC){me->UB.ptr,me->data_len};
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ Copy out the data accumulated in to the output buffer.
+ */
+UsefulBufC UsefulOutBuf_CopyOut(UsefulOutBuf *me, UsefulBuf pDest)
+{
+ const UsefulBufC Tmp = UsefulOutBuf_OutUBuf(me);
+ if(UsefulBuf_IsNULLC(Tmp)) {
+ return NULLUsefulBufC;
+ }
+ return UsefulBuf_Copy(pDest, Tmp);
+}
+
+
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ The core of UsefulInputBuf -- consume some bytes without going off the end of the buffer.
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+ */
+const void * UsefulInputBuf_GetBytes(UsefulInputBuf *me, size_t uAmount)
+{
+ // Already in error state. Do nothing.
+ if(me->err) {
+ return NULL;
+ }
+
+ if(!UsefulInputBuf_BytesAvailable(me, uAmount)) {
+ // The number of bytes asked for at current position are more than available
+ me->err = 1;
+ return NULL;
+ }
+
+ // This is going to succeed
+ const void * const result = ((uint8_t *)me->UB.ptr) + me->cursor;
+ me->cursor += uAmount; // this will not overflow because of check using UsefulInputBuf_BytesAvailable()
+ return result;
+}
+
diff --git a/lib/ext/qcbor/src/ieee754.c b/lib/ext/qcbor/src/ieee754.c
new file mode 100644
index 0000000..6fdfda8
--- /dev/null
+++ b/lib/ext/qcbor/src/ieee754.c
@@ -0,0 +1,497 @@
+/*==============================================================================
+ ieee754.c -- floating point conversion between half, double and single precision
+
+ Copyright (c) 2018-2019, Laurence Lundblade. All rights reserved.
+
+ SPDX-License-Identifier: BSD-3-Clause
+
+ See BSD-3-Clause license in README.md
+
+ Created on 7/23/18
+ ==============================================================================*/
+
+#include "ieee754.h"
+#include <string.h> // For memcpy()
+
+
+/*
+ This code is written for clarity and verifiability, not for size, on the assumption
+ that the optimizer will do a good job. The LLVM optimizer, -Os, does seem to do the
+ job and the resulting object code is smaller from combining code for the many different
+ cases (normal, subnormal, infinity, zero...) for the conversions.
+
+ Dead stripping is also really helpful to get code size down when floating point
+ encoding is not needed.
+
+ This code works solely using shifts and masks and thus has no dependency on
+ any math libraries. It can even work if the CPU doesn't have any floating
+ point support, though that isn't the most useful thing to do.
+
+ The memcpy() dependency is only for CopyFloatToUint32() and friends which only
+ is needed to avoid type punning when converting the actual float bits to
+ an unsigned value so the bit shifts and masks can work.
+ */
+
+/*
+ The references used to write this code:
+
+ - IEEE 754-2008, particularly section 3.6 and 6.2.1
+
+ - https://en.wikipedia.org/wiki/IEEE_754 and subordinate pages
+
+ - https://stackoverflow.com/questions/19800415/why-does-ieee-754-reserve-so-many-nan-values
+ */
+
+
+// ----- Half Precsion -----------
+#define HALF_NUM_SIGNIFICAND_BITS (10)
+#define HALF_NUM_EXPONENT_BITS (5)
+#define HALF_NUM_SIGN_BITS (1)
+
+#define HALF_SIGNIFICAND_SHIFT (0)
+#define HALF_EXPONENT_SHIFT (HALF_NUM_SIGNIFICAND_BITS)
+#define HALF_SIGN_SHIFT (HALF_NUM_SIGNIFICAND_BITS + HALF_NUM_EXPONENT_BITS)
+
+#define HALF_SIGNIFICAND_MASK (0x3ff) // The lower 10 bits // 0x03ff
+#define HALF_EXPONENT_MASK (0x1f << HALF_EXPONENT_SHIFT) // 0x7c00 5 bits of exponent
+#define HALF_SIGN_MASK (0x01 << HALF_SIGN_SHIFT) // // 0x80001 bit of sign
+#define HALF_QUIET_NAN_BIT (0x01 << (HALF_NUM_SIGNIFICAND_BITS-1)) // 0x0200
+
+/* Biased Biased Unbiased Use
+ 0x00 0 -15 0 and subnormal
+ 0x01 1 -14 Smallest normal exponent
+ 0x1e 30 15 Largest normal exponent
+ 0x1F 31 16 NaN and Infinity */
+#define HALF_EXPONENT_BIAS (15)
+#define HALF_EXPONENT_MAX (HALF_EXPONENT_BIAS) // 15 Unbiased
+#define HALF_EXPONENT_MIN (-HALF_EXPONENT_BIAS+1) // -14 Unbiased
+#define HALF_EXPONENT_ZERO (-HALF_EXPONENT_BIAS) // -15 Unbiased
+#define HALF_EXPONENT_INF_OR_NAN (HALF_EXPONENT_BIAS+1) // 16 Unbiased
+
+
+// ------ Single Precision --------
+#define SINGLE_NUM_SIGNIFICAND_BITS (23)
+#define SINGLE_NUM_EXPONENT_BITS (8)
+#define SINGLE_NUM_SIGN_BITS (1)
+
+#define SINGLE_SIGNIFICAND_SHIFT (0)
+#define SINGLE_EXPONENT_SHIFT (SINGLE_NUM_SIGNIFICAND_BITS)
+#define SINGLE_SIGN_SHIFT (SINGLE_NUM_SIGNIFICAND_BITS + SINGLE_NUM_EXPONENT_BITS)
+
+#define SINGLE_SIGNIFICAND_MASK (0x7fffffUL) // The lower 23 bits
+#define SINGLE_EXPONENT_MASK (0xffUL << SINGLE_EXPONENT_SHIFT) // 8 bits of exponent
+#define SINGLE_SIGN_MASK (0x01UL << SINGLE_SIGN_SHIFT) // 1 bit of sign
+#define SINGLE_QUIET_NAN_BIT (0x01UL << (SINGLE_NUM_SIGNIFICAND_BITS-1))
+
+/* Biased Biased Unbiased Use
+ 0x0000 0 -127 0 and subnormal
+ 0x0001 1 -126 Smallest normal exponent
+ 0x7f 127 0 1
+ 0xfe 254 127 Largest normal exponent
+ 0xff 255 128 NaN and Infinity */
+#define SINGLE_EXPONENT_BIAS (127)
+#define SINGLE_EXPONENT_MAX (SINGLE_EXPONENT_BIAS) // 127 unbiased
+#define SINGLE_EXPONENT_MIN (-SINGLE_EXPONENT_BIAS+1) // -126 unbiased
+#define SINGLE_EXPONENT_ZERO (-SINGLE_EXPONENT_BIAS) // -127 unbiased
+#define SINGLE_EXPONENT_INF_OR_NAN (SINGLE_EXPONENT_BIAS+1) // 128 unbiased
+
+
+// --------- Double Precision ----------
+#define DOUBLE_NUM_SIGNIFICAND_BITS (52)
+#define DOUBLE_NUM_EXPONENT_BITS (11)
+#define DOUBLE_NUM_SIGN_BITS (1)
+
+#define DOUBLE_SIGNIFICAND_SHIFT (0)
+#define DOUBLE_EXPONENT_SHIFT (DOUBLE_NUM_SIGNIFICAND_BITS)
+#define DOUBLE_SIGN_SHIFT (DOUBLE_NUM_SIGNIFICAND_BITS + DOUBLE_NUM_EXPONENT_BITS)
+
+#define DOUBLE_SIGNIFICAND_MASK (0xfffffffffffffULL) // The lower 52 bits
+#define DOUBLE_EXPONENT_MASK (0x7ffULL << DOUBLE_EXPONENT_SHIFT) // 11 bits of exponent
+#define DOUBLE_SIGN_MASK (0x01ULL << DOUBLE_SIGN_SHIFT) // 1 bit of sign
+#define DOUBLE_QUIET_NAN_BIT (0x01ULL << (DOUBLE_NUM_SIGNIFICAND_BITS-1))
+
+
+/* Biased Biased Unbiased Use
+ 0x00000000 0 -1023 0 and subnormal
+ 0x00000001 1 -1022 Smallest normal exponent
+ 0x000007fe 2046 1023 Largest normal exponent
+ 0x000007ff 2047 1024 NaN and Infinity */
+#define DOUBLE_EXPONENT_BIAS (1023)
+#define DOUBLE_EXPONENT_MAX (DOUBLE_EXPONENT_BIAS) // unbiased
+#define DOUBLE_EXPONENT_MIN (-DOUBLE_EXPONENT_BIAS+1) // unbiased
+#define DOUBLE_EXPONENT_ZERO (-DOUBLE_EXPONENT_BIAS) // unbiased
+#define DOUBLE_EXPONENT_INF_OR_NAN (DOUBLE_EXPONENT_BIAS+1) // unbiased
+
+
+
+/*
+ Convenient functions to avoid type punning, compiler warnings and such
+ The optimizer reduces them to a simple assignment.
+ This is a crusty corner of C. It shouldn't be this hard.
+
+ These are also in UsefulBuf.h under a different name. They are copied
+ here to avoid a dependency on UsefulBuf.h. There is no
+ object code size impact because these always optimze down to a
+ simple assignment.
+ */
+static inline uint32_t CopyFloatToUint32(float f)
+{
+ uint32_t u32;
+ memcpy(&u32, &f, sizeof(uint32_t));
+ return u32;
+}
+
+static inline uint64_t CopyDoubleToUint64(double d)
+{
+ uint64_t u64;
+ memcpy(&u64, &d, sizeof(uint64_t));
+ return u64;
+}
+
+static inline float CopyUint32ToFloat(uint32_t u32)
+{
+ float f;
+ memcpy(&f, &u32, sizeof(uint32_t));
+ return f;
+}
+
+static inline double CopyUint64ToDouble(uint64_t u64)
+{
+ double d;
+ memcpy(&d, &u64, sizeof(uint64_t));
+ return d;
+}
+
+
+// Public function; see ieee754.h
+uint16_t IEEE754_FloatToHalf(float f)
+{
+ // Pull the three parts out of the single-precision float
+ const uint32_t uSingle = CopyFloatToUint32(f);
+ const int32_t nSingleUnbiasedExponent = ((uSingle & SINGLE_EXPONENT_MASK) >> SINGLE_EXPONENT_SHIFT) - SINGLE_EXPONENT_BIAS;
+ const uint32_t uSingleSign = (uSingle & SINGLE_SIGN_MASK) >> SINGLE_SIGN_SHIFT;
+ const uint32_t uSingleSignificand = uSingle & SINGLE_SIGNIFICAND_MASK;
+
+
+ // Now convert the three parts to half-precision.
+ uint16_t uHalfSign, uHalfSignificand, uHalfBiasedExponent;
+ if(nSingleUnbiasedExponent == SINGLE_EXPONENT_INF_OR_NAN) {
+ // +/- Infinity and NaNs -- single biased exponent is 0xff
+ uHalfBiasedExponent = HALF_EXPONENT_INF_OR_NAN + HALF_EXPONENT_BIAS;
+ if(!uSingleSignificand) {
+ // Infinity
+ uHalfSignificand = 0;
+ } else {
+ // Copy the LBSs of the NaN payload that will fit from the single to the half
+ uHalfSignificand = uSingleSignificand & (HALF_SIGNIFICAND_MASK & ~HALF_QUIET_NAN_BIT);
+ if(uSingleSignificand & SINGLE_QUIET_NAN_BIT) {
+ // It's a qNaN; copy the qNaN bit
+ uHalfSignificand |= HALF_QUIET_NAN_BIT;
+ } else {
+ // It's a sNaN; make sure the significand is not zero so it stays a NaN
+ // This is needed because not all significand bits are copied from single
+ if(!uHalfSignificand) {
+ // Set the LSB. This is what wikipedia shows for sNAN.
+ uHalfSignificand |= 0x01;
+ }
+ }
+ }
+ } else if(nSingleUnbiasedExponent == SINGLE_EXPONENT_ZERO) {
+ // 0 or a subnormal number -- singled biased exponent is 0
+ uHalfBiasedExponent = 0;
+ uHalfSignificand = 0; // Any subnormal single will be too small to express as a half precision
+ } else if(nSingleUnbiasedExponent > HALF_EXPONENT_MAX) {
+ // Exponent is too large to express in half-precision; round up to infinity
+ uHalfBiasedExponent = HALF_EXPONENT_INF_OR_NAN + HALF_EXPONENT_BIAS;
+ uHalfSignificand = 0;
+ } else if(nSingleUnbiasedExponent < HALF_EXPONENT_MIN) {
+ // Exponent is too small to express in half-precision normal; make it a half-precision subnormal
+ uHalfBiasedExponent = (uint16_t)(HALF_EXPONENT_ZERO + HALF_EXPONENT_BIAS);
+ // Difference between single normal exponent and the base exponent of a half subnormal
+ const uint32_t nExpDiff = -(nSingleUnbiasedExponent - HALF_EXPONENT_MIN);
+ // Also have to shift the significand by the difference in number of bits between a single and a half significand
+ const int32_t nSignificandBitsDiff = SINGLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS;
+ // Add in the 1 that is implied in the significand of a normal number; it needs to be present in a subnormal
+ const uint32_t uSingleSignificandSubnormal = uSingleSignificand + (0x01L << SINGLE_NUM_SIGNIFICAND_BITS);
+ uHalfSignificand = uSingleSignificandSubnormal >> (nExpDiff + nSignificandBitsDiff);
+ } else {
+ // The normal case
+ uHalfBiasedExponent = nSingleUnbiasedExponent + HALF_EXPONENT_BIAS;
+ uHalfSignificand = uSingleSignificand >> (SINGLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS);
+ }
+ uHalfSign = uSingleSign;
+
+ // Put the 3 values in the right place for a half precision
+ const uint16_t uHalfPrecision = uHalfSignificand |
+ (uHalfBiasedExponent << HALF_EXPONENT_SHIFT) |
+ (uHalfSign << HALF_SIGN_SHIFT);
+ return uHalfPrecision;
+}
+
+
+// Public function; see ieee754.h
+uint16_t IEEE754_DoubleToHalf(double d)
+{
+ // Pull the three parts out of the double-precision float
+ const uint64_t uDouble = CopyDoubleToUint64(d);
+ const int64_t nDoubleUnbiasedExponent = ((uDouble & DOUBLE_EXPONENT_MASK) >> DOUBLE_EXPONENT_SHIFT) - DOUBLE_EXPONENT_BIAS;
+ const uint64_t uDoubleSign = (uDouble & DOUBLE_SIGN_MASK) >> DOUBLE_SIGN_SHIFT;
+ const uint64_t uDoubleSignificand = uDouble & DOUBLE_SIGNIFICAND_MASK;
+
+
+ // Now convert the three parts to half-precision.
+ uint16_t uHalfSign, uHalfSignificand, uHalfBiasedExponent;
+ if(nDoubleUnbiasedExponent == DOUBLE_EXPONENT_INF_OR_NAN) {
+ // +/- Infinity and NaNs -- single biased exponent is 0xff
+ uHalfBiasedExponent = HALF_EXPONENT_INF_OR_NAN + HALF_EXPONENT_BIAS;
+ if(!uDoubleSignificand) {
+ // Infinity
+ uHalfSignificand = 0;
+ } else {
+ // Copy the LBSs of the NaN payload that will fit from the double to the half
+ uHalfSignificand = uDoubleSignificand & (HALF_SIGNIFICAND_MASK & ~HALF_QUIET_NAN_BIT);
+ if(uDoubleSignificand & DOUBLE_QUIET_NAN_BIT) {
+ // It's a qNaN; copy the qNaN bit
+ uHalfSignificand |= HALF_QUIET_NAN_BIT;
+ } else {
+ // It's an sNaN; make sure the significand is not zero so it stays a NaN
+ // This is needed because not all significand bits are copied from single
+ if(!uHalfSignificand) {
+ // Set the LSB. This is what wikipedia shows for sNAN.
+ uHalfSignificand |= 0x01;
+ }
+ }
+ }
+ } else if(nDoubleUnbiasedExponent == DOUBLE_EXPONENT_ZERO) {
+ // 0 or a subnormal number -- double biased exponent is 0
+ uHalfBiasedExponent = 0;
+ uHalfSignificand = 0; // Any subnormal single will be too small to express as a half precision; TODO, is this really true?
+ } else if(nDoubleUnbiasedExponent > HALF_EXPONENT_MAX) {
+ // Exponent is too large to express in half-precision; round up to infinity; TODO, is this really true?
+ uHalfBiasedExponent = HALF_EXPONENT_INF_OR_NAN + HALF_EXPONENT_BIAS;
+ uHalfSignificand = 0;
+ } else if(nDoubleUnbiasedExponent < HALF_EXPONENT_MIN) {
+ // Exponent is too small to express in half-precision; round down to zero
+ uHalfBiasedExponent = (uint16_t)(HALF_EXPONENT_ZERO + HALF_EXPONENT_BIAS);
+ // Difference between double normal exponent and the base exponent of a half subnormal
+ const uint64_t nExpDiff = -(nDoubleUnbiasedExponent - HALF_EXPONENT_MIN);
+ // Also have to shift the significand by the difference in number of bits between a double and a half significand
+ const int64_t nSignificandBitsDiff = DOUBLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS;
+ // Add in the 1 that is implied in the significand of a normal number; it needs to be present in a subnormal
+ const uint64_t uDoubleSignificandSubnormal = uDoubleSignificand + (0x01ULL << DOUBLE_NUM_SIGNIFICAND_BITS);
+ uHalfSignificand = uDoubleSignificandSubnormal >> (nExpDiff + nSignificandBitsDiff);
+ } else {
+ // The normal case
+ uHalfBiasedExponent = nDoubleUnbiasedExponent + HALF_EXPONENT_BIAS;
+ uHalfSignificand = uDoubleSignificand >> (DOUBLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS);
+ }
+ uHalfSign = uDoubleSign;
+
+
+ // Put the 3 values in the right place for a half precision
+ const uint16_t uHalfPrecision = uHalfSignificand |
+ (uHalfBiasedExponent << HALF_EXPONENT_SHIFT) |
+ (uHalfSign << HALF_SIGN_SHIFT);
+ return uHalfPrecision;
+}
+
+
+// Public function; see ieee754.h
+float IEEE754_HalfToFloat(uint16_t uHalfPrecision)
+{
+ // Pull out the three parts of the half-precision float
+ const uint16_t uHalfSignificand = uHalfPrecision & HALF_SIGNIFICAND_MASK;
+ const int16_t nHalfUnBiasedExponent = ((uHalfPrecision & HALF_EXPONENT_MASK) >> HALF_EXPONENT_SHIFT) - HALF_EXPONENT_BIAS;
+ const uint16_t uHalfSign = (uHalfPrecision & HALF_SIGN_MASK) >> HALF_SIGN_SHIFT;
+
+
+ // Make the three parts of the single-precision number
+ uint32_t uSingleSignificand, uSingleSign, uSingleBiasedExponent;
+ if(nHalfUnBiasedExponent == HALF_EXPONENT_ZERO) {
+ // 0 or subnormal
+ if(uHalfSignificand) {
+ // Subnormal case
+ uSingleBiasedExponent = -HALF_EXPONENT_BIAS + SINGLE_EXPONENT_BIAS +1;
+ // A half-precision subnormal can always be converted to a normal single-precision float because the ranges line up
+ uSingleSignificand = uHalfSignificand;
+ // Shift bits from right of the decimal to left, reducing the exponent by 1 each time
+ do {
+ uSingleSignificand <<= 1;
+ uSingleBiasedExponent--;
+ } while ((uSingleSignificand & 0x400) == 0);
+ uSingleSignificand &= HALF_SIGNIFICAND_MASK;
+ uSingleSignificand <<= (SINGLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS);
+ } else {
+ // Just zero
+ uSingleBiasedExponent = SINGLE_EXPONENT_ZERO + SINGLE_EXPONENT_BIAS;
+ uSingleSignificand = 0;
+ }
+ } else if(nHalfUnBiasedExponent == HALF_EXPONENT_INF_OR_NAN) {
+ // NaN or Inifinity
+ uSingleBiasedExponent = SINGLE_EXPONENT_INF_OR_NAN + SINGLE_EXPONENT_BIAS;
+ if(uHalfSignificand) {
+ // NaN
+ // First preserve the NaN payload from half to single
+ uSingleSignificand = uHalfSignificand & ~HALF_QUIET_NAN_BIT;
+ if(uHalfSignificand & HALF_QUIET_NAN_BIT) {
+ // Next, set qNaN if needed since half qNaN bit is not copied above
+ uSingleSignificand |= SINGLE_QUIET_NAN_BIT;
+ }
+ } else {
+ // Infinity
+ uSingleSignificand = 0;
+ }
+ } else {
+ // Normal number
+ uSingleBiasedExponent = nHalfUnBiasedExponent + SINGLE_EXPONENT_BIAS;
+ uSingleSignificand = uHalfSignificand << (SINGLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS);
+ }
+ uSingleSign = uHalfSign;
+
+
+ // Shift the three parts of the single precision into place
+ const uint32_t uSinglePrecision = uSingleSignificand |
+ (uSingleBiasedExponent << SINGLE_EXPONENT_SHIFT) |
+ (uSingleSign << SINGLE_SIGN_SHIFT);
+
+ return CopyUint32ToFloat(uSinglePrecision);
+}
+
+
+// Public function; see ieee754.h
+double IEEE754_HalfToDouble(uint16_t uHalfPrecision)
+{
+ // Pull out the three parts of the half-precision float
+ const uint16_t uHalfSignificand = uHalfPrecision & HALF_SIGNIFICAND_MASK;
+ const int16_t nHalfUnBiasedExponent = ((uHalfPrecision & HALF_EXPONENT_MASK) >> HALF_EXPONENT_SHIFT) - HALF_EXPONENT_BIAS;
+ const uint16_t uHalfSign = (uHalfPrecision & HALF_SIGN_MASK) >> HALF_SIGN_SHIFT;
+
+
+ // Make the three parts of hte single-precision number
+ uint64_t uDoubleSignificand, uDoubleSign, uDoubleBiasedExponent;
+ if(nHalfUnBiasedExponent == HALF_EXPONENT_ZERO) {
+ // 0 or subnormal
+ uDoubleBiasedExponent = DOUBLE_EXPONENT_ZERO + DOUBLE_EXPONENT_BIAS;
+ if(uHalfSignificand) {
+ // Subnormal case
+ uDoubleBiasedExponent = -HALF_EXPONENT_BIAS + DOUBLE_EXPONENT_BIAS +1;
+ // A half-precision subnormal can always be converted to a normal double-precision float because the ranges line up
+ uDoubleSignificand = uHalfSignificand;
+ // Shift bits from right of the decimal to left, reducing the exponent by 1 each time
+ do {
+ uDoubleSignificand <<= 1;
+ uDoubleBiasedExponent--;
+ } while ((uDoubleSignificand & 0x400) == 0);
+ uDoubleSignificand &= HALF_SIGNIFICAND_MASK;
+ uDoubleSignificand <<= (DOUBLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS);
+ } else {
+ // Just zero
+ uDoubleSignificand = 0;
+ }
+ } else if(nHalfUnBiasedExponent == HALF_EXPONENT_INF_OR_NAN) {
+ // NaN or Inifinity
+ uDoubleBiasedExponent = DOUBLE_EXPONENT_INF_OR_NAN + DOUBLE_EXPONENT_BIAS;
+ if(uHalfSignificand) {
+ // NaN
+ // First preserve the NaN payload from half to single
+ uDoubleSignificand = uHalfSignificand & ~HALF_QUIET_NAN_BIT;
+ if(uHalfSignificand & HALF_QUIET_NAN_BIT) {
+ // Next, set qNaN if needed since half qNaN bit is not copied above
+ uDoubleSignificand |= DOUBLE_QUIET_NAN_BIT;
+ }
+ } else {
+ // Infinity
+ uDoubleSignificand = 0;
+ }
+ } else {
+ // Normal number
+ uDoubleBiasedExponent = nHalfUnBiasedExponent + DOUBLE_EXPONENT_BIAS;
+ uDoubleSignificand = (uint64_t)uHalfSignificand << (DOUBLE_NUM_SIGNIFICAND_BITS - HALF_NUM_SIGNIFICAND_BITS);
+ }
+ uDoubleSign = uHalfSign;
+
+
+ // Shift the 3 parts into place as a double-precision
+ const uint64_t uDouble = uDoubleSignificand |
+ (uDoubleBiasedExponent << DOUBLE_EXPONENT_SHIFT) |
+ (uDoubleSign << DOUBLE_SIGN_SHIFT);
+ return CopyUint64ToDouble(uDouble);
+}
+
+
+// Public function; see ieee754.h
+IEEE754_union IEEE754_FloatToSmallest(float f)
+{
+ IEEE754_union result;
+
+ // Pull the neeed two parts out of the single-precision float
+ const uint32_t uSingle = CopyFloatToUint32(f);
+ const int32_t nSingleExponent = ((uSingle & SINGLE_EXPONENT_MASK) >> SINGLE_EXPONENT_SHIFT) - SINGLE_EXPONENT_BIAS;
+ const uint32_t uSingleSignificand = uSingle & SINGLE_SIGNIFICAND_MASK;
+
+ // Bit mask that is the significand bits that would be lost when converting
+ // from single-precision to half-precision
+ const uint64_t uDroppedSingleBits = SINGLE_SIGNIFICAND_MASK >> HALF_NUM_SIGNIFICAND_BITS;
+
+ // Optimizer will re organize so there is only one call to IEEE754_FloatToHalf()
+ if(uSingle == 0) {
+ // Value is 0.0000, not a a subnormal
+ result.uSize = IEEE754_UNION_IS_HALF;
+ result.uValue = IEEE754_FloatToHalf(f);
+ } else if(nSingleExponent == SINGLE_EXPONENT_INF_OR_NAN) {
+ // NaN, +/- infinity
+ result.uSize = IEEE754_UNION_IS_HALF;
+ result.uValue = IEEE754_FloatToHalf(f);
+ } else if((nSingleExponent >= HALF_EXPONENT_MIN) && nSingleExponent <= HALF_EXPONENT_MAX && (!(uSingleSignificand & uDroppedSingleBits))) {
+ // Normal number in exponent range and precision won't be lost
+ result.uSize = IEEE754_UNION_IS_HALF;
+ result.uValue = IEEE754_FloatToHalf(f);
+ } else {
+ // Subnormal, exponent out of range, or precision will be lost
+ result.uSize = IEEE754_UNION_IS_SINGLE;
+ result.uValue = uSingle;
+ }
+
+ return result;
+}
+
+// Public function; see ieee754.h
+IEEE754_union IEEE754_DoubleToSmallestInternal(double d, int bAllowHalfPrecision)
+{
+ IEEE754_union result;
+
+ // Pull the needed two parts out of the double-precision float
+ const uint64_t uDouble = CopyDoubleToUint64(d);
+ const int64_t nDoubleExponent = ((uDouble & DOUBLE_EXPONENT_MASK) >> DOUBLE_EXPONENT_SHIFT) - DOUBLE_EXPONENT_BIAS;
+ const uint64_t uDoubleSignificand = uDouble & DOUBLE_SIGNIFICAND_MASK;
+
+ // Masks to check whether dropped significand bits are zero or not
+ const uint64_t uDroppedDoubleBits = DOUBLE_SIGNIFICAND_MASK >> HALF_NUM_SIGNIFICAND_BITS;
+ const uint64_t uDroppedSingleBits = DOUBLE_SIGNIFICAND_MASK >> SINGLE_NUM_SIGNIFICAND_BITS;
+
+ // The various cases
+ if(d == 0.0) { // Take care of positive and negative zero
+ // Value is 0.0000, not a a subnormal
+ result.uSize = IEEE754_UNION_IS_HALF;
+ result.uValue = IEEE754_DoubleToHalf(d);
+ } else if(nDoubleExponent == DOUBLE_EXPONENT_INF_OR_NAN) {
+ // NaN, +/- infinity
+ result.uSize = IEEE754_UNION_IS_HALF;
+ result.uValue = IEEE754_DoubleToHalf(d);
+ } else if(bAllowHalfPrecision && (nDoubleExponent >= HALF_EXPONENT_MIN) && nDoubleExponent <= HALF_EXPONENT_MAX && (!(uDoubleSignificand & uDroppedDoubleBits))) {
+ // Can convert to half without precision loss
+ result.uSize = IEEE754_UNION_IS_HALF;
+ result.uValue = IEEE754_DoubleToHalf(d);
+ } else if((nDoubleExponent >= SINGLE_EXPONENT_MIN) && nDoubleExponent <= SINGLE_EXPONENT_MAX && (!(uDoubleSignificand & uDroppedSingleBits))) {
+ // Can convert to single without precision loss
+ result.uSize = IEEE754_UNION_IS_SINGLE;
+ result.uValue = CopyFloatToUint32((float)d);
+ } else {
+ // Can't convert without precision loss
+ result.uSize = IEEE754_UNION_IS_DOUBLE;
+ result.uValue = uDouble;
+ }
+
+ return result;
+}
+
diff --git a/lib/ext/qcbor/src/ieee754.h b/lib/ext/qcbor/src/ieee754.h
new file mode 100644
index 0000000..2530f98
--- /dev/null
+++ b/lib/ext/qcbor/src/ieee754.h
@@ -0,0 +1,168 @@
+/*==============================================================================
+ ieee754.c -- floating point conversion between half, double and single precision
+
+ Copyright (c) 2018-2019, Laurence Lundblade. All rights reserved.
+
+ SPDX-License-Identifier: BSD-3-Clause
+
+ See BSD-3-Clause license in README.md
+
+ Created on 7/23/18
+ ==============================================================================*/
+
+#ifndef ieee754_h
+#define ieee754_h
+
+#include <stdint.h>
+
+
+
+/*
+ General comments
+
+ This is a complete in that it handles all conversion cases
+ including +/- infinity, +/- zero, subnormal numbers, qNaN, sNaN
+ and NaN payloads.
+
+ This confirms to IEEE 754-2008, but note that this doesn't
+ specify conversions, just the encodings.
+
+ NaN payloads are preserved with alignment on the LSB. The
+ qNaN bit is handled differently and explicity copied. It
+ is always the MSB of the significand. The NaN payload MSBs
+ (except the qNaN bit) are truncated when going from
+ double or single to half.
+
+ TODO: what does the C cast do with NaN payloads from
+ double to single?
+
+
+
+ */
+
+/*
+ Most simply just explicilty encode the type you want, single or double.
+ This works easily everywhere since standard C supports both
+ these types and so does qcbor. This encoder also supports
+ half precision and there's a few ways to use it to encode
+ floating point numbers in less space.
+
+ Without losing precision, you can encode a single or double
+ such that the special values of 0, NaN and Infinity encode
+ as half-precision. This CBOR decodoer and most others
+ should handle this properly.
+
+ If you don't mind losing precision, then you can use half-precision.
+ One way to do this is to set up your environment to use
+ ___fp_16. Some compilers and CPUs support it even though it is not
+ standard C. What is nice about this is that your program
+ will use less memory and floating point operations like
+ multiplying, adding and such will be faster.
+
+ Another way to make use of half-precision is to represent
+ the values in your program as single or double, but encode
+ them in CBOR as half-precision. This cuts the size
+ of the encoded messages by 2 or 4, but doesn't reduce
+ memory needs or speed because you are still using
+ single or double in your code.
+
+
+ encode:
+ - float as float
+ - double as double
+ - half as half
+ - float as half_precision, for environments that don't support a half-precision type
+ - double as half_precision, for environments that don't support a half-precision type
+ - float with NaN, Infinity and 0 as half
+ - double with NaN, Infinity and 0 as half
+
+
+
+
+ */
+
+
+
+/*
+ Convert single precision float to half-precision float.
+ Precision and NaN payload bits will be lost. Too large
+ values will round up to infinity and too small to zero.
+ */
+uint16_t IEEE754_FloatToHalf(float f);
+
+
+/*
+ Convert half precision float to single precision float.
+ This is a loss-less conversion.
+ */
+float IEEE754_HalfToFloat(uint16_t uHalfPrecision);
+
+
+/*
+ Convert double precision float to half-precision float.
+ Precision and NaN payload bits will be lost. Too large
+ values will round up to infinity and too small to zero.
+ */
+uint16_t IEEE754_DoubleToHalf(double d);
+
+
+/*
+ Convert half precision float to double precision float.
+ This is a loss-less conversion.
+ */
+double IEEE754_HalfToDouble(uint16_t uHalfPrecision);
+
+
+
+// Both tags the value and gives the size
+#define IEEE754_UNION_IS_HALF 2
+#define IEEE754_UNION_IS_SINGLE 4
+#define IEEE754_UNION_IS_DOUBLE 8
+
+typedef struct {
+ uint8_t uSize; // One of IEEE754_IS_xxxx
+ uint64_t uValue;
+} IEEE754_union;
+
+
+/*
+ Converts double-precision to single-precision or half-precision if possible without
+ loss of precisions. If not, leaves it as a double. Only converts to single-precision
+ unless bAllowHalfPrecision is set.
+ */
+IEEE754_union IEEE754_DoubleToSmallestInternal(double d, int bAllowHalfPrecision);
+
+/*
+ Converts double-precision to single-precision if possible without
+ loss of precision. If not, leaves it as a double.
+ */
+static inline IEEE754_union IEEE754_DoubleToSmall(double d)
+{
+ return IEEE754_DoubleToSmallestInternal(d, 0);
+}
+
+
+/*
+ Converts double-precision to single-precision or half-precision if possible without
+ loss of precisions. If not, leaves it as a double.
+ */
+static inline IEEE754_union IEEE754_DoubleToSmallest(double d)
+{
+ return IEEE754_DoubleToSmallestInternal(d, 1);
+}
+
+/*
+ Converts single-precision to half-precision if possible without
+ loss of precision. If not leaves as single-precision.
+ */
+IEEE754_union IEEE754_FloatToSmallest(float f);
+
+
+#endif /* ieee754_h */
+
+
+
+
+
+
+
diff --git a/lib/ext/qcbor/src/qcbor_decode.c b/lib/ext/qcbor/src/qcbor_decode.c
new file mode 100644
index 0000000..2286038
--- /dev/null
+++ b/lib/ext/qcbor/src/qcbor_decode.c
@@ -0,0 +1,1319 @@
+/*==============================================================================
+ Copyright (c) 2016-2018, The Linux Foundation.
+ Copyright (c) 2018-2019, Laurence Lundblade.
+ All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of The Linux Foundation nor the names of its
+ contributors, nor the name "Laurence Lundblade" may be used to
+ endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ==============================================================================*/
+
+/*===================================================================================
+ FILE: qcbor_decode.c
+
+ DESCRIPTION: This file contains the implementation of QCBOR.
+
+ EDIT HISTORY FOR FILE:
+
+ This section contains comments describing changes made to the module.
+ Notice that changes are listed in reverse chronological order.
+
+ when who what, where, why
+ -------- ---- ---------------------------------------------------
+ 01/10/19 llundblade Clever type and argument decoder is 250 bytes smaller
+ 11/9/18 llundblade Error codes are now enums.
+ 11/2/18 llundblade Simplify float decoding and align with preferred
+ float encoding
+ 10/31/18 llundblade Switch to one license that is almost BSD-3.
+ 10/28/18 llundblade Reworked tag decoding
+ 10/15/18 llundblade Indefinite length maps and arrays supported
+ 10/8/18 llundblade Indefinite length strings supported
+ 02/04/17 llundbla Work on CPUs that don's require pointer alignment
+ by making use of changes in UsefulBuf
+ 03/01/17 llundbla More data types; decoding improvements and fixes
+ 11/13/16 llundbla Integrate most TZ changes back into github version.
+ 09/30/16 gkanike Porting to TZ.
+ 03/15/16 llundbla Initial Version.
+
+ =====================================================================================*/
+
+#include "qcbor.h"
+#include "ieee754.h"
+
+
+/*
+ This casts away the const-ness of a pointer, usually so it can be
+ freed or realloced.
+ */
+#define UNCONST_POINTER(ptr) ((void *)(ptr))
+
+
+/*
+ Collection of functions to track the map/array nesting for decoding
+ */
+
+inline static int IsMapOrArray(uint8_t uDataType)
+{
+ return uDataType == QCBOR_TYPE_MAP || uDataType == QCBOR_TYPE_ARRAY;
+}
+
+inline static int DecodeNesting_IsNested(const QCBORDecodeNesting *pNesting)
+{
+ return pNesting->pCurrent != &(pNesting->pMapsAndArrays[0]);
+}
+
+inline static int DecodeNesting_IsIndefiniteLength(const QCBORDecodeNesting *pNesting)
+{
+ return pNesting->pCurrent->uCount == UINT16_MAX;
+}
+
+inline static uint8_t DecodeNesting_GetLevel(QCBORDecodeNesting *pNesting)
+{
+ return pNesting->pCurrent - &(pNesting->pMapsAndArrays[0]);
+}
+
+inline static int DecodeNesting_TypeIsMap(const QCBORDecodeNesting *pNesting)
+{
+ if(!DecodeNesting_IsNested(pNesting)) {
+ return 0;
+ }
+
+ return CBOR_MAJOR_TYPE_MAP == pNesting->pCurrent->uMajorType;
+}
+
+// Process a break. This will either ascend the nesting or error out
+inline static QCBORError DecodeNesting_BreakAscend(QCBORDecodeNesting *pNesting)
+{
+ // breaks must always occur when there is nesting
+ if(!DecodeNesting_IsNested(pNesting)) {
+ return QCBOR_ERR_BAD_BREAK;
+ }
+
+ // breaks can only occur when the map/array is indefinite length
+ if(!DecodeNesting_IsIndefiniteLength(pNesting)) {
+ return QCBOR_ERR_BAD_BREAK;
+ }
+
+ // if all OK, the break reduces the level of nesting
+ pNesting->pCurrent--;
+
+ return QCBOR_SUCCESS;
+}
+
+// Called on every single item except breaks including the opening of a map/array
+inline static void DecodeNesting_DecrementCount(QCBORDecodeNesting *pNesting)
+{
+ if(!DecodeNesting_IsNested(pNesting)) {
+ // at top level where there is no tracking
+ return;
+ }
+
+ if(DecodeNesting_IsIndefiniteLength(pNesting)) {
+ // There is no count for indefinite length arrays/maps
+ return;
+ }
+
+ // Decrement the count of items in this array/map
+ pNesting->pCurrent->uCount--;
+
+ // Pop up nesting levels if the counts at the levels are zero
+ while(DecodeNesting_IsNested(pNesting) && 0 == pNesting->pCurrent->uCount) {
+ pNesting->pCurrent--;
+ if(!DecodeNesting_IsIndefiniteLength(pNesting)) {
+ pNesting->pCurrent->uCount--;
+ }
+ }
+}
+
+// Called on every map/array
+inline static QCBORError DecodeNesting_Descend(QCBORDecodeNesting *pNesting, QCBORItem *pItem)
+{
+ QCBORError nReturn = QCBOR_SUCCESS;
+
+ if(pItem->val.uCount == 0) {
+ // Nothing to do for empty definite lenth arrays. They are just are
+ // effectively the same as an item that is not a map or array
+ goto Done;
+ // Empty indefinite length maps and arrays are handled elsewhere
+ }
+
+ // Error out if arrays is too long to handle
+ if(pItem->val.uCount != UINT16_MAX && pItem->val.uCount > QCBOR_MAX_ITEMS_IN_ARRAY) {
+ nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
+ goto Done;
+ }
+
+ // Error out if nesting is too deep
+ if(pNesting->pCurrent >= &(pNesting->pMapsAndArrays[QCBOR_MAX_ARRAY_NESTING])) {
+ nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
+ goto Done;
+ }
+
+ // The actual descend
+ pNesting->pCurrent++;
+
+ // Record a few details for this nesting level
+ pNesting->pCurrent->uMajorType = pItem->uDataType;
+ pNesting->pCurrent->uCount = pItem->val.uCount;
+
+Done:
+ return nReturn;;
+}
+
+inline static void DecodeNesting_Init(QCBORDecodeNesting *pNesting)
+{
+ pNesting->pCurrent = &(pNesting->pMapsAndArrays[0]);
+}
+
+
+
+/*
+ This list of built-in tags. Only add tags here that are
+ clearly established and useful. Once a tag is added here
+ it can't be taken out as that would break backwards compatibility.
+ There are only 48 slots available forever.
+ */
+static const uint16_t spBuiltInTagMap[] = {
+ CBOR_TAG_DATE_STRING, // See TAG_MAPPER_FIRST_FOUR
+ CBOR_TAG_DATE_EPOCH, // See TAG_MAPPER_FIRST_FOUR
+ CBOR_TAG_POS_BIGNUM, // See TAG_MAPPER_FIRST_FOUR
+ CBOR_TAG_NEG_BIGNUM, // See TAG_MAPPER_FIRST_FOUR
+ CBOR_TAG_FRACTION,
+ CBOR_TAG_BIGFLOAT,
+ CBOR_TAG_COSE_ENCRYPTO,
+ CBOR_TAG_COSE_MAC0,
+ CBOR_TAG_COSE_SIGN1,
+ CBOR_TAG_ENC_AS_B64URL,
+ CBOR_TAG_ENC_AS_B64,
+ CBOR_TAG_ENC_AS_B16,
+ CBOR_TAG_CBOR,
+ CBOR_TAG_URI,
+ CBOR_TAG_B64URL,
+ CBOR_TAG_B64,
+ CBOR_TAG_REGEX,
+ CBOR_TAG_MIME,
+ CBOR_TAG_BIN_UUID,
+ CBOR_TAG_CWT,
+ CBOR_TAG_ENCRYPT,
+ CBOR_TAG_MAC,
+ CBOR_TAG_SIGN,
+ CBOR_TAG_GEO_COORD,
+ CBOR_TAG_CBOR_MAGIC
+};
+
+// This is used in a bit of cleverness in GetNext_TaggedItem() to
+// keep code size down and switch for the internal processing of
+// these types. This will break if the first four items in
+// spBuiltInTagMap don't have values 0,1,2,3. That is the
+// mapping is 0 to 0, 1 to 1, 2 to 2 and 3 to 3.
+#define QCBOR_TAGFLAG_DATE_STRING (0x01LL << CBOR_TAG_DATE_STRING)
+#define QCBOR_TAGFLAG_DATE_EPOCH (0x01LL << CBOR_TAG_DATE_EPOCH)
+#define QCBOR_TAGFLAG_POS_BIGNUM (0x01LL << CBOR_TAG_POS_BIGNUM)
+#define QCBOR_TAGFLAG_NEG_BIGNUM (0x01LL << CBOR_TAG_NEG_BIGNUM)
+
+#define TAG_MAPPER_FIRST_FOUR (QCBOR_TAGFLAG_DATE_STRING |\
+ QCBOR_TAGFLAG_DATE_EPOCH |\
+ QCBOR_TAGFLAG_POS_BIGNUM |\
+ QCBOR_TAGFLAG_NEG_BIGNUM)
+
+#define TAG_MAPPER_TOTAL_TAG_BITS 64 // Number of bits in a uint64_t
+#define TAG_MAPPER_CUSTOM_TAGS_BASE_INDEX (TAG_MAPPER_TOTAL_TAG_BITS - QCBOR_MAX_CUSTOM_TAGS) // 48
+#define TAG_MAPPER_MAX_SIZE_BUILT_IN_TAGS (TAG_MAPPER_TOTAL_TAG_BITS - QCBOR_MAX_CUSTOM_TAGS ) // 48
+
+static inline int TagMapper_LookupBuiltIn(uint64_t uTag)
+{
+ if(sizeof(spBuiltInTagMap)/sizeof(uint16_t) > TAG_MAPPER_MAX_SIZE_BUILT_IN_TAGS) {
+ // This is a cross-check to make sure the above array doesn't
+ // accidentally get made too big.
+ // In normal conditions the above test should optimize out
+ // as all the values are known at compile time.
+ return -1;
+ }
+
+ if(uTag > UINT16_MAX) {
+ // This tag map works only on 16-bit tags
+ return -1;
+ }
+
+ for(int nTagBitIndex = 0; nTagBitIndex < (int)(sizeof(spBuiltInTagMap)/sizeof(uint16_t)); nTagBitIndex++) {
+ if(spBuiltInTagMap[nTagBitIndex] == uTag) {
+ return nTagBitIndex;
+ }
+ }
+ return -1; // Indicates no match
+}
+
+static inline int TagMapper_LookupCallerConfigured(const QCBORTagListIn *pCallerConfiguredTagMap, uint64_t uTag)
+{
+ for(int nTagBitIndex = 0; nTagBitIndex < pCallerConfiguredTagMap->uNumTags; nTagBitIndex++) {
+ if(pCallerConfiguredTagMap->puTags[nTagBitIndex] == uTag) {
+ return nTagBitIndex + TAG_MAPPER_CUSTOM_TAGS_BASE_INDEX;
+ }
+ }
+
+ return -1; // Indicates no match
+}
+
+/*
+ Find the tag bit index for a given tag value, or error out
+
+ This and the above functions could probably be optimized and made
+ clearer and neater.
+ */
+static QCBORError TagMapper_Lookup(const QCBORTagListIn *pCallerConfiguredTagMap, uint64_t uTag, uint8_t *puTagBitIndex)
+{
+ int nTagBitIndex = TagMapper_LookupBuiltIn(uTag);
+ if(nTagBitIndex >= 0) {
+ // Cast is safe because TagMapper_LookupBuiltIn never returns > 47
+ *puTagBitIndex = (uint8_t)nTagBitIndex;
+ return QCBOR_SUCCESS;
+ }
+
+ if(pCallerConfiguredTagMap) {
+ if(pCallerConfiguredTagMap->uNumTags > QCBOR_MAX_CUSTOM_TAGS) {
+ return QCBOR_ERR_TOO_MANY_TAGS;
+ }
+ nTagBitIndex = TagMapper_LookupCallerConfigured(pCallerConfiguredTagMap, uTag);
+ if(nTagBitIndex >= 0) {
+ // Cast is safe because TagMapper_LookupBuiltIn never returns > 63
+
+ *puTagBitIndex = (uint8_t)nTagBitIndex;
+ return QCBOR_SUCCESS;
+ }
+ }
+
+ return QCBOR_ERR_BAD_OPT_TAG;
+}
+
+
+
+
+/*
+ Public function, see header file
+ */
+void QCBORDecode_Init(QCBORDecodeContext *me, UsefulBufC EncodedCBOR, QCBORDecodeMode nDecodeMode)
+{
+ memset(me, 0, sizeof(QCBORDecodeContext));
+ UsefulInputBuf_Init(&(me->InBuf), EncodedCBOR);
+ // Don't bother with error check on decode mode. If a bad value is passed it will just act as
+ // if the default normal mode of 0 was set.
+ me->uDecodeMode = nDecodeMode;
+ DecodeNesting_Init(&(me->nesting));
+}
+
+
+/*
+ Public function, see header file
+ */
+void QCBORDecode_SetUpAllocator(QCBORDecodeContext *pCtx, const QCBORStringAllocator *pAllocator, bool bAllocAll)
+{
+ pCtx->pStringAllocator = (void *)pAllocator;
+ pCtx->bStringAllocateAll = bAllocAll;
+}
+
+void QCBORDecode_SetCallerConfiguredTagList(QCBORDecodeContext *me, const QCBORTagListIn *pTagList)
+{
+ me->pCallerConfiguredTagList = pTagList;
+}
+
+
+/*
+ This decodes the fundamental part of a CBOR data item, the type and number
+
+ This is the Counterpart to InsertEncodedTypeAndNumber().
+
+ This does the network->host byte order conversion. The conversion here
+ also results in the conversion for floats in addition to that for
+ lengths, tags and integer values.
+
+ This returns:
+ pnMajorType -- the major type for the item
+ puNumber -- the "number" which is used a the value for integers, tags and floats and length for strings and arrays
+ puAdditionalInfo -- Pass this along to know what kind of float or if length is indefinite
+
+ */
+inline static QCBORError DecodeTypeAndNumber(UsefulInputBuf *pUInBuf,
+ int *pnMajorType,
+ uint64_t *puArgument,
+ uint8_t *puAdditionalInfo)
+{
+ QCBORError nReturn;
+
+ // Get the initial byte that every CBOR data item has
+ const uint8_t uInitialByte = UsefulInputBuf_GetByte(pUInBuf);
+
+ // Break down the initial byte
+ const uint8_t uTmpMajorType = uInitialByte >> 5;
+ const uint8_t uAdditionalInfo = uInitialByte & 0x1f;
+
+ // Where the number or argument accumulates
+ uint64_t uArgument;
+
+ if(uAdditionalInfo >= LEN_IS_ONE_BYTE && uAdditionalInfo <= LEN_IS_EIGHT_BYTES) {
+ // Need to get 1,2,4 or 8 additional argument bytes
+ // Map LEN_IS_ONE_BYTE.. LEN_IS_EIGHT_BYTES to actual length
+ static const uint8_t aIterate[] = {1,2,4,8};
+
+ // Loop getting all the bytes in the argument
+ uArgument = 0;
+ for(int i = aIterate[uAdditionalInfo - LEN_IS_ONE_BYTE]; i; i--) {
+ // This shift and add gives the endian conversion
+ uArgument = (uArgument << 8) + UsefulInputBuf_GetByte(pUInBuf);
+ }
+ } else if(uAdditionalInfo >= ADDINFO_RESERVED1 && uAdditionalInfo <= ADDINFO_RESERVED3) {
+ // The reserved and thus-far unused additional info values
+ nReturn = QCBOR_ERR_UNSUPPORTED;
+ goto Done;
+ } else {
+ // Less than 24, additional info is argument or 31, an indefinite length
+ // No more bytes to get
+ uArgument = uAdditionalInfo;
+ }
+
+ if(UsefulInputBuf_GetError(pUInBuf)) {
+ nReturn = QCBOR_ERR_HIT_END;
+ goto Done;
+ }
+
+ // All successful if we got here.
+ nReturn = QCBOR_SUCCESS;
+ *pnMajorType = uTmpMajorType;
+ *puArgument = uArgument;
+ *puAdditionalInfo = uAdditionalInfo;
+
+Done:
+ return nReturn;
+}
+
+/*
+ CBOR doesn't explicitly specify two's compliment for integers but all CPUs
+ use it these days and the test vectors in the RFC are so. All integers in the CBOR
+ structure are positive and the major type indicates positive or negative.
+ CBOR can express positive integers up to 2^x - 1 where x is the number of bits
+ and negative integers down to 2^x. Note that negative numbers can be one
+ more away from zero than positive.
+ Stdint, as far as I can tell, uses two's compliment to represent
+ negative integers.
+
+ See http://www.unix.org/whitepapers/64bit.html for reasons int isn't
+ used here in any way including in the interface
+ */
+inline static QCBORError DecodeInteger(int nMajorType, uint64_t uNumber, QCBORItem *pDecodedItem)
+{
+ // Stack usage: int/ptr 1 -- 8
+ QCBORError nReturn = QCBOR_SUCCESS;
+
+ if(nMajorType == CBOR_MAJOR_TYPE_POSITIVE_INT) {
+ if (uNumber <= INT64_MAX) {
+ pDecodedItem->val.int64 = (int64_t)uNumber;
+ pDecodedItem->uDataType = QCBOR_TYPE_INT64;
+
+ } else {
+ pDecodedItem->val.uint64 = uNumber;
+ pDecodedItem->uDataType = QCBOR_TYPE_UINT64;
+
+ }
+ } else {
+ if(uNumber <= INT64_MAX) {
+ pDecodedItem->val.int64 = -uNumber-1;
+ pDecodedItem->uDataType = QCBOR_TYPE_INT64;
+
+ } else {
+ // C can't represent a negative integer in this range
+ // so it is an error. todo -- test this condition
+ nReturn = QCBOR_ERR_INT_OVERFLOW;
+ }
+ }
+
+ return nReturn;
+}
+
+// Make sure #define value line up as DecodeSimple counts on this.
+#if QCBOR_TYPE_FALSE != CBOR_SIMPLEV_FALSE
+#error QCBOR_TYPE_FALSE macro value wrong
+#endif
+
+#if QCBOR_TYPE_TRUE != CBOR_SIMPLEV_TRUE
+#error QCBOR_TYPE_TRUE macro value wrong
+#endif
+
+#if QCBOR_TYPE_NULL != CBOR_SIMPLEV_NULL
+#error QCBOR_TYPE_NULL macro value wrong
+#endif
+
+#if QCBOR_TYPE_UNDEF != CBOR_SIMPLEV_UNDEF
+#error QCBOR_TYPE_UNDEF macro value wrong
+#endif
+
+#if QCBOR_TYPE_BREAK != CBOR_SIMPLE_BREAK
+#error QCBOR_TYPE_BREAK macro value wrong
+#endif
+
+#if QCBOR_TYPE_DOUBLE != DOUBLE_PREC_FLOAT
+#error QCBOR_TYPE_DOUBLE macro value wrong
+#endif
+
+#if QCBOR_TYPE_FLOAT != SINGLE_PREC_FLOAT
+#error QCBOR_TYPE_FLOAT macro value wrong
+#endif
+
+/*
+ Decode true, false, floats, break...
+ */
+
+inline static QCBORError DecodeSimple(uint8_t uAdditionalInfo, uint64_t uNumber, QCBORItem *pDecodedItem)
+{
+ // Stack usage: 0
+ QCBORError nReturn = QCBOR_SUCCESS;
+
+ // uAdditionalInfo is 5 bits from the initial byte
+ // compile time checks above make sure uAdditionalInfo values line up with uDataType values
+ pDecodedItem->uDataType = uAdditionalInfo;
+
+ switch(uAdditionalInfo) {
+ case ADDINFO_RESERVED1: // 28
+ case ADDINFO_RESERVED2: // 29
+ case ADDINFO_RESERVED3: // 30
+ nReturn = QCBOR_ERR_UNSUPPORTED;
+ break;
+
+ case HALF_PREC_FLOAT:
+ pDecodedItem->val.dfnum = IEEE754_HalfToDouble((uint16_t)uNumber);
+ pDecodedItem->uDataType = QCBOR_TYPE_DOUBLE;
+ break;
+ case SINGLE_PREC_FLOAT:
+ pDecodedItem->val.dfnum = (double)UsefulBufUtil_CopyUint32ToFloat((uint32_t)uNumber);
+ pDecodedItem->uDataType = QCBOR_TYPE_DOUBLE;
+ break;
+ case DOUBLE_PREC_FLOAT:
+ pDecodedItem->val.dfnum = UsefulBufUtil_CopyUint64ToDouble(uNumber);
+ pDecodedItem->uDataType = QCBOR_TYPE_DOUBLE;
+ break;
+
+ case CBOR_SIMPLEV_FALSE: // 20
+ case CBOR_SIMPLEV_TRUE: // 21
+ case CBOR_SIMPLEV_NULL: // 22
+ case CBOR_SIMPLEV_UNDEF: // 23
+ case CBOR_SIMPLE_BREAK: // 31
+ break; // nothing to do
+
+ case CBOR_SIMPLEV_ONEBYTE: // 24
+ if(uNumber <= CBOR_SIMPLE_BREAK) {
+ // This takes out f8 00 ... f8 1f which should be encoded as e0 … f7
+ nReturn = QCBOR_ERR_INVALID_CBOR;
+ goto Done;
+ }
+ /* FALLTHROUGH */
+ // fall through intentionally
+
+ default: // 0-19
+ pDecodedItem->uDataType = QCBOR_TYPE_UKNOWN_SIMPLE;
+ // DecodeTypeAndNumber will make uNumber equal to uAdditionalInfo when uAdditionalInfo is < 24
+ // This cast is safe because the 2, 4 and 8 byte lengths of uNumber are in the double/float cases above
+ pDecodedItem->val.uSimple = (uint8_t)uNumber;
+ break;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+
+/*
+ Decode text and byte strings. Call the string allocator if asked to.
+ */
+inline static QCBORError DecodeBytes(const QCBORStringAllocator *pAlloc, int nMajorType, uint64_t uStrLen, UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem)
+{
+ // Stack usage: UsefulBuf 2, int/ptr 1 40
+ QCBORError nReturn = QCBOR_SUCCESS;
+
+ const UsefulBufC Bytes = UsefulInputBuf_GetUsefulBuf(pUInBuf, uStrLen);
+ if(UsefulBuf_IsNULLC(Bytes)) {
+ // Failed to get the bytes for this string item
+ nReturn = QCBOR_ERR_HIT_END;
+ goto Done;
+ }
+
+ if(pAlloc) {
+ // We are asked to use string allocator to make a copy
+ UsefulBuf NewMem = pAlloc->fAllocate(pAlloc->pAllocaterContext, NULL, uStrLen);
+ if(UsefulBuf_IsNULL(NewMem)) {
+ nReturn = QCBOR_ERR_STRING_ALLOCATE;
+ goto Done;
+ }
+ pDecodedItem->val.string = UsefulBuf_Copy(NewMem, Bytes);
+ } else {
+ // Normal case with no string allocator
+ pDecodedItem->val.string = Bytes;
+ }
+ pDecodedItem->uDataType = (nMajorType == CBOR_MAJOR_TYPE_BYTE_STRING) ? QCBOR_TYPE_BYTE_STRING : QCBOR_TYPE_TEXT_STRING;
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ Mostly just assign the right data type for the date string.
+ */
+inline static QCBORError DecodeDateString(QCBORItem *pDecodedItem)
+{
+ // Stack Use: UsefulBuf 1 16
+ if(pDecodedItem->uDataType != QCBOR_TYPE_TEXT_STRING) {
+ return QCBOR_ERR_BAD_OPT_TAG;
+ }
+
+ const UsefulBufC Temp = pDecodedItem->val.string;
+ pDecodedItem->val.dateString = Temp;
+ pDecodedItem->uDataType = QCBOR_TYPE_DATE_STRING;
+ return QCBOR_SUCCESS;
+}
+
+
+/*
+ Mostly just assign the right data type for the bignum.
+ */
+inline static QCBORError DecodeBigNum(QCBORItem *pDecodedItem)
+{
+ // Stack Use: UsefulBuf 1 -- 16
+ if(pDecodedItem->uDataType != QCBOR_TYPE_BYTE_STRING) {
+ return QCBOR_ERR_BAD_OPT_TAG;
+ }
+ const UsefulBufC Temp = pDecodedItem->val.string;
+ pDecodedItem->val.bigNum = Temp;
+ pDecodedItem->uDataType = pDecodedItem->uTagBits & QCBOR_TAGFLAG_POS_BIGNUM ? QCBOR_TYPE_POSBIGNUM : QCBOR_TYPE_NEGBIGNUM;
+ return QCBOR_SUCCESS;
+}
+
+
+/*
+ The epoch formatted date. Turns lots of different forms of encoding date into uniform one
+ */
+static int DecodeDateEpoch(QCBORItem *pDecodedItem)
+{
+ // Stack usage: 1
+ QCBORError nReturn = QCBOR_SUCCESS;
+
+ pDecodedItem->val.epochDate.fSecondsFraction = 0;
+
+ switch (pDecodedItem->uDataType) {
+
+ case QCBOR_TYPE_INT64:
+ pDecodedItem->val.epochDate.nSeconds = pDecodedItem->val.int64;
+ break;
+
+ case QCBOR_TYPE_UINT64:
+ if(pDecodedItem->val.uint64 > INT64_MAX) {
+ nReturn = QCBOR_ERR_DATE_OVERFLOW;
+ goto Done;
+ }
+ pDecodedItem->val.epochDate.nSeconds = pDecodedItem->val.uint64;
+ break;
+
+ case QCBOR_TYPE_DOUBLE:
+ {
+ const double d = pDecodedItem->val.dfnum;
+ if(d > INT64_MAX) {
+ nReturn = QCBOR_ERR_DATE_OVERFLOW;
+ goto Done;
+ }
+ pDecodedItem->val.epochDate.nSeconds = d; // Float to integer conversion happening here.
+ pDecodedItem->val.epochDate.fSecondsFraction = d - pDecodedItem->val.epochDate.nSeconds;
+ }
+ break;
+
+ default:
+ nReturn = QCBOR_ERR_BAD_OPT_TAG;
+ goto Done;
+ }
+ pDecodedItem->uDataType = QCBOR_TYPE_DATE_EPOCH;
+
+Done:
+ return nReturn;
+}
+
+
+
+
+// Make sure the constants align as this is assumed by the GetAnItem() implementation
+#if QCBOR_TYPE_ARRAY != CBOR_MAJOR_TYPE_ARRAY
+#error QCBOR_TYPE_ARRAY value not lined up with major type
+#endif
+#if QCBOR_TYPE_MAP != CBOR_MAJOR_TYPE_MAP
+#error QCBOR_TYPE_MAP value not lined up with major type
+#endif
+
+/*
+ This gets a single data item and decodes it including preceding optional tagging. This does not
+ deal with arrays and maps and nesting except to decode the data item introducing them. Arrays and
+ maps are handled at the next level up in GetNext().
+
+ Errors detected here include: an array that is too long to decode, hit end of buffer unexpectedly,
+ a few forms of invalid encoded CBOR
+ */
+static QCBORError GetNext_Item(UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem, const QCBORStringAllocator *pAlloc)
+{
+ // Stack usage: int/ptr 3 -- 24
+ QCBORError nReturn;
+
+ // Get the major type and the number. Number could be length of more bytes or the value depending on the major type
+ // nAdditionalInfo is an encoding of the length of the uNumber and is needed to decode floats and doubles
+ int uMajorType;
+ uint64_t uNumber;
+ uint8_t uAdditionalInfo;
+
+ nReturn = DecodeTypeAndNumber(pUInBuf, &uMajorType, &uNumber, &uAdditionalInfo);
+
+ // Error out here if we got into trouble on the type and number.
+ // The code after this will not work if the type and number is not good.
+ if(nReturn)
+ goto Done;
+
+ memset(pDecodedItem, 0, sizeof(QCBORItem));
+
+ // At this point the major type and the value are valid. We've got the type and the number that
+ // starts every CBOR data item.
+ switch (uMajorType) {
+ case CBOR_MAJOR_TYPE_POSITIVE_INT: // Major type 0
+ case CBOR_MAJOR_TYPE_NEGATIVE_INT: // Major type 1
+ nReturn = DecodeInteger(uMajorType, uNumber, pDecodedItem);
+ break;
+
+ case CBOR_MAJOR_TYPE_BYTE_STRING: // Major type 2
+ case CBOR_MAJOR_TYPE_TEXT_STRING: // Major type 3
+ if(uAdditionalInfo == LEN_IS_INDEFINITE) {
+ pDecodedItem->uDataType = (uMajorType == CBOR_MAJOR_TYPE_BYTE_STRING) ? QCBOR_TYPE_BYTE_STRING : QCBOR_TYPE_TEXT_STRING;
+ pDecodedItem->val.string = (UsefulBufC){NULL, SIZE_MAX};
+ } else {
+ nReturn = DecodeBytes(pAlloc, uMajorType, uNumber, pUInBuf, pDecodedItem);
+ }
+ break;
+
+ case CBOR_MAJOR_TYPE_ARRAY: // Major type 4
+ case CBOR_MAJOR_TYPE_MAP: // Major type 5
+ // Record the number of items in the array or map
+ if(uNumber > QCBOR_MAX_ITEMS_IN_ARRAY) {
+ nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
+ goto Done;
+ }
+ if(uAdditionalInfo == LEN_IS_INDEFINITE) {
+ pDecodedItem->val.uCount = UINT16_MAX; // Indicate indefinite length
+ } else {
+ pDecodedItem->val.uCount = (uint16_t)uNumber; // type conversion OK because of check above
+ }
+ pDecodedItem->uDataType = uMajorType; // C preproc #if above makes sure constants align
+ break;
+
+ case CBOR_MAJOR_TYPE_OPTIONAL: // Major type 6, optional prepended tags
+ pDecodedItem->val.uTagV = uNumber;
+ pDecodedItem->uDataType = QCBOR_TYPE_OPTTAG;
+ break;
+
+ case CBOR_MAJOR_TYPE_SIMPLE: // Major type 7, float, double, true, false, null...
+ nReturn = DecodeSimple(uAdditionalInfo, uNumber, pDecodedItem);
+ break;
+
+ default: // Should never happen because DecodeTypeAndNumber() should never return > 7
+ nReturn = QCBOR_ERR_UNSUPPORTED;
+ break;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+
+/*
+ This layer deals with indefinite length strings. It pulls all the
+ individual chunk items together into one QCBORItem using the
+ string allocator.
+
+ Code Reviewers: THIS FUNCTION DOES A LITTLE POINTER MATH
+ */
+static inline QCBORError GetNext_FullItem(QCBORDecodeContext *me, QCBORItem *pDecodedItem)
+{
+ // Stack usage; int/ptr 2 UsefulBuf 2 QCBORItem -- 96
+ QCBORError nReturn;
+ QCBORStringAllocator *pAlloc = (QCBORStringAllocator *)me->pStringAllocator;
+ UsefulBufC FullString = NULLUsefulBufC;
+
+ nReturn = GetNext_Item(&(me->InBuf), pDecodedItem, me->bStringAllocateAll ? pAlloc: NULL);
+ if(nReturn) {
+ goto Done;
+ }
+
+ // To reduce code size by removing support for indefinite length strings, the
+ // code in this function from here down can be eliminated. Run tests, except
+ // indefinite length string tests, to be sure all is OK if this is removed.
+
+ // Only do indefinite length processing on strings
+ if(pDecodedItem->uDataType != QCBOR_TYPE_BYTE_STRING && pDecodedItem->uDataType != QCBOR_TYPE_TEXT_STRING) {
+ goto Done; // no need to do any work here on non-string types
+ }
+
+ // Is this a string with an indefinite length?
+ if(pDecodedItem->val.string.len != SIZE_MAX) {
+ goto Done; // length is not indefinite, so no work to do here
+ }
+
+ // Can't do indefinite length strings without a string allocator
+ if(pAlloc == NULL) {
+ nReturn = QCBOR_ERR_NO_STRING_ALLOCATOR;
+ goto Done;
+ }
+
+ // There is an indefinite length string to work on...
+ // Track which type of string it is
+ const uint8_t uStringType = pDecodedItem->uDataType;
+
+ // Loop getting chunk of indefinite string
+ for(;;) {
+ // Get item for next chunk
+ QCBORItem StringChunkItem;
+ // NULL passed to never string alloc chunk of indefinite length strings
+ nReturn = GetNext_Item(&(me->InBuf), &StringChunkItem, NULL);
+ if(nReturn) {
+ break; // Error getting the next chunk
+ }
+
+ // See if it is a marker at end of indefinite length string
+ if(StringChunkItem.uDataType == QCBOR_TYPE_BREAK) {
+ // String is complete
+ pDecodedItem->val.string = FullString;
+ pDecodedItem->uDataAlloc = 1;
+ break;
+ }
+
+ // Match data type of chunk to type at beginning.
+ // Also catches error of other non-string types that don't belong.
+ if(StringChunkItem.uDataType != uStringType) {
+ nReturn = QCBOR_ERR_INDEFINITE_STRING_CHUNK;
+ break;
+ }
+
+ // Alloc new buffer or expand previously allocated buffer so it can fit
+ UsefulBuf NewMem = (*pAlloc->fAllocate)(pAlloc->pAllocaterContext,
+ UNCONST_POINTER(FullString.ptr),
+ FullString.len + StringChunkItem.val.string.len);
+ if(UsefulBuf_IsNULL(NewMem)) {
+ // Allocation of memory for the string failed
+ nReturn = QCBOR_ERR_STRING_ALLOCATE;
+ break;
+ }
+
+ // Copy new string chunk at the end of string so far.
+ FullString = UsefulBuf_CopyOffset(NewMem, FullString.len, StringChunkItem.val.string);
+ }
+
+Done:
+ if(pAlloc && nReturn && !UsefulBuf_IsNULLC(FullString)) {
+ // Getting item failed, clean up the allocated memory
+ (pAlloc->fFree)(pAlloc->pAllocaterContext, UNCONST_POINTER(FullString.ptr));
+ }
+
+ return nReturn;
+}
+
+
+/*
+ Returns an error if there was something wrong with the optional item or it couldn't
+ be handled.
+ */
+static QCBORError GetNext_TaggedItem(QCBORDecodeContext *me, QCBORItem *pDecodedItem, QCBORTagListOut *pTags)
+{
+ // Stack usage: int/ptr: 3 -- 24
+ QCBORError nReturn;
+ uint64_t uTagBits = 0;
+ if(pTags) {
+ pTags->uNumUsed = 0;
+ }
+
+ for(;;) {
+ nReturn = GetNext_FullItem(me, pDecodedItem);
+ if(nReturn) {
+ goto Done; // Error out of the loop
+ }
+
+ if(pDecodedItem->uDataType != QCBOR_TYPE_OPTTAG) {
+ // Successful exit from loop; maybe got some tags, maybe not
+ pDecodedItem->uTagBits = uTagBits;
+ break;
+ }
+
+ uint8_t uTagBitIndex;
+ // Tag was mapped, tag was not mapped, error with tag list
+ switch(TagMapper_Lookup(me->pCallerConfiguredTagList, pDecodedItem->val.uTagV, &uTagBitIndex)) {
+
+ case QCBOR_SUCCESS:
+ // Successfully mapped the tag
+ uTagBits |= 0x01ULL << uTagBitIndex;
+ break;
+
+ case QCBOR_ERR_BAD_OPT_TAG:
+ // Tag is not recognized. Do nothing
+ break;
+
+ default:
+ // Error Condition
+ goto Done;
+ }
+
+ if(pTags) {
+ // Caller wants all tags recorded in the provided buffer
+ if(pTags->uNumUsed >= pTags->uNumAllocated) {
+ nReturn = QCBOR_ERR_TOO_MANY_TAGS;
+ goto Done;
+ }
+ pTags->puTags[pTags->uNumUsed] = pDecodedItem->val.uTagV;
+ pTags->uNumUsed++;
+ }
+ }
+
+ switch(pDecodedItem->uTagBits & TAG_MAPPER_FIRST_FOUR) {
+ case 0:
+ // No tags at all or none we know about. Nothing to do.
+ // This is part of the pass-through path of this function
+ // that will mostly be taken when decoding any item.
+ break;
+
+ case QCBOR_TAGFLAG_DATE_STRING:
+ nReturn = DecodeDateString(pDecodedItem);
+ break;
+
+ case QCBOR_TAGFLAG_DATE_EPOCH:
+ nReturn = DecodeDateEpoch(pDecodedItem);
+ break;
+
+ case QCBOR_TAGFLAG_POS_BIGNUM:
+ case QCBOR_TAGFLAG_NEG_BIGNUM:
+ nReturn = DecodeBigNum(pDecodedItem);
+ break;
+
+ default:
+ // Encountering some mixed up CBOR like something that
+ // is tagged as both a string and integer date.
+ nReturn = QCBOR_ERR_BAD_OPT_TAG;
+ }
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ This layer takes care of map entries. It combines the label and data items into one QCBORItem.
+ */
+static inline QCBORError GetNext_MapEntry(QCBORDecodeContext *me, QCBORItem *pDecodedItem, QCBORTagListOut *pTags)
+{
+ // Stack use: int/ptr 1, QCBORItem -- 56
+ QCBORError nReturn = GetNext_TaggedItem(me, pDecodedItem, pTags);
+ if(nReturn)
+ goto Done;
+
+ if(pDecodedItem->uDataType == QCBOR_TYPE_BREAK) {
+ // Break can't be a map entry
+ goto Done;
+ }
+
+ if(me->uDecodeMode != QCBOR_DECODE_MODE_MAP_AS_ARRAY) {
+ // In a map and caller wants maps decoded, not treated as arrays
+
+ if(DecodeNesting_TypeIsMap(&(me->nesting))) {
+ // If in a map and the right decoding mode, get the label
+
+ // Get the next item which will be the real data; Item will be the label
+ QCBORItem LabelItem = *pDecodedItem;
+ nReturn = GetNext_TaggedItem(me, pDecodedItem, pTags);
+ if(nReturn)
+ goto Done;
+
+ pDecodedItem->uLabelAlloc = LabelItem.uDataAlloc;
+
+ if(LabelItem.uDataType == QCBOR_TYPE_TEXT_STRING) {
+ // strings are always good labels
+ pDecodedItem->label.string = LabelItem.val.string;
+ pDecodedItem->uLabelType = QCBOR_TYPE_TEXT_STRING;
+ } else if (QCBOR_DECODE_MODE_MAP_STRINGS_ONLY == me->uDecodeMode) {
+ // It's not a string and we only want strings, probably for easy translation to JSON
+ nReturn = QCBOR_ERR_MAP_LABEL_TYPE;
+ goto Done;
+ } else if(LabelItem.uDataType == QCBOR_TYPE_INT64) {
+ pDecodedItem->label.int64 = LabelItem.val.int64;
+ pDecodedItem->uLabelType = QCBOR_TYPE_INT64;
+ } else if(LabelItem.uDataType == QCBOR_TYPE_UINT64) {
+ pDecodedItem->label.uint64 = LabelItem.val.uint64;
+ pDecodedItem->uLabelType = QCBOR_TYPE_UINT64;
+ } else if(LabelItem.uDataType == QCBOR_TYPE_BYTE_STRING) {
+ pDecodedItem->label.string = LabelItem.val.string;
+ pDecodedItem->uLabelAlloc = LabelItem.uDataAlloc;
+ pDecodedItem->uLabelType = QCBOR_TYPE_BYTE_STRING;
+ } else {
+ // label is not an int or a string. It is an arrray
+ // or a float or such and this implementation doesn't handle that.
+ // Also, tags on labels are ignored.
+ nReturn = QCBOR_ERR_MAP_LABEL_TYPE;
+ goto Done;
+ }
+ }
+ } else {
+ if(pDecodedItem->uDataType == QCBOR_TYPE_MAP) {
+ // Decoding a map as an array
+ pDecodedItem->uDataType = QCBOR_TYPE_MAP_AS_ARRAY;
+ pDecodedItem->val.uCount *= 2;
+ }
+ }
+
+Done:
+ return nReturn;
+}
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+QCBORError QCBORDecode_GetNextWithTags(QCBORDecodeContext *me, QCBORItem *pDecodedItem, QCBORTagListOut *pTags)
+{
+ // Stack ptr/int: 2, QCBORItem : 64
+
+ // The public entry point for fetching and parsing the next QCBORItem.
+ // All the CBOR parsing work is here and in subordinate calls.
+ QCBORError nReturn;
+
+ nReturn = GetNext_MapEntry(me, pDecodedItem, pTags);
+ if(nReturn) {
+ goto Done;
+ }
+
+ // Break ending arrays/maps are always processed at the end of this function.
+ // They should never show up here.
+ if(pDecodedItem->uDataType == QCBOR_TYPE_BREAK) {
+ nReturn = QCBOR_ERR_BAD_BREAK;
+ goto Done;
+ }
+
+ // Record the nesting level for this data item before processing any of
+ // decrementing and descending.
+ pDecodedItem->uNestingLevel = DecodeNesting_GetLevel(&(me->nesting));
+
+ // Process the item just received for descent or decrement, and
+ // ascent if decrements are enough to close out a definite length array/map
+ if(IsMapOrArray(pDecodedItem->uDataType)) {
+ // If the new item is array or map, the nesting level descends
+ nReturn = DecodeNesting_Descend(&(me->nesting), pDecodedItem);
+ // Maps and arrays do count in as items in the map/array that encloses
+ // them so a decrement needs to be done for them too, but that is done
+ // only when all the items in them have been processed, not when they
+ // are opened.
+ } else {
+ // Decrement the count of items in the enclosing map/array
+ // If the count in the enclosing map/array goes to zero, that
+ // triggers a decrement in the map/array above that and
+ // an ascend in nesting level.
+ DecodeNesting_DecrementCount(&(me->nesting));
+ }
+ if(nReturn) {
+ goto Done;
+ }
+
+ // For indefinite length maps/arrays, looking at any and
+ // all breaks that might terminate them. The equivalent
+ // for definite length maps/arrays happens in
+ // DecodeNesting_DecrementCount().
+ if(DecodeNesting_IsNested(&(me->nesting)) && DecodeNesting_IsIndefiniteLength(&(me->nesting))) {
+ while(UsefulInputBuf_BytesUnconsumed(&(me->InBuf))) {
+ // Peek forward one item to see if it is a break.
+ QCBORItem Peek;
+ size_t uPeek = UsefulInputBuf_Tell(&(me->InBuf));
+ nReturn = GetNext_Item(&(me->InBuf), &Peek, NULL);
+ if(nReturn) {
+ goto Done;
+ }
+ if(Peek.uDataType != QCBOR_TYPE_BREAK) {
+ // It is not a break, rewind so it can be processed normally.
+ UsefulInputBuf_Seek(&(me->InBuf), uPeek);
+ break;
+ }
+ // It is a break. Ascend one nesting level.
+ // The break is consumed.
+ nReturn = DecodeNesting_BreakAscend(&(me->nesting));
+ if(nReturn) {
+ // break occured outside of an indefinite length array/map
+ goto Done;
+ }
+ }
+ }
+
+ // Tell the caller what level is next. This tells them what maps/arrays
+ // were closed out and makes it possible for them to reconstruct
+ // the tree with just the information returned by GetNext
+ pDecodedItem->uNextNestLevel = DecodeNesting_GetLevel(&(me->nesting));
+
+Done:
+ return nReturn;
+}
+
+
+QCBORError QCBORDecode_GetNext(QCBORDecodeContext *me, QCBORItem *pDecodedItem)
+{
+ return QCBORDecode_GetNextWithTags(me, pDecodedItem, NULL);
+}
+
+
+/*
+ Decoding items is done in 5 layered functions, one calling the
+ next one down. If a layer has no work to do for a particular item
+ it returns quickly.
+
+ - QCBORDecode_GetNext -- The top layer manages the beginnings and
+ ends of maps and arrays. It tracks descending into and ascending
+ out of maps/arrays. It processes all breaks that terminate
+ maps and arrays.
+
+ - GetNext_MapEntry -- This handles the combining of two
+ items, the label and the data, that make up a map entry.
+ It only does work on maps. It combines the label and data
+ items into one labeled item.
+
+ - GetNext_TaggedItem -- This handles the type 6 tagged items.
+ It accumulates all the tags and combines them with the following
+ non-tagged item. If the tagged item is something that is understood
+ like a date, the decoding of that item is invoked.
+
+ - GetNext_FullItem -- This assembles the sub items that make up
+ an indefinte length string into one string item. It uses the
+ string allocater to create contiguous space for the item. It
+ processes all breaks that are part of indefinite length strings.
+
+ - GetNext_Item -- This gets and decodes the most atomic
+ item in CBOR, the thing with an initial byte containing
+ the major type.
+
+ Roughly this takes 300 bytes of stack for vars. Need to
+ evaluate this more carefully and correctly.
+
+ */
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+int QCBORDecode_IsTagged(QCBORDecodeContext *me, const QCBORItem *pItem, uint64_t uTag)
+{
+ const QCBORTagListIn *pCallerConfiguredTagMap = me->pCallerConfiguredTagList;
+
+ uint8_t uTagBitIndex;
+ // Do not care about errors in pCallerConfiguredTagMap here. They are
+ // caught during GetNext() before this is called.
+ if(TagMapper_Lookup(pCallerConfiguredTagMap, uTag, &uTagBitIndex)) {
+ return 0;
+ }
+
+ const uint64_t uTagBit = 0x01ULL << uTagBitIndex;
+ return (uTagBit & pItem->uTagBits) != 0;
+}
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+QCBORError QCBORDecode_Finish(QCBORDecodeContext *me)
+{
+ int nReturn = QCBOR_SUCCESS;
+
+ // Error out if all the maps/arrays are not closed out
+ if(DecodeNesting_IsNested(&(me->nesting))) {
+ nReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
+ goto Done;
+ }
+
+ // Error out if not all the bytes are consumed
+ if(UsefulInputBuf_BytesUnconsumed(&(me->InBuf))) {
+ nReturn = QCBOR_ERR_EXTRA_BYTES;
+ }
+
+Done:
+ // Call the destructor for the string allocator if there is one.
+ // Always called, even if there are errors; always have to clean up
+ if(me->pStringAllocator) {
+ QCBORStringAllocator *pAllocator = (QCBORStringAllocator *)me->pStringAllocator;
+ if(pAllocator->fDestructor) {
+ (pAllocator->fDestructor)(pAllocator->pAllocaterContext);
+ }
+ }
+
+ return nReturn;
+}
+
+
+
+/*
+
+Decoder errors handled in this file
+
+ - Hit end of input before it was expected while decoding type and number QCBOR_ERR_HIT_END
+
+ - negative integer that is too large for C QCBOR_ERR_INT_OVERFLOW
+
+ - Hit end of input while decoding a text or byte string QCBOR_ERR_HIT_END
+
+ - Encountered conflicting tags -- e.g., an item is tagged both a date string and an epoch date QCBOR_ERR_UNSUPPORTED
+
+ - Encontered an array or mapp that has too many items QCBOR_ERR_ARRAY_TOO_LONG
+
+ - Encountered array/map nesting that is too deep QCBOR_ERR_ARRAY_NESTING_TOO_DEEP
+
+ - An epoch date > INT64_MAX or < INT64_MIN was encountered QCBOR_ERR_DATE_OVERFLOW
+
+ - The type of a map label is not a string or int QCBOR_ERR_MAP_LABEL_TYPE
+
+ - Hit end with arrays or maps still open -- QCBOR_ERR_EXTRA_BYTES
+
+ */
+
+
+
+
+/*
+ This is a very primitive memory allocator. It does not track individual
+ allocations, only a high-water mark. A free or reallotcation must be of
+ the last chunk allocated.
+
+ All of this following code will get dead-stripped if QCBORDecode_SetMemPool()
+ is not called.
+ */
+
+typedef struct {
+ QCBORStringAllocator StringAllocator;
+ uint8_t *pStart; // First byte that can be allocated
+ uint8_t *pEnd; // One past the last byte that can be allocated
+ uint8_t *pFree; // Where the next free chunk is
+} MemPool;
+
+
+/*
+ Internal function for an allocation
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+ */
+static UsefulBuf MemPool_Alloc(void *ctx, void *pMem, size_t uNewSize)
+{
+ MemPool *me = (MemPool *)ctx;
+ void *pReturn = NULL;
+
+ if(pMem) {
+ // Realloc case
+ // This check will work even if uNewSize is a super-large value like UINT64_MAX
+ if((uNewSize <= (size_t)(me->pEnd - (uint8_t *)pMem)) && ((uint8_t *)pMem >= me->pStart)) {
+ me->pFree = (uint8_t *)pMem + uNewSize;
+ pReturn = pMem;
+ }
+ } else {
+ // New chunk case
+ // This check will work even if uNewSize is a super large value like UINT64_MAX
+ if(uNewSize <= (size_t)(me->pEnd - me->pFree)) {
+ pReturn = me->pFree;
+ me->pFree += uNewSize;
+ }
+ }
+
+ return (UsefulBuf){pReturn, uNewSize};
+}
+
+/*
+ Internal function to free memory
+ */
+static void MemPool_Free(void *ctx, void *pOldMem)
+{
+ MemPool *me = (MemPool *)ctx;
+ me->pFree = pOldMem;
+}
+
+/*
+ Public function, see header qcbor.h file
+ */
+QCBORError QCBORDecode_SetMemPool(QCBORDecodeContext *me, UsefulBuf Pool, bool bAllStrings)
+{
+ // The idea behind QCBOR_MIN_MEM_POOL_SIZE is
+ // that the caller knows exactly what size to
+ // allocate and that the tests can run conclusively
+ // no matter what size MemPool is
+ // even though it wastes some memory. MemPool
+ // will vary depending on pointer size of the
+ // the machine. QCBOR_MIN_MEM_POOL_SIZE is
+ // set for pointers up to 64-bits. This
+ // wastes about 50 bytes on a 32-bit machine.
+ // This check makes sure things don't go
+ // horribly wrong. It should optimize out
+ // when there is no problem as the sizes are
+ // known at compile time.
+ if(sizeof(MemPool) > QCBOR_DECODE_MIN_MEM_POOL_SIZE) {
+ return QCBOR_ERR_MEM_POOL_INTERNAL;
+ }
+
+ // The first bytes of the Pool passed in are used
+ // as the context (vtable of sorts) for the memory pool
+ // allocator.
+ if(Pool.len < QCBOR_DECODE_MIN_MEM_POOL_SIZE) {
+ return QCBOR_ERR_BUFFER_TOO_SMALL;
+ }
+ MemPool *pMP = (MemPool *)Pool.ptr;
+
+ // Fill in the "vtable"
+ pMP->StringAllocator.fAllocate = MemPool_Alloc;
+ pMP->StringAllocator.fFree = MemPool_Free;
+ pMP->StringAllocator.fDestructor = NULL;
+
+ // Set up the pointers to the memory to be allocated
+ pMP->pStart = (uint8_t *)Pool.ptr + QCBOR_DECODE_MIN_MEM_POOL_SIZE;
+ pMP->pFree = pMP->pStart;
+ pMP->pEnd = (uint8_t *)Pool.ptr + Pool.len;
+
+ // More book keeping of context
+ pMP->StringAllocator.pAllocaterContext = pMP;
+ me->pStringAllocator = pMP;
+
+ // The flag indicating when to use the allocator
+ me->bStringAllocateAll = bAllStrings;
+
+ return QCBOR_SUCCESS;
+}
+
+
+/*
+ Extra little hook to make MemPool testing work right
+ without adding any code size or overhead to non-test
+ uses. This will get dead-stripped for non-test use.
+
+ This is not a public function.
+ */
+size_t MemPoolTestHook_GetPoolSize(void *ctx)
+{
+ MemPool *me = (MemPool *)ctx;
+
+ return me->pEnd - me->pStart;
+}
+
diff --git a/lib/ext/qcbor/src/qcbor_encode.c b/lib/ext/qcbor/src/qcbor_encode.c
new file mode 100644
index 0000000..460dd85
--- /dev/null
+++ b/lib/ext/qcbor/src/qcbor_encode.c
@@ -0,0 +1,650 @@
+/*==============================================================================
+ Copyright (c) 2016-2018, The Linux Foundation.
+ Copyright (c) 2018-2019, Laurence Lundblade.
+ All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of The Linux Foundation nor the names of its
+ contributors, nor the name "Laurence Lundblade" may be used to
+ endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ==============================================================================*/
+
+/*===================================================================================
+ FILE: qcbor_encode.c
+
+ DESCRIPTION: This file contains the implementation of QCBOR.
+
+ EDIT HISTORY FOR FILE:
+
+ This section contains comments describing changes made to the module.
+ Notice that changes are listed in reverse chronological order.
+
+ when who what, where, why
+ -------- ---- ---------------------------------------------------
+ 12/30/18 llundblade Small efficient clever encode of type & argument.
+ 11/29/18 llundblade Rework to simpler handling of tags and labels.
+ 11/9/18 llundblade Error codes are now enums.
+ 11/1/18 llundblade Floating support.
+ 10/31/18 llundblade Switch to one license that is almost BSD-3.
+ 09/28/18 llundblade Added bstr wrapping feature for COSE implementation.
+ 02/05/18 llundbla Works on CPUs which require integer alignment.
+ Requires new version of UsefulBuf.
+ 07/05/17 llundbla Add bstr wrapping of maps/arrays for COSE
+ 03/01/17 llundbla More data types
+ 11/13/16 llundbla Integrate most TZ changes back into github version.
+ 09/30/16 gkanike Porting to TZ.
+ 03/15/16 llundbla Initial Version.
+
+ =====================================================================================*/
+
+#include "qcbor.h"
+#include "ieee754.h"
+
+
+/*...... This is a ruler that is 80 characters long...........................*/
+
+
+/*
+ CBOR's two nesting types, arrays and maps, are tracked here. There is a
+ limit of QCBOR_MAX_ARRAY_NESTING to the number of arrays and maps
+ that can be nested in one encoding so the encoding context stays
+ small enough to fit on the stack.
+
+ When an array / map is opened, pCurrentNesting points to the element
+ in pArrays that records the type, start position and accumluates a
+ count of the number of items added. When closed the start position is
+ used to go back and fill in the type and number of items in the array
+ / map.
+
+ Encoded output be just items like ints and strings that are
+ not part of any array / map. That is, the first thing encoded
+ does not have to be an array or a map.
+ */
+inline static void Nesting_Init(QCBORTrackNesting *pNesting)
+{
+ // assumes pNesting has been zeroed
+ pNesting->pCurrentNesting = &pNesting->pArrays[0];
+ // Implied CBOR array at the top nesting level. This is never returned,
+ // but makes the item count work correctly.
+ pNesting->pCurrentNesting->uMajorType = CBOR_MAJOR_TYPE_ARRAY;
+}
+
+inline static QCBORError Nesting_Increase(QCBORTrackNesting *pNesting,
+ uint8_t uMajorType,
+ uint32_t uPos)
+{
+ QCBORError nReturn = QCBOR_SUCCESS;
+
+ if(pNesting->pCurrentNesting == &pNesting->pArrays[QCBOR_MAX_ARRAY_NESTING]) {
+ // trying to open one too many
+ nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
+ } else {
+ pNesting->pCurrentNesting++;
+ pNesting->pCurrentNesting->uCount = 0;
+ pNesting->pCurrentNesting->uStart = uPos;
+ pNesting->pCurrentNesting->uMajorType = uMajorType;
+ }
+ return nReturn;
+}
+
+inline static void Nesting_Decrease(QCBORTrackNesting *pNesting)
+{
+ pNesting->pCurrentNesting--;
+}
+
+inline static QCBORError Nesting_Increment(QCBORTrackNesting *pNesting)
+{
+ if(1 >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
+ return QCBOR_ERR_ARRAY_TOO_LONG;
+ }
+
+ pNesting->pCurrentNesting->uCount += 1;
+
+ return QCBOR_SUCCESS;
+}
+
+inline static uint16_t Nesting_GetCount(QCBORTrackNesting *pNesting)
+{
+ // The nesting count recorded is always the actual number of individiual
+ // data items in the array or map. For arrays CBOR uses the actual item
+ // count. For maps, CBOR uses the number of pairs. This function returns
+ // the number needed for the CBOR encoding, so it divides the number of
+ // items by two for maps to get the number of pairs. This implementation
+ // takes advantage of the map major type being one larger the array major
+ // type, hence uDivisor is either 1 or 2.
+ const uint16_t uDivisor = pNesting->pCurrentNesting->uMajorType - CBOR_MAJOR_TYPE_ARRAY+1;
+
+ return pNesting->pCurrentNesting->uCount / uDivisor;
+}
+
+inline static uint32_t Nesting_GetStartPos(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting->uStart;
+}
+
+inline static uint8_t Nesting_GetMajorType(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting->uMajorType;
+}
+
+inline static int Nesting_IsInNest(QCBORTrackNesting *pNesting)
+{
+ return pNesting->pCurrentNesting == &pNesting->pArrays[0] ? 0 : 1;
+}
+
+
+
+
+/*
+ Error tracking plan -- Errors are tracked internally and not returned
+ until Finish is called. The CBOR errors are in me->uError.
+ UsefulOutBuf also tracks whether the buffer is full or not in its
+ context. Once either of these errors is set they are never
+ cleared. Only QCBOREncode_Init() resets them. Or said another way, they must
+ never be cleared or we'll tell the caller all is good when it is not.
+
+ Only one error code is reported by QCBOREncode_Finish() even if there are
+ multiple errors. The last one set wins. The caller might have to fix
+ one error to reveal the next one they have to fix. This is OK.
+
+ The buffer full error tracked by UsefulBuf is only pulled out of
+ UsefulBuf in Finish() so it is the one that usually wins. UsefulBuf
+ will never go off the end of the buffer even if it is called again
+ and again when full.
+
+ It is really tempting to not check for overflow on the count in the
+ number of items in an array. It would save a lot of code, it is
+ extremely unlikely that any one will every put 65,000 items in an
+ array, and the only bad thing that would happen is the CBOR would be
+ bogus.
+
+ Since this does not parse any input, you could in theory remove all
+ error checks in this code if you knew the caller called it
+ correctly. Maybe someday CDDL or some such language will be able to
+ generate the code to call this and the calling code would always be
+ correct. This could also automatically size some of the data
+ structures like array/map nesting resulting in some stack memory
+ savings.
+
+ Errors returned here fall into two categories:
+
+ Sizes
+ QCBOR_ERR_BUFFER_TOO_LARGE -- Encoded output exceeded UINT32_MAX
+ QCBOR_ERR_BUFFER_TOO_SMALL -- output buffer too small
+
+ QCBOR_ERR_ARRAY_NESTING_TOO_DEEP -- Array/map nesting > QCBOR_MAX_ARRAY_NESTING1
+ QCBOR_ERR_ARRAY_TOO_LONG -- Too many things added to an array/map
+
+ Nesting constructed incorrectly
+ QCBOR_ERR_TOO_MANY_CLOSES -- more close calls than opens
+ QCBOR_ERR_CLOSE_MISMATCH -- Type of close does not match open
+ QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN -- Finish called without enough closes
+ */
+
+
+
+
+/*
+ Public function for initialization. See header qcbor.h
+ */
+void QCBOREncode_Init(QCBOREncodeContext *me, UsefulBuf Storage)
+{
+ memset(me, 0, sizeof(QCBOREncodeContext));
+ UsefulOutBuf_Init(&(me->OutBuf), Storage);
+ Nesting_Init(&(me->nesting));
+}
+
+
+
+
+/*
+ All CBOR data items have a type and an "argument". The argument is
+ either the value of the item for integer types, the length of the
+ content for string, byte, array and map types, a tag for major type
+ 6, and has several uses for major type 7.
+
+ This function encodes the type and the argument. There are several
+ encodings for the argument depending on how large it is and how it is
+ used.
+
+ Every encoding of the type and argument has at least one byte, the
+ "initial byte".
+
+ The top three bits of the initial byte are the major type for the
+ CBOR data item. The eight major types defined by the standard are
+ defined as CBOR_MAJOR_TYPE_xxxx in qcbor.h.
+
+ The remaining five bits, known as "additional information", and
+ possibly more bytes encode the argument. If the argument is less than
+ 24, then it is encoded entirely in the five bits. This is neat
+ because it allows you to encode an entire CBOR data item in 1 byte
+ for many values and types (integers 0-23, true, false, and tags).
+
+ If the argument is larger than 24, then it is encoded in 1,2,4 or 8
+ additional bytes, with the number of these bytes indicated by the
+ values of the 5 bits 24, 25, 25 and 27.
+
+ It is possible to encode a particular argument in many ways with this
+ representation. This implementation always uses the smallest
+ possible representation. This conforms with CBOR preferred encoding.
+
+ This function inserts them into the output buffer at the specified
+ position. AppendEncodedTypeAndNumber() appends to the end.
+
+ This function takes care of converting to network byte order.
+
+ This function is also used to insert floats and doubles. Before this
+ function is called the float or double must be copied into a
+ uint64_t. That is how they are passed in. They are then converted to
+ network byte order correctly. The uMinLen param makes sure that even
+
+ if all the digits of a half, float or double are 0 it is still
+ correctly encoded in 2, 4 or 8 bytes.
+ */
+
+static void InsertEncodedTypeAndNumber(QCBOREncodeContext *me,
+ uint8_t uMajorType,
+ int nMinLen,
+ uint64_t uNumber,
+ size_t uPos)
+{
+ /*
+ This code does endian conversion without hton or knowing the
+ endianness of the machine using masks and shifts. This avoids the
+ dependency on hton and the mess of figuring out how to find the
+ machine's endianness.
+
+ This is a good efficient implementation on little-endian machines.
+ A faster and small implementation is possible on big-endian
+ machines because CBOR/network byte order is big endian. However
+ big endian machines are uncommon.
+
+ On x86, it is about 200 bytes instead of 500 bytes for the more
+ formal unoptimized code.
+
+ This also does the CBOR preferred shortest encoding for integers
+ and is called to do endian conversion for floats.
+
+ It works backwards from the LSB to the MSB as needed.
+
+ Code Reviewers: THIS FUNCTION DOES POINTER MATH
+ */
+ // Holds up to 9 bytes of type and argument
+ // plus one extra so pointer always points to
+ // valid bytes.
+ uint8_t bytes[sizeof(uint64_t)+2];
+ // Point to the last bytes and work backwards
+ uint8_t *pByte = &bytes[sizeof(bytes)-1];
+ // This is the 5 bits in the initial byte that is not the major type
+ uint8_t uAdditionalInfo;
+
+ if(uNumber < CBOR_TWENTY_FOUR && nMinLen == 0) {
+ // Simple case where argument is < 24
+ uAdditionalInfo = uNumber;
+ } else {
+ /*
+ Encode argument in 1,2,4 or 8 bytes. Outer loop
+ runs once for 1 byte and 4 times for 8 bytes.
+ Inner loop runs 1, 2 or 4 times depending on
+ outer loop counter. This works backwards taking
+ 8 bits off the argument being encoded at a time
+ until all bits from uNumber have been encoded
+ and the minimum encoding size is reached.
+ Minimum encoding size is for floating point
+ numbers with zero bytes.
+ */
+ static const uint8_t aIterate[] = {1,1,2,4};
+ uint8_t i;
+ for(i = 0; uNumber || nMinLen > 0; i++) {
+ const uint8_t uIterations = aIterate[i];
+ for(int j = 0; j < uIterations; j++) {
+ *--pByte = uNumber & 0xff;
+ uNumber = uNumber >> 8;
+ }
+ nMinLen -= uIterations;
+ }
+ // Additional info is the encoding of the
+ // number of additional bytes to encode
+ // argument.
+ uAdditionalInfo = LEN_IS_ONE_BYTE-1 + i;
+ }
+ *--pByte = (uMajorType << 5) + uAdditionalInfo;
+
+ UsefulOutBuf_InsertData(&(me->OutBuf), pByte, &bytes[sizeof(bytes)-1] - pByte, uPos);
+}
+
+
+/*
+ Append the type and number info to the end of the buffer.
+
+ See InsertEncodedTypeAndNumber() function above for details
+*/
+inline static void AppendEncodedTypeAndNumber(QCBOREncodeContext *me,
+ uint8_t uMajorType,
+ uint64_t uNumber)
+{
+ // An append is an insert at the end.
+ InsertEncodedTypeAndNumber(me,
+ uMajorType,
+ 0,
+ uNumber,
+ UsefulOutBuf_GetEndPosition(&(me->OutBuf)));
+}
+
+
+
+
+/*
+ Public functions for closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_AddUInt64(QCBOREncodeContext *me, uint64_t uValue)
+{
+ if(me->uError == QCBOR_SUCCESS) {
+ AppendEncodedTypeAndNumber(me, CBOR_MAJOR_TYPE_POSITIVE_INT, uValue);
+ me->uError = Nesting_Increment(&(me->nesting));
+ }
+}
+
+
+/*
+ Public functions for closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_AddInt64(QCBOREncodeContext *me, int64_t nNum)
+{
+ if(me->uError == QCBOR_SUCCESS) {
+ uint8_t uMajorType;
+ uint64_t uValue;
+
+ if(nNum < 0) {
+ // In CBOR -1 encodes as 0x00 with major type negative int.
+ uValue = (uint64_t)(-nNum - 1);
+ uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
+ } else {
+ uValue = (uint64_t)nNum;
+ uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
+ }
+
+ AppendEncodedTypeAndNumber(me, uMajorType, uValue);
+ me->uError = Nesting_Increment(&(me->nesting));
+ }
+}
+
+
+/*
+ Semi-private function. It is exposed to user of the interface,
+ but they will usually call one of the inline wrappers rather than this.
+
+ See header qcbor.h
+
+ Does the work of adding some bytes to the CBOR output. Works for a
+ byte and text strings, which are the same in in CBOR though they have
+ different major types. This is also used to insert raw
+ pre-encoded CBOR.
+ */
+void QCBOREncode_AddBuffer(QCBOREncodeContext *me, uint8_t uMajorType, UsefulBufC Bytes)
+{
+ if(me->uError == QCBOR_SUCCESS) {
+ // If it is not Raw CBOR, add the type and the length
+ if(uMajorType != CBOR_MAJOR_NONE_TYPE_RAW) {
+ AppendEncodedTypeAndNumber(me, uMajorType, Bytes.len);
+ }
+
+ // Actually add the bytes
+ UsefulOutBuf_AppendUsefulBuf(&(me->OutBuf), Bytes);
+
+ // Update the array counting if there is any nesting at all
+ me->uError = Nesting_Increment(&(me->nesting));
+ }
+}
+
+
+/*
+ Public functions for closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_AddTag(QCBOREncodeContext *me, uint64_t uTag)
+{
+ AppendEncodedTypeAndNumber(me, CBOR_MAJOR_TYPE_OPTIONAL, uTag);
+}
+
+
+/*
+ Semi-private function. It is exposed to user of the interface,
+ but they will usually call one of the inline wrappers rather than this.
+
+ See header qcbor.h
+ */
+void QCBOREncode_AddType7(QCBOREncodeContext *me, size_t uSize, uint64_t uNum)
+{
+ if(me->uError == QCBOR_SUCCESS) {
+ // This function call takes care of endian swapping for the float / double
+ InsertEncodedTypeAndNumber(me,
+ // The major type for floats and doubles
+ CBOR_MAJOR_TYPE_SIMPLE,
+ // size makes sure floats with zeros encode correctly
+ (int)uSize,
+ // Bytes of the floating point number as a uint
+ uNum,
+ // end position because this is append
+ UsefulOutBuf_GetEndPosition(&(me->OutBuf)));
+
+ me->uError = Nesting_Increment(&(me->nesting));
+ }
+}
+
+
+/*
+ Public functions for closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_AddDouble(QCBOREncodeContext *me, double dNum)
+{
+ const IEEE754_union uNum = IEEE754_DoubleToSmallest(dNum);
+
+ QCBOREncode_AddType7(me, uNum.uSize, uNum.uValue);
+}
+
+
+/*
+ Semi-public function. It is exposed to user of the interface,
+ but they will usually call one of the inline wrappers rather than this.
+
+ See header qcbor.h
+*/
+void QCBOREncode_OpenMapOrArray(QCBOREncodeContext *me, uint8_t uMajorType)
+{
+ // Add one item to the nesting level we are in for the new map or array
+ me->uError = Nesting_Increment(&(me->nesting));
+ if(me->uError == QCBOR_SUCCESS) {
+ // The offset where the length of an array or map will get written
+ // is stored in a uint32_t, not a size_t to keep stack usage smaller. This
+ // checks to be sure there is no wrap around when recording the offset.
+ // Note that on 64-bit machines CBOR larger than 4GB can be encoded as long as no
+ // array / map offsets occur past the 4GB mark, but the public interface
+ // says that the maximum is 4GB to keep the discussion simpler.
+ size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
+
+ // QCBOR_MAX_ARRAY_OFFSET is slightly less than UINT32_MAX so this
+ // code can run on a 32-bit machine and tests can pass on a 32-bit
+ // machine. If it was exactly UINT32_MAX, then this code would
+ // not compile or run on a 32-bit machine and an #ifdef or some
+ // machine size detection would be needed reducing portability.
+ if(uEndPosition >= QCBOR_MAX_ARRAY_OFFSET) {
+ me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
+
+ } else {
+ // Increase nesting level because this is a map or array.
+ // Cast from size_t to uin32_t is safe because of check above
+ me->uError = Nesting_Increase(&(me->nesting), uMajorType, (uint32_t)uEndPosition);
+ }
+ }
+}
+
+
+/*
+ Public functions for closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_CloseMapOrArray(QCBOREncodeContext *me,
+ uint8_t uMajorType,
+ UsefulBufC *pWrappedCBOR)
+{
+ if(me->uError == QCBOR_SUCCESS) {
+ if(!Nesting_IsInNest(&(me->nesting))) {
+ me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
+ } else if(Nesting_GetMajorType(&(me->nesting)) != uMajorType) {
+ me->uError = QCBOR_ERR_CLOSE_MISMATCH;
+ } else {
+ // When the array, map or bstr wrap was started, nothing was done
+ // except note the position of the start of it. This code goes back
+ // and inserts the actual CBOR array, map or bstr and its length.
+ // That means all the data that is in the array, map or wrapped
+ // needs to be slid to the right. This is done by UsefulOutBuf's
+ // insert function that is called from inside
+ // InsertEncodedTypeAndNumber()
+ const size_t uInsertPosition = Nesting_GetStartPos(&(me->nesting));
+ const size_t uEndPosition = UsefulOutBuf_GetEndPosition(&(me->OutBuf));
+ // This can't go negative because the UsefulOutBuf always only grows
+ // and never shrinks. UsefulOutBut itself also has defenses such that
+ // it won't write were it should not even if given hostile input lengths
+ const size_t uLenOfEncodedMapOrArray = uEndPosition - uInsertPosition;
+
+ // Length is number of bytes for a bstr and number of items a for map & array
+ const size_t uLength = uMajorType == CBOR_MAJOR_TYPE_BYTE_STRING ?
+ uLenOfEncodedMapOrArray : Nesting_GetCount(&(me->nesting));
+
+ // Actually insert
+ InsertEncodedTypeAndNumber(me,
+ uMajorType, // major type bstr, array or map
+ 0, // no minimum length for encoding
+ uLength, // either len of bstr or num map / array items
+ uInsertPosition); // position in out buffer
+
+ // Return pointer and length to the enclosed encoded CBOR. The intended
+ // use is for it to be hashed (e.g., SHA-256) in a COSE implementation.
+ // This must be used right away, as the pointer and length go invalid
+ // on any subsequent calls to this function because of the
+ // InsertEncodedTypeAndNumber() call that slides data to the right.
+ if(pWrappedCBOR) {
+ const UsefulBufC PartialResult = UsefulOutBuf_OutUBuf(&(me->OutBuf));
+ const size_t uBstrLen = UsefulOutBuf_GetEndPosition(&(me->OutBuf)) - uEndPosition;
+ *pWrappedCBOR = UsefulBuf_Tail(PartialResult, uInsertPosition+uBstrLen);
+ }
+ Nesting_Decrease(&(me->nesting));
+ }
+ }
+}
+
+
+
+
+/*
+ Public functions to finish and get the encoded result. See header qcbor.h
+ */
+QCBORError QCBOREncode_Finish(QCBOREncodeContext *me, UsefulBufC *pEncodedCBOR)
+{
+ QCBORError uReturn = me->uError;
+
+ if(uReturn != QCBOR_SUCCESS) {
+ goto Done;
+ }
+
+ if (Nesting_IsInNest(&(me->nesting))) {
+ uReturn = QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN;
+ goto Done;
+ }
+
+ if(UsefulOutBuf_GetError(&(me->OutBuf))) {
+ // Stuff didn't fit in the buffer.
+ // This check catches this condition for all the appends and inserts
+ // so checks aren't needed when the appends and inserts are performed.
+ // And of course UsefulBuf will never overrun the input buffer given
+ // to it. No complex analysis of the error handling in this file is
+ // needed to know that is true. Just read the UsefulBuf code.
+ uReturn = QCBOR_ERR_BUFFER_TOO_SMALL;
+ goto Done;
+ }
+
+ *pEncodedCBOR = UsefulOutBuf_OutUBuf(&(me->OutBuf));
+
+Done:
+ return uReturn;
+}
+
+
+/*
+ Public functions to finish and get the encoded result. See header qcbor.h
+ */
+QCBORError QCBOREncode_FinishGetSize(QCBOREncodeContext *me, size_t *puEncodedLen)
+{
+ UsefulBufC Enc;
+
+ QCBORError nReturn = QCBOREncode_Finish(me, &Enc);
+
+ if(nReturn == QCBOR_SUCCESS) {
+ *puEncodedLen = Enc.len;
+ }
+
+ return nReturn;
+}
+
+
+
+
+/*
+ Notes on the code
+
+ CBOR Major Type Public Function
+ 0 QCBOREncode_AddUInt64
+ 0, 1 QCBOREncode_AddUInt64, QCBOREncode_AddInt64
+ 2, 3 QCBOREncode_AddBuffer, Also QCBOREncode_OpenMapOrArray
+ 4, 5 QCBOREncode_OpenMapOrArray
+ 6 QCBOREncode_AddTag
+ 7 QCBOREncode_AddDouble, QCBOREncode_AddType7
+
+ Object code sizes on X86 with LLVM compiler and -Os (Dec 30, 2018)
+
+ _QCBOREncode_Init 69
+ _QCBOREncode_AddUInt64 76
+ _QCBOREncode_AddInt64 87
+ _QCBOREncode_AddBuffer 113
+ _QCBOREncode_AddTag 27
+ _QCBOREncode_AddType7 87
+ _QCBOREncode_AddDouble 36
+ _QCBOREncode_OpenMapOrArray 103
+ _QCBOREncode_CloseMapOrArray 181
+ _InsertEncodedTypeAndNumber 190
+ _QCBOREncode_Finish 72
+ _QCBOREncode_FinishGetSize 70
+
+ Total is about 1.1KB
+
+ _QCBOREncode_CloseMapOrArray is larger because it has a lot
+ of nesting tracking to do and much of Nesting_ inlines
+ into it. It probably can't be reduced much.
+
+ If the error returned by Nesting_Increment() can be ignored
+ because the limit is so high and the consequence of exceeding
+ is proved to be inconsequential, then a lot of if(me->uError)
+ instance can be removed, saving some code.
+
+ */
+