Initial drop from Qualcomm / CAF
diff --git a/inc/UsefulBuf.h b/inc/UsefulBuf.h
new file mode 100644
index 0000000..aed6644
--- /dev/null
+++ b/inc/UsefulBuf.h
@@ -0,0 +1,1332 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. 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 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.h
+ 
+ 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
+ --------           ----            ---------------------------------------------------
+ 02/02/18           llundbla        Full support for integers in and out; fix pointer alignment bug
+                                    Incompatible change: integers in/out are now in network byte order.
+ 08/12/17           llundbla        Added UsefulOutBuf_AtStart and UsefulBuf_Find
+ 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.
+
+ 
+ =====================================================================================*/
+
+#ifndef _UsefulBuf_h
+#define _UsefulBuf_h
+
+
+#include <stdint.h>
+#include <string.h>
+#include <stddef.h> // for size_t
+
+/**
+ 
+ The goal of this code is to make buffer and pointer manipulation
+ easier and safer.
+ 
+ The idea is that you use the UsefulBuf, UsefulOutBuf and UsefulInputBuf 
+ structures to represent buffers rather than ad hoc pointers and lengths.
+ 
+ With these it will often be possible to write code that does little or no
+ direct pointer manipulation for copying and formating data. For example
+ the QCBOR encoder was rewritten using these and only one simple function
+ remains that does any pointer manipulation.
+ 
+ While it is true that object code using these functions will be a little
+ larger and slower than a white-knuckle clever use of pointers might be, but
+ not by that much or enough to have an affect for must use cases. For
+ security-oriented code this is highly worthwhile. Clarity, simplicity,
+ reviwability and certainty are more important.
+
+ There are some extra sanity and double checks in this code to help catch
+ coding errors and simple memory corruption. They are helpful, but not a
+ substitute for proper code review, input validation and such.
+
+ This code has a lot of simple small functions to hopefully create clarity
+ about what it does so it is easier to review. UsefulOutBuf and UsefulInBuf 
+ are also objects in a form (a largely private data structure and accessor 
+ functions). Most of the code is marked inline and presumably compilers
+ will do a good job on optimizing all this. (In theory they should, though
+ this has not been verified yet).
+ 
+ */
+
+
+/**
+ 
+ UsefulBuf is a simple data structure to hold a pointer and length for
+ a binary data.  In C99 this data structure can be passed on the stack
+ making a lot of code cleaner than carrying around a pointer and
+ length as two parameters.
+ 
+ This is also conducive to secure code practice as the lengths are
+ always carried with the the pointer and the convention for handling a
+ pointer and a length is clear.
+ 
+ While it might be possible to write buffer and pointer code more
+ efficiently in some use cases, the thought is that unless there is an
+ extreme need for performance (e.g. you are building a
+ gigabit-per-second IP router), it is probably better to have cleaner
+ code you can be most certain about the security of.
+ 
+ The len field is the length of the valid data pointed to.
+ 
+ There is also a const version of it when the data is const.
+ 
+ A UsefulBuf is NULL, it has no value, when the ptr in it is NULL.
+ 
+ There are only a few utility functions and macros associated with 
+ UsefulBuf.
+ 
+ See also UsefulOutBuf. It is a richer structure that has both the
+ size of the valid data and the size of the buffer.
+ 
+ Struct is 16 or 8 bytes on a 64 or 32 bit machine so it can go on the
+ stack and be a function parameter or return value.
+ 
+ UsefulBuf is kind of like the Useful Pot Pooh gave Eeyore on his
+ birthday. Eeyore's ballon fits beautifully, "it goes in and out like
+ anything".
+ 
+*/
+
+typedef struct __UsefulBuf {
+   void  *ptr;
+   size_t len;
+} UsefulBuf;
+
+
+typedef struct __UsefulBufC {
+   const void *ptr;
+   size_t      len;
+} UsefulBufC;
+
+
+
+
+/**
+ @brief Convert a non const UsefulBuf to a const UsefulBufC
+ 
+ @param[in] UB The UsefulBuf to convert
+ 
+ Returns: a UsefulBufC struct
+ */
+
+static inline UsefulBufC UsefulBuf_Const(const UsefulBuf UB)
+{
+   return (UsefulBufC){UB.ptr, UB.len};
+}
+
+// Old form. Should be deprecated.
+static inline UsefulBufC UsefulBufConst(const UsefulBuf UB)
+{
+   return (UsefulBufC){UB.ptr, UB.len};
+}
+
+
+/**
+ @brief Convert a const UsefulBufC to a non-const UsefulBuf
+ 
+ @param[in] UBC The UsefulBuf to convert
+ 
+ Returns: a non const UsefulBuf struct
+ */
+static inline UsefulBuf UsefulBufC_Unconst(const UsefulBufC UBC)
+{
+   return (UsefulBuf){(void *)UBC.ptr, UBC.len};
+}
+
+
+/**
+  A "NULL" UsefulBuf is one that has no value in the same way a NULL pointer has no value.
+  A UsefulBuf is NULL when the ptr field is NULL. It doesn't matter what len is.
+ */
+#define UsefulBuf_IsNULL(UB)  (!(UB).ptr)
+
+#define NULLUsefulBufC        ((UsefulBufC) {NULL, 0})
+
+#define NULLUsefulBuf         ((UsefulBuf) {NULL, 0})
+
+
+/*
+ An "Empty" UsefulBuf is one that has a value and can be considered to be set,
+ but that value is of zero length.  It is empty when len is zero. It 
+ doesn't matter what the ptr is. 
+ 
+ A lot of uses will not need to clearly distinguish a NULL UsefulBuf
+ from an empty one and can have the ptr NULL and the len 0.  However
+ if a use of UsefulBuf needs to make a distinction then ptr should
+ not be NULL when the UsefulBuf is considered empty, but not NULL.
+ */
+
+#define UsefulBuf_IsEmpty(UB)  (!(UB).len)
+
+#define UsefulBuf_IsNULLOrEmpty(UB) (UsefulBuf_IsNULL(UB) || UsefulBuf_IsEmpty(UB))
+
+
+
+
+/**
+ @brief Convert a NULL terminated string to a UsefulBufC.
+
+ @param[in] szString The string to convert
+ 
+ @return a UsefulBufC struct
+
+ UsefulBufC.ptr points to the string so it's lifetime
+ must be maintained.
+ 
+ The terminating \0 (NULL) is NOT included in the length!
+ 
+ */
+static inline UsefulBufC SZToUsefulBufC(const char *szString){
+   return ((UsefulBufC) {szString, strlen(szString)});
+}
+
+
+/**
+ @brief Copy one UsefulBuf into another
+ 
+ @param[in] pDest The destination buffer to copy into
+ @param[out] Src  The source to copy from
+ 
+ @return 0 on success, 1 on failure
+ 
+ This fails and returns 1 if Src.len is greater than
+ pDest->len.
+ 
+ Note that like memcpy, the pointers are not checked and
+ this will crash, rather than return 1 if they are NULL
+ or invalid.
+ 
+ */
+int UsefulBuf_Copy(UsefulBuf *pDest, const UsefulBufC Src);
+
+
+
+/**
+ @brief Set all bytes in a UsefulBuf to a value, for example 0
+ 
+ @param[in] pDest The destination buffer to copy into
+ @param[in] value The value to set the bytes to
+ 
+ Note that like memset, the pointer in pDest is not checked and
+ this will crash if NULL or invalid.
+ 
+ */
+void UsefulBuf_Set(UsefulBuf *pDest, uint8_t value);
+
+
+
+/**
+ @brief Copy a pointer into a UsefulBuf
+ 
+ @param[in] pDest The destination buffer to copy into
+ @param[out] Src  The source to copy from
+ 
+ @return 0 on success, 1 on failure
+ 
+ This fails and returns 1 if Src.len is greater than
+ pDest->len.
+ 
+ Note that like memcpy, the pointers are not checked and
+ this will crash, rather than return 1 if they are NULL
+ or invalid.
+ 
+ */
+inline static int UsefulBuf_CopyPtr(UsefulBuf *pDest, const void *ptr, size_t len)
+{
+   return UsefulBuf_Copy(pDest, (UsefulBufC){ptr, len});
+}
+
+
+/**
+ @brief Compare two UsefulBufs
+ 
+ @param[in] UB1 The destination buffer to copy into
+ @param[in] UB2  The source to copy from
+ 
+ @return 0 if equal...
+ 
+ Returns a negative value if UB1 if is less than UB2. UB1 is
+ less than UB2 if it is shorter or the first byte that is not
+ the same is less. 
+ 
+ Returns 0 if the UsefulBufs are the same.
+ 
+ Returns a positive value if UB2 is less than UB1.
+ 
+ All that is of significance is that the result is positive,
+ negative or 0. (This doesn't return the difference between
+ the first non-matching byte like memcmp).
+ 
+ */
+int UsefulBuf_Compare(const UsefulBufC UB1, const UsefulBufC UB2);
+
+
+/*
+ @brief Find one UsefulBuf in another
+ 
+ @param[in] BytesToSearch  UsefulBuf to search through
+ @param[in] BytesToFind    UsefulBuf with bytes to be found
+ 
+ @return position of found bytes or SIZE_MAX if not found.
+ 
+ */
+size_t UsefulBuf_FindBytes(UsefulBufC BytesToSearch, UsefulBufC BytesToFind);
+
+
+
+/**
+ Convert a literal string to a UsefulBufC.
+ 
+ szString must be a literal string that you can take sizeof. 
+ This is better for literal strings than SZToUsefulBufC
+ because it generates less code. It will not work on
+ non-literal strings.
+ 
+ The terminating \0 (NULL) is NOT included in the length!
+
+ */
+#define SZLiteralToUsefulBufC(szString) \
+      ((UsefulBufC) {(szString), sizeof(szString)-1})
+
+
+/**
+ Convert a literal byte array to a UsefulBufC.
+ 
+ pBytes must be a literal string that you can take sizeof.
+ It will not work on  non-literal strings.
+ 
+ */
+#define ByteArrayLiteralToUsefulBufC(pBytes) \
+      ((UsefulBufC) {(pBytes), sizeof(pBytes)})
+
+
+// Make an automatic variable with name of type UsefulBuf and point it to a stack
+// variable of the give size
+#define  MakeUsefulBufOnStack(name, size) \
+   uint8_t    __pBuf##name[(size)];\
+   UsefulBuf  name = {__pBuf##name , sizeof( __pBuf##name )}
+
+
+
+
+/**
+ UsefulOutBuf is a structure and functions (an object) that are good
+ for serializing data into a buffer such as is often done with network
+ protocols or data written to files.
+ 
+ The main idea is that all the pointer manipulation for adding data is
+ done by UsefulOutBuf functions so the caller doesn't have to do any.
+ All the pointer manipulation is centralized here.  This code will
+ have been reviewed and written carefully so it spares the caller of
+ much of this work and results in much safer code with much less work.
+ 
+ The functions to add data to the output buffer always check the
+ length and will never write off the end of the output buffer. If an
+ attempt to add data that will not fit is made, an internal error flag
+ will be set and further attempts to add data will not do anything.
+ 
+ Basically, if you initialized with the correct buffer, there is no
+ way to ever write off the end of that buffer when calling the Add
+ and Insert functions here.
+ 
+ The functions to add data do not return an error. The working model
+ is that the caller just makes all the calls to add data without any
+ error checking on each one. The error is instead checked after all the
+ data is added when the result is to be used.  This makes the callers
+ code cleaner.
+ 
+ There is a utility function to get the error status anytime along the
+ way if the caller wants. There are functions to see how much room is
+ left and see if some data will fit too, but their use is generally
+ not necessary.
+ 
+ The generall calling flow is like this:
+
+    - Initialize the UsefulOutBuf with the buffer that is to have the
+      data added.  The caller allocates the buffer.  It can be heap
+      or stack or shared memory (or other).
+    
+    - Make calls to add data to the output buffer. Insert and append
+      are both supported. The append and insert calls will never write
+      off the end of the buffer.
+    
+    - When all data is added, check the error status to make sure
+      everything fit.
+    
+    - Get the resulting serialized data either as a UsefulBuf (a
+      pointer and length) or have it copied to another buffer.
+ 
+ UsefulOutBuf can be initialized with just a buffer length by passing
+ NULL as the pointer to the output buffer. This is useful if you want
+ to go through the whole serialization process to either see if it
+ will fit into a given buffer or compute the size of the buffer
+ needed. Pass a very large buffer size when callint Init, if you want
+ just to compute the size.
+ 
+ Some inexpensive simple sanity checks are performed before every data
+ addtion to gaurd against use of an uninitialized or corrupted
+ UsefulOutBuf.
+ 
+ This has been used to create a CBOR encoder. The CBOR encoder has
+ almost no pointer manipulation in it, is much easier to read, and
+ easier to review.
+ 
+ A UsefulOutBuf is 27 bytes or 15 bytes on 64 or 32 bit machines so it
+ can go on the stack or be a C99 function parameter.
+ */
+
+typedef struct __UsefulOutBuf {
+   UsefulBuf  UB;
+   size_t     size;  // size of the buffer (not the valid data in the buffer)
+   uint16_t   magic; // Used to detect corruption and lack of initialization
+   uint8_t    err;
+} UsefulOutBuf;
+
+
+/**
+ @brief Initialize and supply the actual output buffer
+ 
+ @param[out] pOutBuf The UsefulOutBuf to initialize
+ @param[in] pStorage Pointer to data buffer to use
+ @param[in] nStorageSize Size of buffer pStorage
+ 
+ @return None
+ 
+ Intializes the UsefulOutBuf with storage. Sets the current position
+ to the beginning of the buffer clears the error.
+ 
+ This must be called before the UsefulOutBuf is used.
+ */
+void UsefulOutBuf_Init(UsefulOutBuf *me, void *pStorage, size_t uStorageSize);
+
+
+
+/** Convenience marco to make a UsefulOutBuf on the stack and
+   initialize it with stack buffer
+ */
+#define  MakeUsefulOutBufOnStack(name, size) \
+   uint8_t       __pBuf##name[(size)];\
+   UsefulOutBuf  name;\
+   UsefulOutBuf_Init(&(name), __pBuf##name, (size));
+
+
+
+/**
+ @brief Reset a UsefulOutBuf for re use
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+
+ This sets the amount of data in the output buffer to none and
+ clears the error state.  
+ 
+ The output buffer is still the same one and size as from the
+ UsefulOutBuf_Init() call.
+ 
+ It doesn't zero the data, just resets to 0 bytes of valid data.
+ */
+static inline void UsefulOutBuf_Reset(UsefulOutBuf *me)
+{
+   me->UB.len = 0;
+   me->err    = 0;
+}
+
+
+/**
+ @brief Returns position of end of data in the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ 
+ @return position of end of data
+ 
+ On a freshly initialized UsefulOutBuf with no data added, this will
+ return 0. After ten bytes have been added, it will return 10 and so
+ on.
+ 
+ Generally callers will not need this function for most uses of
+ UsefulOutBuf.
+ 
+ */
+static inline size_t UsefulOutBuf_GetEndPosition(UsefulOutBuf *me)
+{
+   return me->UB.len;
+}
+
+
+/**
+ @brief Returns whether any data has been added to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ 
+ @return 1 if output position is at start
+ 
+ */
+static inline int UsefulOutBuf_AtStart(UsefulOutBuf *me)
+{
+   return 0 == me->UB.len;
+}
+
+
+/**
+ @brief Inserts bytes into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] NewData UsefulBuf with the bytes to insert
+ @param[in] uPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ NewData is the pointer and length for the bytes to be added to the
+ output buffer. There must be room in the output buffer for all of
+ NewData or an error will occur.
+ 
+ The insertion point must be between 0 and the current valid data. If
+ not an error will occur. Appending data to the output buffer is
+ achieved by inserting at the end of the valid data. This can be
+ retrieved by calling UsefulOutBuf_GetEndPosition().
+ 
+ When insertion is performed, the bytes between the insertion point and
+ the end of data previously added to the output buffer is slid to the
+ right to make room for the new data.
+ 
+ Overlapping buffers are OK. NewData can point to data in the output
+ buffer.
+
+ If an error occurs an error state is set in the UsefulOutBuf. No
+ error is returned.  All subsequent attempts to add data will do
+ nothing.
+ 
+ Call UsefulOutBuf_GetError() to find out if there is an error. This
+ is usually not needed until all additions of data are complete.
+ 
+ */
+void UsefulOutBuf_InsertUsefulBuf(UsefulOutBuf *me, UsefulBufC NewData, size_t uPos);
+
+
+/**
+ @brief Insert a data buffer into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] pBytes Pointer to the bytes to insert
+ @param[in] uLen Length of the bytes to insert
+ @param[in] uPos Index in output buffer at which to insert
+
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a pointer and length is passed in rather than an
+ UsefulBuf.
+ 
+ */
+
+static inline void UsefulOutBuf_InsertData(UsefulOutBuf *me, const void *pBytes, size_t uLen, size_t uPos)
+{
+   UsefulBufC Data = {pBytes, uLen};
+   UsefulOutBuf_InsertUsefulBuf(me, Data, uPos);
+}
+
+
+/**
+ @brief Insert a NULL-terminated string into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] szString string to append
+ 
+ @return None
+ */
+static inline void UsefulOutBuf_InsertString(UsefulOutBuf *me, const char *szString, size_t uPos)
+{
+   UsefulOutBuf_InsertUsefulBuf(me, (UsefulBufC){szString, strlen(szString)}, uPos);
+}
+
+
+/**
+ @brief Insert a byte into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] pByte Bytes to insert
+ @param[in] nPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a single byte is to be inserted.
+ */
+static inline void UsefulOutBuf_InsertByte(UsefulOutBuf *me, uint8_t byte, size_t uPos)
+{
+   UsefulOutBuf_InsertData(me, &byte, 1, uPos);
+}
+
+
+/**
+ @brief Insert a 16-bit integer into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] uInteger16 Integer to insert
+ @param[in] nPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a single byte is to be inserted.
+ 
+ The integer will be inserted in network byte order (big endian)
+ */
+static inline void UsefulOutBuf_InsertUint16(UsefulOutBuf *me, uint16_t uInteger16, size_t uPos)
+{
+   // Converts native integer format to network byte order (big endian)
+   uint8_t tmp[2];
+   tmp[0] = (uInteger16 & 0xff00) >> 8;
+   tmp[1] = (uInteger16 & 0xff);
+   UsefulOutBuf_InsertData(me, tmp, 2, uPos);
+}
+
+
+/**
+ @brief Insert a 32-bit integer into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] uInteger32 Integer to insert
+ @param[in] nPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a single byte is to be inserted.
+ 
+ The integer will be inserted in network byte order (big endian)
+ */
+static inline void UsefulOutBuf_InsertUint32(UsefulOutBuf *me, uint32_t uInteger32, size_t uPos)
+{
+   // Converts native integer format to network byte order (big endian)
+   uint8_t tmp[4];
+   tmp[0] = (uInteger32 & 0xff000000) >> 24;
+   tmp[1] = (uInteger32 & 0xff0000) >> 16;
+   tmp[2] = (uInteger32 & 0xff00) >> 8;
+   tmp[3] = (uInteger32 & 0xff);
+   UsefulOutBuf_InsertData(me, tmp, 4, uPos);
+}
+
+
+/**
+ @brief Insert a 64-bit integer into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] uInteger64 Integer to insert
+ @param[in] nPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a single byte is to be inserted.
+ 
+ The integer will be inserted in network byte order (big endian)
+ */
+static inline void UsefulOutBuf_InsertUint64(UsefulOutBuf *me, uint64_t uInteger64, size_t uPos)
+{
+   // Converts native integer format to network byte order (big endian)
+   uint8_t tmp[8];
+   tmp[0] = (uInteger64 & 0xff00000000000000) >> 56;
+   tmp[1] = (uInteger64 & 0xff000000000000) >> 48;
+   tmp[2] = (uInteger64 & 0xff0000000000) >> 40;
+   tmp[3] = (uInteger64 & 0xff00000000) >> 32;
+   tmp[4] = (uInteger64 & 0xff000000) >> 24;
+   tmp[5] = (uInteger64 & 0xff0000) >> 16;
+   tmp[6] = (uInteger64 & 0xff00) >> 8;
+   tmp[7] = (uInteger64 & 0xff);
+   UsefulOutBuf_InsertData(me, tmp, 8, uPos);
+}
+
+
+/**
+ @brief Insert a float into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] f Integer to insert
+ @param[in] nPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a single byte is to be inserted.
+ 
+ The float will be inserted in network byte order (big endian)
+ */
+static inline void UsefulOutBuf_InsertFloat(UsefulOutBuf *me, float f, size_t uPos)
+{
+   // Have to cast a pointer and deref so the bit pattern is what put
+   // passed. This is to avoid 3.1415 getting converted to 3.
+   UsefulOutBuf_InsertUint32(me, *(uint32_t *)&f, uPos);
+}
+
+
+/**
+ @brief Insert a double into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBul
+ @param[in] d Integer to insert
+ @param[in] nPos Index in output buffer at which to insert
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This is the same with
+ the difference being a single byte is to be inserted.
+ 
+ The double will be inserted in network byte order (big endian)
+ */
+static inline void UsefulOutBuf_InsertDouble(UsefulOutBuf *me, double d, size_t uPos)
+{
+   // See UsefulOutBuf_InsertFloat
+   UsefulOutBuf_InsertUint64(me, *(uint64_t *)&d, uPos);
+}
+
+
+
+/**
+ Append a UsefulBuf into the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] NewData UsefulBuf with the bytes to append
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ 
+*/
+static inline void UsefulOutBuf_AppendUsefulBuf(UsefulOutBuf *me, UsefulBufC NewData)
+{
+   // An append is just a insert at the end
+   UsefulOutBuf_InsertUsefulBuf(me, NewData, UsefulOutBuf_GetEndPosition(me));
+}
+
+
+/**
+ Append bytes to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] pBytes Pointer to bytes to append
+ @param[in] nLen Index in output buffer at which to append
+ 
+ @return None
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ */
+
+static inline void UsefulOutBuf_AppendData(UsefulOutBuf *me, const void *pBytes, size_t uLen)
+{
+   UsefulBufC Data = {pBytes, uLen};
+   UsefulOutBuf_AppendUsefulBuf(me, Data);
+}
+
+
+/**
+ Append a NULL-terminated string to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] szString string to append
+ 
+ @return None
+ */
+static inline void UsefulOutBuf_AppendString(UsefulOutBuf *me, const char *szString)
+{
+   UsefulOutBuf_AppendUsefulBuf(me, (UsefulBufC){szString, strlen(szString)});
+}
+
+
+/**
+ @brief Append a byte to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] byte Bytes to append
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ */
+static inline void UsefulOutBuf_AppendByte(UsefulOutBuf *me, uint8_t byte)
+{
+   UsefulOutBuf_AppendData(me, &byte, 1);
+}
+
+/**
+ @brief Append an integer to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] uInteger16 Integer to append
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ 
+ The integer will be appended in network byte order (big endian).
+ */
+static inline void UsefulOutBuf_AppendUint16(UsefulOutBuf *me, uint16_t uInteger16){
+   UsefulOutBuf_InsertUint16(me, uInteger16, UsefulOutBuf_GetEndPosition(me));
+}
+
+/**
+ @brief Append an integer to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] uInteger32 Integer to append
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ 
+ The integer will be appended in network byte order (big endian).
+ */
+static inline void UsefulOutBuf_AppendUint32(UsefulOutBuf *me, uint32_t uInteger32){
+   UsefulOutBuf_InsertUint32(me, uInteger32, UsefulOutBuf_GetEndPosition(me));
+}
+
+/**
+ @brief Append an integer to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] uInteger64 Integer to append
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ 
+ The integer will be appended in network byte order (big endian).
+ */
+static inline void UsefulOutBuf_AppendUint64(UsefulOutBuf *me, uint64_t uInteger64){
+   UsefulOutBuf_InsertUint64(me, uInteger64, UsefulOutBuf_GetEndPosition(me));
+}
+
+
+/**
+ @brief Append a float to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] f Float to append
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ 
+ The float will be appended in network byte order (big endian).
+ */
+static inline void UsefulOutBuf_AppendFloat(UsefulOutBuf *me, float f){
+   UsefulOutBuf_InsertFloat(me, f, UsefulOutBuf_GetEndPosition(me));
+}
+
+/**
+ @brief Append a float to the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] d Double to append
+ 
+ See UsefulOutBuf_InsertUsefulBuf() for details. This does the same
+ with the insertion point at the end of the valid data.
+ 
+ The double will be appended in network byte order (big endian).
+ */
+static inline void UsefulOutBuf_AppendDouble(UsefulOutBuf *me, double d){
+   UsefulOutBuf_InsertDouble(me, d, UsefulOutBuf_GetEndPosition(me));
+}
+
+/**
+ @brief Returns the current error status
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ 
+ @return 0 if all OK, 1 on error
+ 
+ This is the error status since the call to either
+ UsefulOutBuf_Reset() of UsefulOutBuf_Init().  Once it goes into error
+ state it will stay until one of those functions is called.
+ 
+ Possible error conditions are:
+   - bytes to be inserted will not fit
+   - insertion point is out of buffer or past valid data
+   - current position is off end of buffer (probably corruption or uninitialized)
+   - detect corruption / uninitialized by bad magic number
+ */
+
+static inline int UsefulOutBuf_GetError(UsefulOutBuf *me)
+{
+   return me->err;
+}
+
+
+/**
+ @brief Returns number of bytes unused used in the output buffer
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ 
+ @return Number of unused bytes or zero
+ 
+ Because of the error handling strategy and checks in UsefulOutBuf_InsertUsefulBuf()
+ it is usually not necessary to use this.
+ */
+
+static inline size_t UsefulOutBuf_RoomLeft(UsefulOutBuf *me)
+{
+   return me->size - me->UB.len;
+}
+
+
+/**
+ @brief Returns true / false if some number of bytes will fit in the UsefulOutBuf
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[in] uLen Number of bytes for which to check
+ 
+ @return 1 or 0 if nLen bytes would fit
+ 
+ Because of the error handling strategy and checks in UsefulOutBuf_InsertUsefulBuf()
+ it is usually not necessary to use this.
+ */
+
+static inline int UsefulOutBuf_WillItFit(UsefulOutBuf *me, size_t uLen)
+{
+   return uLen <= UsefulOutBuf_RoomLeft(me);
+}
+
+
+/**
+  @brief Returns the resulting valid data in a UsefulBuf
+ 
+  @param[in] me Pointer to the UsefulOutBuf
+  @param[out] O UsefuBuf structure holding pointer and length
+ 
+  @return Same as UsefulOutBuf_GetError()
+ 
+  If you want a pointer and length to the resulting data, dereference
+  O.
+ 
+  This can be called anytime and many times to get intermediate
+  results. It doesn't change the data or reset the current position
+  so you can keep adding data.
+ */
+
+int UsefulOutBuf_OutUBuf(UsefulOutBuf *me, UsefulBuf *O);
+
+
+/**
+ @brief Copies the valid data out into a supplied buffer
+ 
+ @param[in] me Pointer to the UsefulOutBuf
+ @param[out] pBuf buffer to copy data into
+ @param[in] uBufSize size of pBuf
+ @param[out] puCopied number of valid bytes copied into pBuf
+ 
+ @return Same as UsefulOutBuf_GetError()
+ 
+ This is the same as UsefulOutBuf_OutUBuf() except it copies the data.
+ */
+
+int UsefulOutBuf_CopyOut(UsefulOutBuf *me, void *pBuf, size_t uBufSize, size_t *puCopied);
+
+
+
+
+
+
+
+
+
+
+
+
+
+/**
+ UsefulInBuf is the counterpart to UsefulOutBuf and is for parsing
+ data read or received.  The idea is that you initialize with the data
+ you got off the network and its length. Then you use the functions
+ here to get the various data types out of it. It maintains a position
+ for getting the next item. This means you don't have to track a
+ pointer as you get each object. UsefulInBuf does that for you and
+ makes sure it never goes off the end of the buffer.  The qcbor
+ implementation parser makes use of this for all its pointer math and
+ length checking.
+ 
+ UsefulInBuf also maintains an intenal error state so you do not have
+ to. Once data has been requested off the end of the buffer, it goes
+ into an error state. You can keep calling functions to get more data
+ but they will either return 0 or NULL. As long as you don't
+ dereference the NULL, you can wait until all data items have been
+ fetched before checking for the error and this can simplify your
+ code.
+ 
+ The integer parsing expects network byte order (big endian). Network
+ byte order is what is used by TCP/IP, CBOR and most internet protocols.
+ 
+ 64-bit machine: 16 + 8 + 2 + 1 (5 bytes padding to align) = 32 bytes
+ 32-bit machine: 8 + 4 + 2 + 1 (1 byte padding to align) = 16 bytes
+
+ */
+
+#define UIB_MAGIC (0xB00F)
+
+typedef struct __UsefulInputBuf {
+   UsefulBufC UB;
+   size_t     cursor;
+   uint16_t   magic;
+   uint8_t    err; // set if off end of buffer; also can set if this structure is corrupt or inconsistent.
+} UsefulInputBuf;
+
+
+
+/**
+ 
+ Initialize the UsefulInputBuf structure before use.
+ 
+ */
+
+static inline void UsefulInputBuf_Init(UsefulInputBuf *me, UsefulBufC UB)
+{
+   me->cursor = 0;
+   me->err    = 0;
+   me->magic  = UIB_MAGIC;
+   me->UB     = UB;
+}
+
+
+/**
+ Returns current position in input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return Integer position of the cursor
+ 
+ The position that the next bytes will be returned from.
+ 
+ */
+static inline size_t UsefulInputBuf_Tell(UsefulInputBuf *me) {
+   return me->cursor;
+}
+
+
+/**
+ Sets current position in input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ @param[in] nPos  Position to set to
+ 
+ @return None.
+ 
+ If the position is off the end of the input buffer, the error state
+ is entered and all functions will do nothing.
+ 
+ Seeking to a valid position in the buffer will not reset the error
+ state. Only re initialization will do that.
+ 
+ */
+
+static inline void UsefulInputBuf_Seek(UsefulInputBuf *me, size_t uPos)
+{
+   if(uPos > me->UB.len) {
+      me->err = 1;
+   } else {
+      me->cursor = uPos;
+   }
+}
+
+
+/**
+ 
+ Returns the number of bytes from the cursor to the end of the buffer,
+ the uncomsummed bytes.
+ 
+ This is a critical function for input length validation. This does
+ some pointer / offset math.
+ 
+ Returrns 0 if the cursor it invalid or corruption of the structure is
+ detected.
+ */
+static inline size_t UsefulInputBuf_BytesUnconsumed(UsefulInputBuf *me)
+{
+   // Magic number is messed up. Either the structu got overwritten
+   // or was never initialized.
+   if(me->magic != UIB_MAGIC)
+      return 0;
+   
+   // The cursor is off the end of the input buffer given
+   // Presuming there are no bugs in this code, this should never happen.
+   // If it so, the struct was corrupted. The check is retained as
+   // as a defense in case there is a bug in this code or the struct is corrupted.
+   if(me->cursor > me->UB.len)
+      return 0;
+   
+   // subtraction can't go neative because of check above
+   return me->UB.len - me->cursor;
+}
+
+
+/*
+ 
+ Returns 1 if len bytes are available after the cursor, and 0 if not
+ 
+ */
+
+static inline int UsefulInputBuf_BytesAvailable(UsefulInputBuf *me, size_t uLen)
+{
+   return UsefulInputBuf_BytesUnconsumed(me) >= uLen ? 1 : 0;
+}
+
+
+
+
+
+/**
+ @brief Get pointer to bytes out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ @param[in] uNum  Number of bytes to get
+ 
+ @return Pointer to bytes.
+ 
+ This consumes n bytes from the input buffer. It returns a pointer to
+ the start of the n bytes.
+ 
+ If there are not n bytes in the input buffer, NULL will be returned
+ and an error will be set.
+ 
+ It advances the current position by n bytes.
+ */
+const void * UsefulInputBuf_GetBytes(UsefulInputBuf *me, size_t uNum);
+
+
+/**
+ @brief Get UsefulBuf  out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ @param[in] uNum  Number of bytes to get
+ 
+ @return UsefulBufC with ptr and length for bytes consumed.
+ 
+ This consumes n bytes from the input buffer and returns the pointer
+ and len to them as a UsefulBufC. The len returned will always be n.
+ 
+ If there are not n bytes in the input buffer, UsefulBufC.ptr will be
+ NULL and UsefulBufC.len will be 0. An error will be set.
+ 
+ It advances the current position by n bytes.
+ */
+static inline UsefulBufC UsefulInputBuf_GetUsefulBuf(UsefulInputBuf *me, size_t uNum)
+{
+   const void *pResult = UsefulInputBuf_GetBytes(me, uNum);
+   
+   UsefulBufC UBR = {NULL, 0};
+   
+   if(pResult) {
+      UBR.len = uNum;
+      UBR.ptr = pResult;
+   }
+   
+   return UBR;
+}
+
+
+/**
+ @brief Get a byte out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The byte
+ 
+ This consumes 1 byte from the input buffer. It returns the byte.
+ 
+ If there is not 1 byte in the buffer, 0 will be returned for the byte
+ and an error set internally.  You must check the error at some point
+ to know whether the 0 was the real value or just returned in error,
+ but you may not have to do that right away.  Check the error state
+ with UsefulInputBuf_GetError().  You can also know you are in the
+ error state if UsefulInputBuf_GetBytes() returns NULL or the ptr from
+ UsefulInputBuf_GetUsefulBuf() is NULL.
+ 
+ It advances the current position by 1 byte.
+ */
+static inline uint8_t UsefulInputBuf_GetByte(UsefulInputBuf *me)
+{
+   const void *pResult = UsefulInputBuf_GetBytes(me, sizeof(uint8_t));
+   
+   return pResult ? *(uint8_t *)pResult : 0;
+}
+
+/**
+ @brief Get a uint16_t out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The uint16_t
+ 
+ See UsefulInputBuf_GetByte(). This works the same, except it returns
+ a uint16_t and two bytes are consumed.
+ 
+ The input bytes must be in network order (big endian).
+ */
+static inline uint16_t UsefulInputBuf_GetUint16(UsefulInputBuf *me)
+{
+   const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(me, sizeof(uint16_t));
+   
+   if(!pResult) {
+      return 0;
+   }
+   
+   return  ((uint16_t)pResult[0] << 8) + (uint16_t)pResult[1];
+}
+
+/**
+ @brief Get a uint32_t out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The uint32_t
+ 
+ See UsefulInputBuf_GetByte(). This works the same, except it returns
+ a uint32_t and four bytes are consumed.
+ 
+ The input bytes must be in network order (big endian).
+ */
+static inline uint32_t UsefulInputBuf_GetUint32(UsefulInputBuf *me)
+{
+   const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(me, sizeof(uint32_t));
+   
+   if(!pResult) {
+      return 0;
+   }
+   
+   return ((uint32_t)pResult[0]<<24) + ((uint32_t)pResult[1]<<16) + ((uint32_t)pResult[2]<<8) + (uint32_t)pResult[3];
+}
+
+/**
+ @brief Get a uint64_t out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The uint64_t
+ 
+ See UsefulInputBuf_GetByte(). This works the same, except it returns
+ a uint64_t and eight bytes are consumed.
+ 
+ The input bytes must be in network order (big endian).
+ */
+static inline uint64_t UsefulInputBuf_GetUint64(UsefulInputBuf *me)
+{
+   const uint8_t *pResult = (const uint8_t *)UsefulInputBuf_GetBytes(me, sizeof(uint64_t));
+   
+   if(!pResult) {
+      return 0;
+   }
+   
+   return   ((uint64_t)pResult[0]<<56) +
+            ((uint64_t)pResult[1]<<48) +
+            ((uint64_t)pResult[2]<<40) +
+            ((uint64_t)pResult[3]<<32) +
+            ((uint64_t)pResult[4]<<24) +
+            ((uint64_t)pResult[5]<<16) +
+            ((uint64_t)pResult[6]<<8)  +
+            (uint64_t)pResult[7];
+}
+
+
+/**
+ Get a float out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The float
+ 
+ See UsefulInputBuf_GetByte(). This works the same, except it returns
+ a float and four bytes are consumed.
+ 
+ The input bytes must be in network order (big endian).
+ */
+static inline float UsefulInputBuf_GetFloat(UsefulInputBuf *me)
+{
+   uint32_t uResult = UsefulInputBuf_GetUint32(me);
+
+   return uResult ? *(float *)&uResult : 0;
+
+}
+
+/**
+ Get a double out of the input buffer
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The double
+ 
+ See UsefulInputBuf_GetByte(). This works the same, except it returns
+ a double and eight bytes are consumed.
+ 
+ The input bytes must be in network order (big endian).
+ */
+static inline double UsefulInputBuf_GetDouble(UsefulInputBuf *me)
+{
+   uint64_t uResult = UsefulInputBuf_GetUint64(me);
+
+   return uResult ? *(double *)&uResult : 0;
+}
+
+
+
+/**
+ Get the error status
+ 
+ @param[in] me Pointer to the UsefulInputBuf.
+ 
+ @return The error.
+ 
+ Zero is success, non-zero is error. Once in the error state, the only
+ way to clear it is to call Init again.
+ 
+ You may be able to only check the error state at the end after all
+ the Get()'s have been done, but if what you get later depends on what
+ you get sooner you cannot. For example if you get a length or count
+ of following items you will have to check the error.
+ 
+ */
+static inline int UsefulInputBuf_GetError(UsefulInputBuf *me)
+{
+   return me->err;
+}
+
+
+#endif  // _UsefulBuf_h
+
+
diff --git a/inc/qcbor.h b/inc/qcbor.h
new file mode 100644
index 0000000..130d05a
--- /dev/null
+++ b/inc/qcbor.h
@@ -0,0 +1,1724 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. 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 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.h
+ 
+ DESCRIPTION:  This is the full public API and data structures for 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
+ --------           ----            ---------------------------------------------------
+ 07/05/17           llundbla        Add bstr wrapping of maps/arrays for COSE
+ 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.
+ 
+ =====================================================================================*/
+
+#ifndef __QCBOR__qcbor__
+#define __QCBOR__qcbor__
+
+/*...... This is a ruler that is 80 characters long...........................*/
+
+/* ===========================================================================
+   BEGINNING OF PRIVATE PART OF THIS FILE
+
+   Caller of QCBOR should not reference any of the details below up until
+   the start of the public part.
+   =========================================================================== */
+
+/*
+ Standard integer types are used in the interface to be precise about
+ sizes to be better at preventing underflow/overflow errors.
+ */
+#include <stdint.h>
+#include <stdbool.h>
+#include "UsefulBuf.h"
+
+
+/*
+ The maxium nesting of arrays and maps when encoding or decoding. 
+ (Further down in the file there is a definition that refers to this 
+ that is public. This is done this way so there can be a nice
+ separation of public and private parts in this file.
+*/
+#define QCBOR_MAX_ARRAY_NESTING1 10 // Do not increase this over 255
+
+
+/*  
+ PRIVATE DATA STRUCTURE 
+ 
+ Holds the data for tracking array and map nesting during encoding. Pairs up with
+ the Nesting_xxx functions to make an "object" to handle nesting encoding.
+ 
+ uStart is a uint32_t instead of a size_t to keep the size of this
+ struct down so it can be on the stack without any concern.  It would be about
+ double if size_t was used instead.
+ 
+ 64-bit machine: 10 * (4 + 2 + 1 + 1) + 8 = 88 bytes
+ 32-bit machine: 10 * (4 + 2 + 1 + 1) + 4 = 84 bytes
+*/
+typedef struct __QCBORTrackNesting {
+   // PRIVATE DATA STRUCTURE
+   struct {
+      // See function OpenArrayInternal() for detailed comments on how this works
+      uint32_t  uStart;     // uStart is the byte position where the array starts
+      uint16_t  uCount;     // Number of items in the arrary or map; counts items in a map, not pairs of items 
+      uint8_t   uMajorType; // Indicates if item is a map or an array
+      uint8_t   bBstrWrap;  // non-zero if map/array should be wrapped in a bstring
+   } pArrays[QCBOR_MAX_ARRAY_NESTING1+1], // stored state for the nesting levels
+   *pCurrentNesting; // the current nesting level
+} QCBORTrackNesting;
+
+
+/*  
+ PRIVATE DATA STRUCTURE 
+ 
+ Context / data object for encoding some CBOR. Used by all encode functions to 
+ form a public "object" that does the job of encdoing.
+ 
+ 64-bit machine: 27 + 1 (+ 4 padding) + 88 = 32+88 = 120 bytes
+ 32-bit machine: 15 + 1 + 84 = 90 bytes
+*/
+struct _QCBOREncodeContext {
+   // PRIVATE DATA STRUCTURE
+   UsefulOutBuf      OutBuf;  // Pointer to output buffer, its length and position in it
+   uint8_t           uError;  // Error state
+   QCBORTrackNesting nesting; // Keep track of array and map nesting
+};
+
+
+/*
+ PRIVATE DATA STRUCTURE
+ 
+ Holds the data for array and map nesting for decoding work. This structure
+ and the DecodeNesting_xxx functions form an "object" that does the work
+ for arrays and maps.
+ 
+ 64-bit machine: 27 + 1 + 96 = 32+96 = 128 bytes
+ 32-bit machine: 15 + 1 + 96 = 114 bytes
+ */
+typedef struct __QCBORDecodeNesting  {
+  // PRIVATE DATA STRUCTURE
+   struct {
+      uint16_t uCount;  
+      uint8_t  uMajorType;
+   } pMapsAndArrays[QCBOR_MAX_ARRAY_NESTING1+1],
+   *pCurrent;
+} QCBORDecodeNesting;
+
+
+/* 
+ PRIVATE DATA STRUCTURE
+
+ The decode context. This data structure plus the public QCBORDecode_xxx
+ functions form an "object" that does CBOR decoding.
+
+ 64-bit machine: 32 + 1 + (7 bytes padding) + 128 = 168 bytes
+ 32-bit machine: 16 + 1 + (3 bytes padding) + 114 = 134 bytes
+ */
+struct _QCBORDecodeContext {
+   // PRIVATE DATA STRUCTURE   
+   UsefulInputBuf InBuf;
+   
+   uint8_t        uDecodeMode;
+   
+   QCBORDecodeNesting nesting;
+};
+
+
+/* ===========================================================================
+   END OF PRIVATE PART OF THIS FILE
+
+   BEGINNING OF PUBLIC PART OF THIS FILE
+   =========================================================================== */
+
+
+
+/* ===========================================================================
+   BEGINNING OF CONSTANTS THAT COME FROM THE CBOR STANDARD, RFC 7049
+ 
+   It is not necessary to use these directly when encoding or decoding
+   CBOR with this implementation.
+   =========================================================================== */
+
+/* Standard CBOR Major type for positive integers of various lengths */
+#define CBOR_MAJOR_TYPE_POSITIVE_INT 0
+
+/* Standard CBOR Major type for negative integer of various lengths */
+#define CBOR_MAJOR_TYPE_NEGATIVE_INT 1
+
+/* Standard CBOR Major type for an array of arbitrary 8-bit bytes. */
+#define CBOR_MAJOR_TYPE_BYTE_STRING  2
+
+/* Standard CBOR Major type for a UTF-8 string. Note this is true 8-bit UTF8
+ with no encoding and no NULL termination */
+#define CBOR_MAJOR_TYPE_TEXT_STRING  3
+
+/* Standard CBOR Major type for an ordered array of other CBOR data items */
+#define CBOR_MAJOR_TYPE_ARRAY        4
+
+/* Standard CBOR Major type for CBOR MAP. Maps an array of pairs. The
+ first item in the pair is the "label" (key, name or identfier) and the second
+ item is the value.  */
+#define CBOR_MAJOR_TYPE_MAP          5
+
+/* Standard CBOR optional tagging. This tags things like dates and URLs */
+#define CBOR_MAJOR_TYPE_OPTIONAL     6
+
+/* Standard CBOR extra simple types like floats and the values true and false */
+#define CBOR_MAJOR_TYPE_SIMPLE       7
+
+
+/*
+ These are special values for the AdditionalInfo bits that are part of the first byte.
+ Mostly they encode the length of the data item.
+ */
+#define LEN_IS_ONE_BYTE    24
+#define LEN_IS_TWO_BYTES   25
+#define LEN_IS_FOUR_BYTES  26
+#define LEN_IS_EIGHT_BYTES 27
+#define ADDINFO_RESERVED1  28
+#define ADDINFO_RESERVED2  29
+#define ADDINFO_RESERVED3  30
+#define LEN_IS_INDEFINITE  31
+
+
+/*
+ 24 is a special number for CBOR. Integers and lengths
+ less than it are encoded in the same byte as the major type
+ */
+#define CBOR_TWENTY_FOUR   24
+
+
+/*
+ Tags that are used with CBOR_MAJOR_TYPE_OPTIONAL. These are
+ the ones defined in the CBOR spec.
+ */
+/** See QCBOREncode_AddDateString() below */
+#define CBOR_TAG_DATE_STRING    0
+/** See QCBOREncode_AddDateEpoch_2() */
+#define CBOR_TAG_DATE_EPOCH     1
+#define CBOR_TAG_POS_BIGNUM     2
+#define CBOR_TAG_NEG_BIGNUM     3
+#define CBOR_TAG_FRACTION       4
+#define CBOR_TAG_BIGFLOAT       5
+/* The data in byte string should be converted in base 64 URL when encoding in JSON or similar text-based representations */
+#define CBOR_TAG_ENC_AS_B64URL 21
+/* The data in byte string should be encoded in base 64 when encoding in JSON */
+#define CBOR_TAG_ENC_AS_B64    22
+/* The data in byte string should be encoded in base 16 when encoding in JSON */
+#define CBOR_TAG_ENC_AS_B16    23
+#define CBOR_TAG_CBOR          24
+/** The data in the string is a URIs, as defined in RFC3986 */
+#define CBOR_TAG_URI           32
+/** The data in the string is a base 64'd URL */
+#define CBOR_TAG_B64URL        33
+/** The data in the string is base 64'd */
+#define CBOR_TAG_B64           34
+/** regular expressions in Perl Compatible Regular Expressions (PCRE) / JavaScript syntax ECMA262. */
+#define CBOR_TAG_REGEX         35
+/** MIME messages (including all headers), as defined in RFC2045 */
+#define CBOR_TAG_MIME          36
+/** Binary UUID */
+#define CBOR_TAG_BIN_UUID      37
+/** The data is CBOR data */
+#define CBOR_TAG_CBOR_MAGIC 55799
+#define CBOR_TAG_NONE  UINT64_MAX
+
+
+/*
+ Values for the 5 bits for items of major type 7
+ */
+#define CBOR_SIMPLEV_FALSE   20
+#define CBOR_SIMPLEV_TRUE    21
+#define CBOR_SIMPLEV_NULL    22
+#define CBOR_SIMPLEV_UNDEF   23
+#define CBOR_SIMPLEV_ONEBYTE 24
+#define HALF_PREC_FLOAT      25
+#define SINGLE_PREC_FLOAT    26
+#define DOUBLE_PREC_FLOAT    27
+#define CBOR_SIMPLE_BREAK    31
+
+
+
+/* ===========================================================================
+ 
+ END OF CONSTANTS THAT COME FROM THE CBOR STANDARD, RFC 7049
+ 
+ BEGINNING OF PUBLIC INTERFACE FOR QCBOR ENCODER / DECODER
+ 
+ =========================================================================== */
+
+/**
+ 
+ @file qcbor.h
+ 
+ Q C B O R   E n c o d e / D e c o d e
+ 
+ This implements CBOR -- Concise Binary Ojbect Representation as defined
+ in RFC 7049. More info is at http://cbor.io.  This is a near-complete
+ implementation of the specification. Limitations are listed further down.
+ 
+ CBOR is intentinonally designed to be translatable to JSON, but not
+ all CBOR can convert to JSON. See RFC 7049 for more info on how to
+ construct CBOR that is the most JSON friendly.
+ 
+ The memory model for encoding and decoding is that encoded CBOR
+ must be in a contigious buffer in memory.  During encoding the
+ caller must supply an output buffer and if the encoding would go
+ off the end of the buffer an error is returned.  During decoding
+ the caller supplies the encoded CBOR in a contiguous buffer
+ and the decoder returns pointers and lengths into that buffer
+ for strings. 
+ 
+ This implementation does not use malloc at all. All data structures
+ passed in/out of the APIs can fit on the stack.
+ 
+ Here are some terms and definitions:
+ 
+ - "Item", "Data Item": An integer or string or such. The basic "thing" that
+ CBOR is about. An array is an item itself that contains some items.
+ 
+ - "Array": An ordered sequence of items, the same as JSON.
+ 
+ - "Map": A collection of label/value pairs. Each pair is a data
+ item. A JSON "object" is the same as a CBOR "map".
+ 
+ - "Label": The data item in a pair in a map that names or identifies the
+ pair, not the value. This implementation refers to it as a "label".
+ JSON refers to it as the "name". The CBOR RFC refers to it this as a "key".
+ This implementation chooses label instead because key is too easily confused
+ with a cryptographic key. The COSE standard, which uses CBOR, has also
+ choosen to use the term "label" rather than "key" for this same reason.
+ 
+ - "Tag": Optional info that can be added before each data item. This is always
+ CBOR major type 6.
+ 
+ - "Initial Byte": The first byte of an encoded item. Encoding and decoding of
+ this byte is taken care of by the implementation.
+ 
+ - "Additional Info": In addition to the major type, all data items have some
+ other info. This is usually the length of the data, but can be several
+ other things. Encoding and decoding of this is taken care of by the
+ implementation.
+ 
+ CBOR has two mechanisms for tagging and labeling the primitive data
+ values like integers and strings. For example an integter that
+ represents someone's birthday in epoch seconds since Jan 1, 1970
+ could be encoded like this:
+ 
+ - First it is CBOR_MAJOR_TYPE_POSITIVE_INT, the primitive positive
+ integer.
+ - Next it has a "tag" CBOR_TAG_DATE_EPOCH indicating the integer
+ represents a date in the form of the number of seconds since
+ Jan 1, 1970.
+ - Last it has a string "label" like "BirthDate" indicating
+ the meaning of the data.
+ 
+ The encoded binary looks like this:
+   a1                      # Map of 1 item
+      69                   # Indicates text string of 9 bytes
+        426972746844617465 # The text "BirthDate"
+     c1                    # Tags next int as epoch date
+        1a                 # Indicates 4 byte integer
+            580d4172       # unsigned integer date 1477263730
+ 
+ Implementors using this API will primarily work with labels. Generally
+ tags are only needed for making up new data types. This implementation
+ covers most of the data types defined in the RFC using tags. However,
+ it does allow for the creation of news tags if necessary.
+ 
+ This implementation explicitly supports labels that are text strings
+ and integers. Text strings translate nicely into JSON objects and
+ are very readable.  Integer labels are much less readable, but
+ can be very compact. If they are in the range of -23 to
+ 23 they take up only one byte.
+ 
+ CBOR allows a label to be any type of data including an array or 
+ a map. It is possible to use this API to construct and
+ parse such labels, but it is not explicitly supported.
+ 
+ 
+ The intended encoding usage mode is to invoke the encoding twice. First
+ with no output buffer to compute the length of the needed output
+ buffer. Then the correct sized output buffer is allocated. Last the
+ encoder is invoked again, this time with the output buffer.
+ 
+ The double invocation is not required if the max output buffer size
+ can be predicted. This is usually possible for simple CBOR structures.
+ If the double invocation is implemented it can be
+ in a loop or function as in the example code so that the code doesn't
+ have to actually be written twice, saving code size.
+ 
+ If a buffer too small to hold the encoded output is given, the error
+ QCBOR_ERR_BUFFER_TOO_SMALL will be returned. Data will never be
+ written off the end of the output buffer no matter which functions
+ here are called or what parameters are passed to them.
+ 
+ The error handling is simple. The only possible errors are trying to
+ encode structures that are too large or too complex. There are no
+ internal malloc calls so there will be no failures for out of memory.
+ Only the final call, QCBOREncode_Finish(), returns an error code.
+ Once an error happens, the encoder goes into an error state and calls
+ to it will do nothing so the encoding can just go on. An error
+ check is not needed after every data item is added.
+ 
+ Encoding generally proceeds by calling QCBOREncode_Init(), calling
+ lots of "Add" functions and calling QCBOREncode_Finish(). There
+ are many "Add" functions for various data types. The input
+ buffers need only to be valid during the "Add" calls. The 
+ data is copied into the output buf during the "Add" call.
+ 
+ There are several "Add" functions / macros for each type. The one
+ with named ending in "_3", for example QCBOREncode_AddInt64_3(),
+ takes parameters for labels and tags and is the most powerful.
+ Generally it is better to use the macros that only take the
+ parameters necessary. For example, QCBOREncode_AddInt64(),
+ only takes the integer value to add with no labels and tags.
+ 
+ The simplest aggregate type is an array, which is a simple ordered
+ set of items without labels the same as JSON arrays. Call 
+ QCBOREncode_OpenArray() to open a new array, then "Add" to
+ put items in the array and then QCBOREncode_CloseArray(). Nesting
+ to a limit is allowed.  All opens must be matched by closes or an
+ encoding error will be returned.
+ 
+ The other aggregate is a map which does use labels.  For convenience
+ there are macros for adding each type to a map, one with a string
+ label, the other with an integer label. (Part of the goal of this
+ design is to make the code implementing a CBOR protocol easy to
+ read).
+ 
+ Note that when you nest arrays or maps in a map, the nested
+ array or map has a label.
+ 
+ As mentioned callers of this API will generally not need tags
+ and thus not need the "_3" functions, but they are available
+ if need be. There is an IANA registry for new tags that are
+ for broad use and standardization as per RFC 7049. It is also 
+ allowed for protocols to make up new tags in the range above 256.
+ Note that even arrays and maps can be tagged.
+ 
+ Tags in CBOR are a bit open-ended in particular allowing
+ multiple tags per item, and the ability to tag deeply nested maps
+ and arrays. Partly this is good as it allows them to be used 
+ in lots of ways, but also makes a general purpose decoder 
+ like this more difficult.
+ 
+ This implementation only supports one tag per data item
+ during encoding and decoding.
+  
+ Summary Limits of this implementation:
+ - The entire encoded CBOR must fit into contiguous memory.
+ - Max size of encoded / decoded CBOR data is UINT32_MAX (4GB).
+ - Max array / map nesting level when encoding / decoding is
+   QCBOR_MAX_ARRAY_NESTING (this is typically 10).
+ - Max items in an array or map when encoding / decoding is
+   QCBOR_MAX_ITEMS_IN_ARRAY (typicall 65,536).
+ - Does not support encoding or decoding indefinite lengths.
+ - Does not directly support some tagged types: decimal fractions, big floats
+ - Does not directly support labels in maps other than text strings and ints.
+ - Epoch dates limited to INT64_MAX (+/- 292 billion years)
+ - Only one tag per data item is supported for tag values > 62
+ - Tags on labels are ignored
+ 
+ This implementation is intended to run on 32 and 64-bit CPUs. It
+ will probably work on 16-bit CPUs but less efficiently.
+ 
+ The public interface uses size_t for all lengths. Internally the
+ implementation uses 32-bit lengths by design to use less memory and
+ fit structures on the stack. This limits the encoded
+ CBOR it can work with to size UINT32_MAX (4GB) which should be
+ enough.
+ 
+ This implementation assume two's compliment integer
+ machines. Stdint.h also requires this. It of course would be easy to
+ fix this implementation for another integer representation, but all
+ modern machines seem to be two's compliment.
+ 
+ */
+
+
+
+/**
+ This holds some encoded CBOR. It is primarily the pointer and length
+ of the encoded CBOR.
+ 
+ It also includes a count of the number of items at the top level of 
+ the encoded CBOR. When the top level of CBOR is a map or an array
+ the item count will be 1 because there is one map or array. It is
+ only greater than 1 if the top level is not a map or an array.
+ 
+ For the most part the item count can be ignored. It is only needed
+ when piecing together separately encoded chunks using QCBOREncode_AddRaw().
+ (In this case it saves the parsing the encoded CBOR that is being
+ added to get the item count).
+ 
+ The item count is the actual number of individual items. In array
+ it is the same as the CBOR count. For a map it is double because
+ the CBOR count is label/data pairs while this count the label 
+ and the data separately
+ */
+
+typedef struct __EncodedCBORC {
+   UsefulBufC Bytes;
+   uint16_t   uItems;
+} EncodedCBORC;
+
+typedef struct __EncodedCBOR {
+   UsefulBuf  Bytes;
+   uint16_t   uItems;
+} EncodedCBOR;
+
+
+/** 
+ The maximum number of items in a single array or map when encoding of decoding.
+*/
+#define QCBOR_MAX_ITEMS_IN_ARRAY (UINT16_MAX) // This value is 65,535 a lot of items for an array
+
+/** 
+ The maxium nesting of arrays and maps when encoding or decoding. The
+ error QCBOR_ERR_ARRAY_NESTING_TOO_DEEP will be returned on encoding
+ of decoding if it is exceeded
+*/
+#define QCBOR_MAX_ARRAY_NESTING  QCBOR_MAX_ARRAY_NESTING1
+
+
+
+
+/** The encode or decode completely correctly. */
+#define QCBOR_SUCCESS                     0
+
+/** The buffer provided for the encoded output when doing encoding was
+ too small and the encoded output will not fit. */
+#define QCBOR_ERR_BUFFER_TOO_SMALL        1
+
+/**  During encoding or decoding, the array or map nesting was deeper than this
+ implementation can handle. Note that in the interest of code size and
+ memory use, this implementation has a hard limit on array nesting. The
+ limit is defined as the constant QCBOR_MAX_ARRAY_NESTING. */
+#define QCBOR_ERR_ARRAY_NESTING_TOO_DEEP  2
+
+/**  During decoding the array or map had too many items in it. This limit is quite
+ high at 65,535. */
+#define QCBOR_ERR_ARRAY_TOO_LONG          3
+
+/**  During encoding, more arrays or maps were closed than opened. This is a
+ coding error on the part of the caller of the encoder. */
+#define QCBOR_ERR_TOO_MANY_CLOSES         4
+
+/**  During decoding, some CBOR construct was encountered that this decoder
+ doesn't support. For example indefinite lengths. */
+#define QCBOR_ERR_UNSUPPORTED             5
+
+/**  During decoding, hit the end of the given data to decode. For example,
+ a byte string of 100 bytes was expected, but the end of the input
+ was hit before finding those 100 bytes.  Corrupted CBOR
+ input will often result in this error. */
+#define QCBOR_ERR_HIT_END                 6
+
+/** The length of the input buffer was too large. This might happen
+ on a 64-bit machine when a buffer larger than INT32_MAX is passed */
+#define QCBOR_ERR_BUFFER_TOO_LARGE        7
+
+/** The simple value added for encoding (e.g. passed to QCBOR_AddSimple) was not valid */
+#define QCBOR_ERR_INVALID_SIMPLE          8
+
+/** During parsing, the integer received was larger than can be handled. This is
+ most likely a large negative number as CBOR can represent large negative integers
+ that C cannot */
+#define QCBOR_ERR_INT_OVERFLOW            9
+
+/** During parsing, the label for a map entry is bad. An array is used as a map label,
+ in mode to accept strings only as labels and it is not a string... */
+#define QCBOR_ERR_MAP_LABEL_TYPE          10
+
+/** The number of array or map opens was not matched by the number of closes */
+#define QCBOR_ERR_ARRAY_OR_MAP_STILL_OPEN 11
+
+/** The simple value is not between CBOR_SIMPLEV_FALSE and CBOR_SIMPLEV_UNDEF */
+#define QCBOR_ERR_BAD_SIMPLE              12 // todo combine with 8?
+
+/** Date greater than +- 292 billion years from Jan 1 1970 encountered during parsing */
+#define QCBOR_ERR_DATE_OVERFLOW           13
+
+/** The CBOR is not valid (a simple type is encoded wrong)  */
+#define QCBOR_ERR_INVALID_CBOR            14
+
+/** Optional tagging that doesn't make sense (an int is tagged as a date string) or can't be handled. */
+#define QCBOR_ERR_BAD_OPT_TAG             15
+
+/** Returned by QCBORDecode_Finish() if all the inputs bytes have not been consumed */
+#define QCBOR_ERR_EXTRA_BYTES             16
+
+
+/** See QCBORDecode_Init() */
+#define QCBOR_DECODE_MODE_NORMAL            0
+/** See QCBORDecode_Init() */
+#define QCBOR_DECODE_MODE_MAP_STRINGS_ONLY  1
+/** See QCBORDecode_Init() */
+#define QCBOR_DECODE_MODE_MAP_AS_ARRAY      2
+
+
+
+
+
+/* Do not renumber these. Code depends on some of these values. */
+/** Type for an integer that decoded either between INT64_MIN and INT32_MIN or INT32_MAX and INT64_MAX; val.int64 */
+#define QCBOR_TYPE_INT64          2
+/** Type for an integer that decoded to a more than INT64_MAX and UINT64_MAX; val.uint64 */
+#define QCBOR_TYPE_UINT64         3
+/** Type for an array. The number of items in the array is in val.uCount. */
+#define QCBOR_TYPE_ARRAY          4
+/** Type for a map; number of items in map is in val.uCount */ // todo note how map decoding works
+#define QCBOR_TYPE_MAP            5
+/** Type for a buffer full of bytes. Data is in val.string. */
+#define QCBOR_TYPE_BYTE_STRING    6
+/** Type for a UTF-8 string. It is not NULL terminated. Data is in val.string.  */
+#define QCBOR_TYPE_TEXT_STRING    7
+/** Type for a floating point number. Data is in val.float. */
+#define QCBOR_TYPE_FLOAT         26
+/** Type for a double floating point number. Data is in val.double. */
+#define QCBOR_TYPE_DOUBLE        27
+/** Type for a postive big number. Data is in val.bignum, a pointer and a length. */
+#define QCBOR_TYPE_POSBIGNUM     9
+/** Type for a negative big number. Data is in val.bignum, a pointer and a length. */
+#define QCBOR_TYPE_NEGBIGNUM     10
+/** Type for RFC xxxx date string, possibly with time zone.Data is in val.dateString */
+#define QCBOR_TYPE_DATE_STRING   11
+/** Type for integer seconds since Jan 1970 + floating point fraction. Data is in val.epochDate */
+#define QCBOR_TYPE_DATE_EPOCH    12
+/** A simple type that this CBOR implementation doesn't know about; Type is in val.uSimple. */
+#define QCBOR_TYPE_UKNOWN_SIMPLE 13
+/** Type for the simple value false; nothing more; nothing in val union. */
+#define QCBOR_TYPE_FALSE         20
+/** Type for the simple value true; nothing more; nothing in val union. */
+#define QCBOR_TYPE_TRUE          21
+/** Type for the simple value null; nothing more; nothing in val union. */
+#define QCBOR_TYPE_NULL          22
+/** Type for the simple value undef; nothing more; nothing in val union. */
+#define QCBOR_TYPE_UNDEF         23
+
+
+#define QCBOR_TYPE_OPTTAG     254 // Used internally; never returned
+#define QCBOR_TYPE_BREAK      255 // Used internally; never returned
+
+
+
+/*
+ Approx Size of this:
+   8 + 8 + 1 + 1 + 1 + (1 padding) + (4 padding on 64-bit machine) = 24 for first part (20 on a 32-bit machine)
+   16 bytes for the val union
+   16 bytes for label union
+   total = 56 bytes (52 bytes on 32-bit machine)
+ */
+
+/**
+ QCBORItem holds the type, value and other info for a decoded item returned by GetNextItem().
+ */
+typedef struct _QCBORItem {
+   uint8_t  uDataType;     /** Tells what element of the val union to use. One of QCBOR_TYPE_XXXX */
+   uint8_t  uNestingLevel; /** How deep the nesting from arrays and maps are. 0 is the top level with no arrays or maps entered */
+   uint8_t  uLabelType;    /** Tells what element of the label union to use */
+   
+   union {
+      int64_t     int64;      /** The value for uDataType QCBOR_TYPE_INT64 */
+      uint64_t    uint64;     /** The value for uDataType QCBOR_TYPE_UINT64 */
+
+      UsefulBufC  string;     /** The value for uDataType QCBOR_TYPE_BYTE_STRING and QCBOR_TYPE_TEXT_STRING */
+      uint16_t    uCount;     /** The "value" for uDataType QCBOR_TYPE_ARRAY or QCBOR_TYPE_MAP -- the number of items in the array or map */
+      float       fnum;       /** The value for uDataType QCBOR_TYPE_FLOAT */
+      double      dfnum;      /** The value for uDataType QCBOR_TYPE_DOUBLE */
+      struct {
+         int64_t  nSeconds;
+         double   fSecondsFraction;
+      } epochDate;            /** The value for uDataType QCBOR_TYPE_DATE_EPOCH */
+      UsefulBufC  dateString; /** The value for uDataType QCBOR_TYPE_DATE_STRING */
+      UsefulBufC  bigNum;     /** The value for uDataType QCBOR_TYPE_BIGNUM */
+      uint8_t     uSimple;    /** The integer value for unknown simple types */
+      
+   } val;  /** The union holding the item's value. Select union member based on uMajorType */
+   
+   union {
+      UsefulBufC  string;  /** The label for uLabelType QCBOR_TYPE_BYTE_STRING and QCBOR_TYPE_TEXT_STRING */
+      int64_t     int64;   /** The label for uLabelType for QCBOR_TYPE_INT64 */
+      uint64_t    uint64;  /** The label for uLabelType for QCBOR_TYPE_UINT64 */
+   } label; /** Union holding the different label types selected based on uLabelType */
+   
+   uint64_t uTag;     /** Any tag value that is greater than 63.  If there is more than one, then only the last one is recorded */
+   uint64_t uTagBits; /** Bits corresponding to tag values less than 63 as defined in RFC 7049, section 2.4 */
+   
+} QCBORItem;
+
+
+/** See the descriptions for CBOR_SIMPLEV_FALSE, CBOR_TAG_DATE_EPOCH... for
+    the meaning of the individual tags.  The values here are bit flags
+    associated with each tag.  These flags are set in uTagsBits in QCBORItem */
+#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 QCBOR_TAGFLAG_FRACTION       (0x01LL << CBOR_TAG_FRACTION)
+#define QCBOR_TAGFLAG_BIGFLOAT       (0x01LL << CBOR_TAG_BIGFLOAT)
+#define QCBOR_TAGFLAG_ENC_AS_B64URL  (0x01LL << CBOR_TAG_ENC_AS_B64URL)
+#define QCBOR_TAGFLAG_ENC_AS_B64     (0x01LL << CBOR_TAG_ENC_AS_B64)
+#define QCBOR_TAGFLAG_ENC_AS_B16     (0x01LL << CBOR_TAG_ENC_AS_B16)
+#define QCBOR_TAGFLAG_CBOR           (0x01LL << CBOR_TAG_CBOR)
+#define QCBOR_TAGFLAG_URI            (0x01LL << CBOR_TAG_URI)
+#define QCBOR_TAGFLAG_B64URL         (0x01LL << CBOR_TAG_B64URL)
+#define QCBOR_TAGFLAG_B64            (0x01LL << CBOR_TAG_B64)
+#define QCBOR_TAGFLAG_REGEX          (0x01LL << CBOR_TAG_REGEX)
+#define QCBOR_TAGFLAG_MIME           (0x01LL << CBOR_TAG_MIME)
+#define QCBOR_TAGFLAG_CBOR_MAGIC     (0x01ULL << 63)
+
+
+/**
+ Constant passed for paramenter nLabel to indicate that no integer
+ label should be added for this item. This also means that you can
+ never use INT64_MAX as an integer label.
+ */
+#define QCBOR_NO_INT_LABEL           INT64_MAX
+
+
+/**
+ Convert a non const EncodedCBOR to a const EncodedCBORC
+ 
+ @param[in] ECBOR The EncodedCBOR to convert
+ 
+ Returns: a EncodedCBORC struct
+ */
+static inline EncodedCBORC EncodedCBORConst(const EncodedCBOR ECBOR)
+{
+   return (EncodedCBORC){UsefulBufConst(ECBOR.Bytes), ECBOR.uItems};
+}
+
+
+/**
+ QCBOREncodeContext is the data type that holds context for all the
+ encoding functions. It is a little over 100 bytes so it can go on 
+ the stack. The contents are opaque and the caller should not access
+ any internal items.  A context may be re used serially as long as
+ it is re initialized.
+ */
+typedef struct _QCBOREncodeContext QCBOREncodeContext;
+
+
+/**
+ 
+ Initialize the the encoder to prepare to encode some CBOR.
+ 
+ @param[in,out]  pCtx    The encoder context to initialize.
+ @param[out]     pBuf    The buffer into which this encoded result will be placed.
+ @param[in]      uBufLen The length of pBuf.
+ 
+ @return
+ None.
+ 
+ Call this once at the start of an encoding of a CBOR structure. Then
+ call the various QCBOREncode_AddXXX() functions to add the data
+ items. Then call QCBOREncode_Finish().
+ 
+ The maximum output buffer is UINT32_MAX (4GB). This is not a practical
+ limit in any way and reduces the memory needed by the implementation.
+ The error QCBOR_ERR_BUFFER_TOO_LARGE will be returned by QCBOR_Finish()
+ if a larger buffer length is passed in.
+  
+ If this is called with pBuf as NULL and uBufLen a large value like
+ UINT32_MAX, all the QCBOREncode_AddXXXX() functions and
+ QCBORE_Encode_Finish() can still be called. No data will be encoded,
+ but the length of what would be encoded will be calculated. The
+ length of the encoded structure will be handed back in the call to
+ QCBOREncode_Finish(). You can then allocate a buffer of that size
+ and call all the encoding again, this time to fill in the buffer.
+ 
+ A QCBORContext can be reused over and over as long as
+ QCBOREncode_Init() is called.
+ 
+ */
+
+void QCBOREncode_Init(QCBOREncodeContext *pCtx, void *pBuf, size_t uBufLen);
+
+
+
+
+/**
+ 
+ @brief  Add a 64-bit integer to the encoded output
+ 
+ @param[in] pCtx      The encoding context to add the integer to.
+ @param[in] szLabel   The string map label for this integer value.
+ @param[in] nLabel    The integer map label for this integer value.
+ @param[in] uTag      A CBOR type 6 tag
+ @param[in] uNum      The integer to add.
+ 
+ @return
+ None.
+ 
+ The functions and macros with a "U" add unsigned integers and those
+ without add signed. The main reason to use the unsigned versions is
+ when the integers are in the range of MAX_INT to MAX_UINT, values
+ that can be expressed by a uint64_t, but not an int64_t.
+ 
+ This function figures out the size and the sign and encodes in the
+ correct minimal CBOR. Specifically it will select CBOR major type 0 or 1
+ based on sign and will encode to 1, 2, 4 or 8 bytes depending on the
+ value of the integer. Values less than 24 effectively encode to one
+ byte because they are encoded in with the CBOR major type.  This is
+ a neat and efficient characteristic of CBOR that can be taken
+ advantage of when designing CBOR-based protocols. If integers like
+ tags can be kept between -23 and 23 they will be encoded in one byte
+ including the major type.
+ 
+ If you pass a smaller int, say an int16_t or a small value, say 100,
+ the encoding will still be CBOR's most compact that can represent the
+ value.  For example CBOR always encodes the value 0 as one byte,
+ 0x00. The representation as 0x00 includes identfication of the type
+ as an integer too as the major type for an integer is 0. See RFC 7049
+ Appendix A for more examples of CBOR encoding. This compact encoding
+ is also cannonical CBOR as per section 3.9 in RFC 7049.
+ 
+ There are no functions to add int16_t or int32_t because they are
+ not necessary because this always encodes to the smallest number
+ of bytes based on the value (If this code is running on a 32-bit
+ machine having way to add 32-bit integers would reduce code size some).
+ 
+ If the encoding context is in an error state, this will do
+ nothing. If this causes an error such as going off the end of the
+ buffer an internal error flag will be set and the error will be
+ returned when QCBOREncode_Finish() is called.
+ 
+ */
+
+void QCBOREncode_AddInt64_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, int64_t nNum);
+void QCBOREncode_AddUInt64_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, uint64_t uNum);
+
+#define QCBOREncode_AddUInt64(pCtx, uNum) \
+      QCBOREncode_AddUInt64_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (uNum))
+
+#define QCBOREncode_AddUInt64ToMap(pCtx, szLabel, uNum) \
+      QCBOREncode_AddUInt64_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (uNum))
+
+#define QCBOREncode_AddUInt64ToMapN(pCtx, nLabel, uNum) \
+      QCBOREncode_AddUInt64_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (uNum))
+
+#define QCBOREncode_AddInt64(pCtx, nNum) \
+      QCBOREncode_AddInt64_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (nNum))
+
+#define QCBOREncode_AddInt64ToMap(pCtx, szLabel, nNum) \
+      QCBOREncode_AddInt64_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (nNum))
+
+#define QCBOREncode_AddInt64ToMapN(pCtx, nLabel, nNum) \
+      QCBOREncode_AddInt64_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (nNum))
+
+
+
+
+/**
+ 
+ @brief  Add a float or double value to the encoded output
+ 
+ @param[in] pCtx      The encoding context to add the float to.
+ @param[in] szLabel   The string map label for this integer value.
+ @param[in] nLabel    The integer map label for this integer value.
+ @param[in] uTag      A CBOR type 6 tag
+ @param[in] Num       The float to add.
+ 
+ @return
+ None.
+ 
+ This works the same as QCBOREncode_AddInt64_3() except it is for floats and doubles.
+ 
+ */
+void QCBOREncode_AddFloat_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, float fNum);
+void QCBOREncode_AddDouble_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, double dNum);
+
+#define QCBOREncode_AddFloat(pCtx, fNum) \
+      QCBOREncode_AddFloat_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (fNum))
+
+#define QCBOREncode_AddFloatToMap(pCtx, szLabel, fNum) \
+      QCBOREncode_AddFloat_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (fNum))
+
+#define QCBOREncode_AddFloatToMapN(pCtx, nLabel, fNum) \
+      QCBOREncode_AddFloat_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (fNum))
+
+#define QCBOREncode_AddDouble(pCtx, dNum) \
+      QCBOREncode_AddDouble_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (dNum))
+
+#define QCBOREncode_AddDoubleToMap(pCtx, szLabel, dNum) \
+      QCBOREncode_AddDouble_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (dNum))
+
+#define QCBOREncode_AddDoubleToMapN(pCtx, nLabel, dNum) \
+      QCBOREncode_AddDouble_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (dNum))
+
+
+
+/**
+ 
+ @brief  Add an epoch-based date
+ 
+ @param[in] pCtx     The encoding context to add the simple value to.
+ @param[in] szLabel  The string map label for this integer value.
+ @param[in] nLabel   The integer map label for this integer value.
+ @param[in] date     Number of seconds since 1970-01-01T00:00Z in UTC time.
+ 
+ @return
+ None.
+ 
+ As per RFC 7049 this is similar to UNIX/Linux/POSIX dates. This is
+ the most compact way to specify a date and time in CBOR. Note that this
+ is always UTC and does not include the time zone.  Use
+ QCBOREncode_AddDateString() if you want to include the time zone.
+ 
+ The integer encoding rules apply here so the date will be encoded in a
+ minimal number of 1, 2 4 or 8 bytes. Until about the year 2106 these
+ dates should encode in 6 bytes -- one byte for the tag, one byte for the type
+ and 4 bytes for the integer.
+ 
+ If you care about leap-seconds and that level of accuracy, make sure the
+ system you are running this code on does it correctly. This code just takes
+ the value passed in.
+ 
+ This implementation cannot encode fractional seconds using float or double
+ even though that is allowed by CBOR, but you can encode them if you
+ want to by calling QCBOREncode_AddFloat_3() or QCBOREncode_AddDouble_3()
+ with the right parameters.
+ 
+ Error handling is the same as QCBOREncode_AddInt64_3().
+ */
+
+static inline void QCBOREncode_AddDateEpoch_2(QCBOREncodeContext *pCtx, const char *szLabel, uint64_t nLabel, int64_t date)
+{
+   QCBOREncode_AddInt64_3(pCtx, szLabel, nLabel, CBOR_TAG_DATE_EPOCH, date);
+}
+
+#define QCBOREncode_AddDateEpoch(pCtx, date) \
+      QCBOREncode_AddDateEpoch_2((pCtx), NULL, QCBOR_NO_INT_LABEL, (date))
+
+#define QCBOREncode_AddDateEpochToMap(pCtx, szLabel, date) \
+      QCBOREncode_AddDateEpoch_2((pCtx), (szLabel), QCBOR_NO_INT_LABEL, (date))
+
+#define QCBOREncode_AddDateEpochToMapN(pCtx, nLabel, date) \
+      QCBOREncode_AddDateEpoch_2((pCtx), NULL, (nLabel), (date))
+
+
+
+
+/**
+ 
+ @brief Add a byte string to the encoded output.
+ 
+ @param[in] pCtx      The context to initialize.
+ @param[in] szLabel   The string map label for this integer value.
+ @param[in] nLabel    The integer map label for this integer value.
+ @param[in[ uTag      Optional CBOR data tag or CBOR_TAG_NONE.
+ @param[in] Bytes     Pointer and length of the input data.
+ 
+ @return
+ None.
+ 
+ Simply adds the bytes to the encoded output and CBOR major type 2.
+ 
+ If called with Bytes.len equal to 0, an empty string will be
+ added. When Bytes.len is 0, Bytes.ptr may be NULL.
+ 
+ */
+
+void QCBOREncode_AddBytes_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes);
+
+#define QCBOREncode_AddBytes(pCtx, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (Bytes))
+
+#define QCBOREncode_AddBytesToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (Bytes))
+
+#define QCBOREncode_AddBytesToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (Bytes))
+
+
+#define QCBOREncode_AddBinaryUUID(pCtx, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_BIN_UUID, (Bytes))
+
+#define QCBOREncode_AddBinaryUUIDToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_BIN_UUID, (Bytes))
+
+#define QCBOREncode_AddBinaryUUIDToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, (nLabel), CBOR_TAG_BIN_UUID, (Bytes))
+
+
+#define QCBOREncode_AddPositiveBignum(pCtx, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_POS_BIGNUM, (Bytes))
+
+#define QCBOREncode_AddPositiveBignumToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_POS_BIGNUM, (Bytes))
+
+#define QCBOREncode_AddPositiveBignumToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, (nLabel), CBOR_TAG_POS_BIGNUM, (Bytes))
+
+
+#define QCBOREncode_AddNegativeBignum(pCtx, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NEG_BIGNUM, (Bytes))
+
+#define QCBOREncode_AddNegativeBignumToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NEG_BIGNUM, (Bytes))
+
+#define QCBOREncode_AddNegativeBignumToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddBytes_3((pCtx), NULL, (nLabel), CBOR_TAG_NEG_BIGNUM, (Bytes))
+
+
+
+/**
+ 
+ @brief  Add a UTF-8 text string to the encoded output
+ 
+ @param[in] pCtx     The context to initialize.
+ @param[in] szLabel  The string map label for this integer value.
+ @param[in] nLabel   The integer map label for this integer value.
+ @param[in[ uTag     Optional CBOR data tag or CBOR_TAG_NONE.
+ @param[in] Bytes    Pointer and length of text to add.
+ 
+ @return
+ None
+ 
+ The text passed in must be unencoded UTF-8 according to RFC
+ 3629. There is no NULL termination.
+ 
+ If called with nBytesLen equal to 0, an empty string will be
+ added. When nBytesLen is 0, pBytes may be NULL.
+ 
+ 
+ Note that the restriction of the buffer length to an uint32_t is
+ entirely intentional as this encoder is not capable of encoding
+ lengths greater. This limit to 4GB for a text string should not be a
+ problem.
+ 
+ Error handling is the same as QCBOREncode_AddInt64_3().
+ 
+ */
+
+void QCBOREncode_AddText_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes);
+
+#define QCBOREncode_AddText(pCtx, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (Bytes))
+
+#define QCBOREncode_AddTextToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (Bytes))
+
+#define QCBOREncode_AddTextToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (Bytes))
+
+inline static void QCBOREncode_AddSZString_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, const char *szString) {
+   QCBOREncode_AddText_3(pCtx, szLabel, nLabel, uTag, SZToUsefulBufC(szString));
+}
+
+#define QCBOREncode_AddSZString(pCtx, szString) \
+      QCBOREncode_AddSZString_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (szString))
+
+#define QCBOREncode_AddSZStringToMap(pCtx, szLabel, szString) \
+      QCBOREncode_AddSZString_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (szString))
+
+#define QCBOREncode_AddSZStringToMapN(pCtx, nLabel, szString) \
+      QCBOREncode_AddSZString_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (szString))
+
+#define QCBOREncode_AddURI(pCtx, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_URI, (Bytes))
+
+#define QCBOREncode_AddURIToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_URI, (Bytes))
+
+#define QCBOREncode_AddURIToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, (nLabel), CBOR_TAG_URI, (Bytes))
+
+#define QCBOREncode_AddB64Text(pCtx, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_B64, (Bytes))
+
+#define QCBOREncode_AddB64TextToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_B64, (Bytes))
+
+#define QCBOREncode_AddB64TextToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, (nLabel), CBOR_TAG_B64, (Bytes))
+
+#define QCBOREncode_AddB64URLText(pCtx, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_B64URL, (Bytes))
+
+#define QCBOREncode_AddB64URLTextToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_B64URL, (Bytes))
+
+#define QCBOREncode_AddB64URLTextToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, (nLabel), CBOR_TAG_B64URL, (Bytes))
+
+#define QCBOREncode_AddRegex(pCtx, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_REGEX, (Bytes))
+
+#define QCBOREncode_AddRegexToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_REGEX, (Bytes))
+
+#define QCBOREncode_AddRegexToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, (nLabel), CBOR_TAG_REGEX, (Bytes))
+
+#define QCBOREncode_AddMIMEData(pCtx, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_MIME, (Bytes))
+
+#define QCBOREncode_AddMIMEDataToMap(pCtx, szLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_MIME, (Bytes))
+
+#define QCBOREncode_AddMIMEDataToMapN(pCtx, nLabel, Bytes) \
+      QCBOREncode_AddText_3((pCtx), NULL, (nLabel), CBOR_TAG_MIME, (Bytes))
+
+
+
+/**
+ 
+ @brief  Add an RFC 3339 date string
+ 
+ @param[in] pCtx      The encoding context to add the simple value to.
+ @param[in] szDate    Null-terminated string with date to add
+ @param[in] szLabel   A string label for the bytes to add. NULL if no label.
+ @param[in] nLabel    The integer map label for this integer value.
+ 
+ @return
+ None.
+ 
+ The string szDate should be in the form of RFC 3339 as refined by section
+ 3.3 in RFC 4287. This is as described in section 2.4.1 in RFC 7049.
+ 
+ Note that this function doesn't validate the format of the date string
+ at all. If you add an incorrect format date string, the generated
+ CBOR will be incorrect and the receiver may not be able to handle it.
+ 
+ Error handling is the same as QCBOREncode_AddInt64_3().
+ 
+ */
+
+#define QCBOREncode_AddDateString(pCtx, szDate) \
+      QCBOREncode_AddSZString_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_DATE_STRING, (szDate))
+
+#define QCBOREncode_AddDateStringToMap(pCtx, szLabel, szDate)  \
+      QCBOREncode_AddSZString_3(pCtx, (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_DATE_STRING, (szDate))
+
+#define QCBOREncode_AddDateStringToMapN(pCtx, nLabel, szDate)  \
+      QCBOREncode_AddSZString_3(pCtx, NULL, (nLabel), CBOR_TAG_DATE_STRING, (szDate))
+
+
+
+
+/**
+ 
+ @brief  Add true, false, null and undef
+ 
+ @param[in] pCtx      The encoding context to add the simple value to.
+ @param[in] szLabel   A string label for the bytes to add. NULL if no label.
+ @param[in] nLabel    The integer map label for this integer value.
+ @param[in] uTag      Optional CBOR data tag or CBOR_TAG_NONE.
+ @param[in] uSimple   One of CBOR_SIMPLEV_FALSE through _UNDEF
+ 
+ @return
+ None.
+
+ CBOR defines encoding for special values "true", "false", "null" and "undef". This
+ function can add these values.
+ 
+ Error handling is the same as QCBOREncode_AddInt64_3().
+ */
+void QCBOREncode_AddSimple_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uSimple);
+
+#define QCBOREncode_AddSimple(pCtx, uSimple) \
+      QCBOREncode_AddSimple_3((pCtx), NULL,  QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (uSimple))
+
+#define QCBOREncode_AddSimpleToMap(pCtx, szLabel, uSimple) \
+      QCBOREncode_AddSimple_3((pCtx), (szLabel),  QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (uSimple))
+
+#define QCBOREncode_AddSimpleToMapN(pCtx, nLabel, uSimple) \
+      QCBOREncode_AddSimple_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (uSimple))
+
+
+/**
+ 
+ @brief  Add a standard boolean
+ 
+ @param[in] pCtx      The encoding context to add the simple value to.
+ @param[in] szLabel   A string label for the bytes to add. NULL if no label.
+ @param[in] nLabel    The integer map label for this integer value.
+ @param[in] uTag      Optional CBOR data tag or CBOR_TAG_NONE.
+ @param[in] bool      true or false from stdbool. Anything will result in an error.
+ 
+ @return
+ None.
+ 
+ Error handling is the same as QCBOREncode_AddInt64_3().
+ */
+
+inline static void QCBOREncode_AddBool_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, bool b) {
+   uint8_t uSimple = CBOR_SIMPLE_BREAK; // CBOR_SIMPLE_BREAK is invalid here. The point is to cause an error later
+   if(b == true || b == false)
+      uSimple = CBOR_SIMPLEV_FALSE + b;;
+   QCBOREncode_AddSimple_3(pCtx, szLabel, nLabel, uTag, uSimple);
+}
+
+#define QCBOREncode_AddBool(pCtx, bool) \
+   QCBOREncode_AddBool_3((pCtx), NULL,  QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (bool))
+
+#define QCBOREncode_AddBoolToMap(pCtx, szLabel, bool) \
+   QCBOREncode_AddBool_3((pCtx), (szLabel),  QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, (bool))
+
+#define QCBOREncode_AddBoolToMapN(pCtx, nLabel, bool) \
+   QCBOREncode_AddBool_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, (bool))
+
+
+/**
+ 
+ @brief  Indicates that the next items added are in an array.
+ 
+ @param[in] pCtx The encoding context to open the array in.
+ @param[in] szLabel A NULL-terminated string label for the map. May be a NULL pointer.
+ @param[in] nLabel An integer label for the whole map. QCBOR_NO_INT_LABEL for no integer label.
+ @param[in] uTag A tag for the whole map or CBOR_TAG_NONE.
+ @param[in] bBstrWrap Indicates entire map should be wrapped as a binary string. Normally 0.
+ 
+ @return
+ None.
+ 
+ Arrays are the basic CBOR aggregate or structure type. Call this
+ function to start or open an array. The call the various AddXXX
+ functions to add the items that go into the array. Then call
+ QCBOREncode_CloseArray() when all items have been added.
+ 
+ Nesting of arrays and maps is allowed and supported just by calling
+ OpenArray again before calling CloseArray.  While CBOR has no limit
+ on nesting, this implementation does in order to keep it smaller and
+ simpler.  The limit is QCBOR_MAX_ARRAY_NESTING. This is the max
+ number of times this can be called without calling
+ QCBOREncode_CloseArray(). QCBOREncode_Finish() will return
+ QCBOR_ERR_ARRAY_TOO_LONG when it is called as this function just sets
+ an error state and returns no value when this occurs.
+ 
+ If you try to add more than 32,767 items to an array or map, incorrect CBOR will
+ be produced by this encoder.
+ 
+ An array itself may have a label if it is being added to a map. Either the
+ string array or integer label should be filled in, but not both. Note that
+ array elements do not have labels (but map elements do).
+ 
+ An array itself may be tagged.
+ 
+ When constructing signed CBOR objects, maps or arrays, they are encoded
+ normally and then wrapped as a byte string. The COSE standard for example
+ does this. The wrapping is simply treating the encoded CBOR map
+ as a byte string.
+ 
+ The stated purpose of this wrapping is to prevent code relaying the signed data
+ but not verifying it from tampering with the signed data thus making
+ the signature unverifiable. It is also quite beneficial for the
+ signature verification code. Standard CBOR parsers usually do not give
+ access to partially parsed CBOR as would be need to check the signature
+ of some CBOR. With this wrapping, standard CBOR parsers can be used
+ to get to all the data needed for a signature verification.
+ */
+
+void QCBOREncode_OpenArray_3(QCBOREncodeContext *pCtx, const char *szLabel, uint64_t nLabel, uint64_t uTag, bool bBstrWrap);
+
+#define QCBOREncode_OpenArray(pCtx) \
+      QCBOREncode_OpenArray_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, 0)
+
+#define QCBOREncode_OpenArrayInMap(pCtx, szLabel) \
+      QCBOREncode_OpenArray_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, 0)
+
+#define QCBOREncode_OpenArrayInMapN(pCtx, nLabel) \
+      QCBOREncode_OpenArray_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, 0)
+
+
+/**
+ 
+ @brief  Indicates that the next items added are in a map.
+ 
+ @param[in] pCtx The context to add to.
+ @param[in] szLabel A NULL-terminated string label for the map. May be a NULL pointer.
+ @param[in] nLabel An integer label for the whole map. QCBOR_NO_INT_LABEL for no integer label.
+ @param[in] uTag A tag for the whole map or CBOR_TAG_NONE.
+ @param[in] bBstrWrap Indicates entire map should be wrapped as a binary string. Normally 0.
+ 
+ @return
+ None.
+ 
+ See QCBOREncode_OpenArray() for more information.
+ 
+ When adding items to maps, they must be added in pairs, the label and
+ the value. This can be done making two calls to QCBOREncode_AddXXX
+ one for the map label and one for the value.
+ 
+ It can also be accomplished by calling one of the add functions that
+ takes an additional NULL-terminated text string parameter that is the
+ label.  This is useful for encoding CBOR you which to translate easily
+ to JSON.
+ 
+ Note that labels do not have to be strings. They can be integers or
+ other. Small integers < 24 are a good choice for map labels when the
+ size of the encoded data should be as small and simple as possible.
+
+ See the RFC7049 for a lot more information on creating maps.
+ 
+ */
+
+void QCBOREncode_OpenMap_3(QCBOREncodeContext *pCtx, const char *szLabel,  uint64_t nLabel, uint64_t uTag, uint8_t bBstrWrap);
+
+#define QCBOREncode_OpenMap(pCtx) \
+      QCBOREncode_OpenMap_3((pCtx), NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, 0)
+
+#define QCBOREncode_OpenMapInMap(pCtx, szLabel) \
+      QCBOREncode_OpenMap_3((pCtx), (szLabel), QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, 0)
+
+#define QCBOREncode_OpenMapInMapN(pCtx, nLabel) \
+      QCBOREncode_OpenMap_3((pCtx), NULL, (nLabel), CBOR_TAG_NONE, 0)
+
+
+/**
+ 
+ @brief Closes the current open array.
+ 
+ @param[in] pCtx The context to add to.
+ 
+ @return
+ None.
+ 
+ This reduces the nesting level by one.
+ 
+ If more Close's have been called than Open's the error state is
+ entered, no value is returned and the error can be discovered when
+ QCBOREncode_Finish() is called. The error will be
+ QCBOR_ERR_TOO_MANY_CLOSES.
+ */
+
+void QCBOREncode_CloseArray(QCBOREncodeContext *pCtx);
+
+#define QCBOREncode_CloseMap(pCtx)  QCBOREncode_CloseArray(pCtx)
+
+
+
+/**
+ Add some already-encoded CBOR bytes
+ 
+ @param[in] pCtx The context to add to.
+ @param[in] pEncodedCBOR The already-encoded CBOR to add to the context.
+ @param[in] nEncodedLength The length of pEncodedCBOR.
+ @param[in] nItems The number of items in the encoded CBOR.
+ 
+ @return
+ None.
+ 
+ The CBOR added here must be self-consistent and not have any arrays
+ or maps open. Specifically, if an array or map with N encoded items is
+ added all N items must be present in pEncodedCBOR.  This is because
+ the bytes added here are not examined in any way for correct CBOR
+ formatting or to figure out if all the arrays and maps are closed or
+ not.
+ 
+ If what you are adding is one array or map at the top level, then
+ pass 1 for nItems. This is really the main intended use for this
+ function.
+ 
+ Otherwise you must provide the correct count for the number of items,
+ particularly if you have a map or array open so the correct count can
+ be added when it is closed.
+ 
+ It is a good idea to use http://cbor.me, the CBOR playground to validate
+ CBOR generated when you use this function.
+ */
+
+void QCBOREncode_AddRaw(QCBOREncodeContext *pCtx, EncodedCBORC Encoded);
+
+
+
+
+/**
+ 
+ @brief  Add a simple value
+ 
+ @param[in] pCtx      The encoding context to add the simple value to.
+ @param[in] szLabel   A string label for the bytes to add. NULL if no label.
+ @param[in] nLabel    The integer map tag / label for this integer value.
+ @param[in[ uTag      Optional CBOR data tag or CBOR_TAG_NONE.
+ @param[in] uSimple   One of CBOR_SIMPLEV_xxx.
+ 
+ @return
+ None.
+ 
+ There should be no need to use this function directly unless some
+ extensions to the CBOR standard are created and put to use.  All the defined
+ simple types are available via the macros for false...null
+ below. Float and double are also simple types and have functions to
+ add them above.
+ 
+ Error handling is the same as QCBOREncode_AddInt64_3().
+ */
+void QCBOREncode_AddRawSimple_3(QCBOREncodeContext *pCtx, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uSimple);
+
+
+
+/**
+ Get the encoded CBOR and error status.
+ 
+ @param[in] pCtx  The context to finish encoding with.
+ @param[out] uEncodedLen The length of the encoded or potentially encoded CBOR in bytes.
+ 
+ @return
+ One of the CBOR error codes.
+ 
+ If this returns success QCBOR_SUCCESS the encoding was a success and
+ the return length is correct and complete.
+ 
+ If no buffer was passed to QCBOR_Init(), then only the length was
+ computed. If a buffer was passed, then the encoded CBOR is in the
+ buffer.
+ 
+ If an error is returned, the buffer may have partially encoded
+ incorrect CBOR in it and it should not be used. Likewise the length
+ may be incorrect and should not be used.
+ 
+ Note that the error could have occurred in one of the many
+ QCBOR_AddXXX calls long before QCBOREncode_Finish() was called. This
+ error handling reduces the CBOR implementation size, but makes
+ debugging harder.
+ 
+ */
+
+int QCBOREncode_Finish(QCBOREncodeContext *pCtx, size_t *uEncodedLen);
+
+
+
+/**
+ Get the encoded result.
+ 
+ @param[in] pCtx  The context to finish encoding with.
+ @param[out] pEncodedCBOR  Pointer and length of encoded CBOR.
+ 
+ @return
+ One of the CBOR error codes.
+ 
+ If this returns success QCBOR_SUCCESS the encoding was a success and
+ the return length is correct and complete.
+ 
+ If no buffer was passed to QCBOR_Init(), then only the length and
+ number of items was computed. The length is in
+ pEncodedCBOR->Bytes.len. The number of items is in
+ pEncodedCBOR->nItems. pEncodedCBOR->Bytes.ptr is NULL.
+ 
+ If a buffer was passed, then pEncodedCBOR->Bytes.ptr is the same as
+ the buffer passed to QCBOR_Init() and contains the encoded CBOR.
+ 
+ If an error is returned, the buffer may have partially encoded
+ incorrect CBOR in it and it should not be used. Likewise the length
+ may be incorrect and should not be used.
+ 
+ Note that the error could have occurred in one of the many
+ QCBOR_AddXXX calls long before QCBOREncode_Finish() was called. This
+ error handling reduces the CBOR implementation size, but makes
+ debugging harder.
+ 
+ */
+
+int QCBOREncode_Finish2(QCBOREncodeContext *pCtx, EncodedCBOR *pEncodedCBOR);
+
+
+
+
+
+
+/**
+ QCBORDecodeContext is the data type that holds context decoding the
+ data items for some received CBOR.  It is about 50 bytes so it can go
+ on the stack.  The contents are opaque and the caller should not
+ access any internal items.  A context may be re used serially as long
+ as it is re initialized.
+ */
+
+typedef struct _QCBORDecodeContext QCBORDecodeContext;
+
+
+/**
+ Initialize the CBOR decoder context.
+ 
+ @param[in] pCtx The context to initialize.
+ @param[in] EncodedCBOR The buffer with CBOR encoded bytes to be decoded.
+ @param[in] nMode One of QCBOR_DECODE_MODE_xxx
+ 
+ @return
+ None.
+ 
+ Initialize context for a pre-order traveral of the encoded CBOR tree.
+ 
+ Three decoding modes are supported.  In normal mode, maps are decoded
+ and strings and ints are accepted as map labels. If a label is other
+ than these, the error QCBOR_ERR_MAP_LABEL_TYPE is returned by
+ QCBORDecode_GetNext(). In strings-only mode, only text strings are
+ accepted for map labels.  This lines up with CBOR that converts to
+ JSON. The error QCBOR_ERR_MAP_LABEL_TYPE is returned by
+ QCBORDecode_GetNext() if anything but a text string label is
+ encountered. In array mode, the maps are treated as arrays. This will
+ decode any type of label, but the caller must figure out all the map
+ decoding.
+ 
+ */
+
+void QCBORDecode_Init(QCBORDecodeContext *pCtx, UsefulBufC EncodedCBOR, int8_t nMode);
+
+
+/**
+ Gets the next item (integer, byte string, array...) in pre order traversal of CBOR tree
+ 
+ @param[in]  pCtx          The context to initialize
+ @param[out] pDecodedItem  Holds the CBOR item just decoded.
+ 
+ @return
+ 0 or error.
+ 
+ pDecodedItem is filled in with the value parsed. Generally, the
+ folloinwg data is returned in the structure.
+ 
+ - The data type in uDataType which indicates which member of the val
+   union the data is in. This decoder figure out the type based on the
+   CBOR major type, the CBOR "additionalInfo", the CBOR optional tags
+   and the value of the integer.
+ 
+ - The value of the item, which might be an integer, a pointer and a
+   length, the count of items in an array, a floating point number or
+   other.
+ 
+ - The nesting level for maps and arrays.
+ 
+ - The label for an item in a map, which may be a text or byte string or an integer.
+ 
+ - The CBOR optional tag or tags.
+ 
+ See documentation on in the data type QCBORItem for all the details
+ on what is returned.
+ 
+ This function also handles arrays and maps. When first encountered a
+ QCBORItem will be returned with major type CBOR_MAJOR_TYPE_ARRAY or
+ CBOR_MAJOR_TYPE_ARRAY_MAP. QCBORItem.nCount will indicate the number
+ if Items in the array or map.  Typically an implementation will call
+ QCBORDecode_GetNext() in a for loop to fetch them all.
+ 
+ Optional tags are integer tags that are prepended to the actual data
+ item. That tell more about the data. For example it can indicate data
+ is a date or a big number or a URL.
+ 
+ Note that when traversing maps, the count is the number of pairs of
+ items, so the for loop would decrement once for every two calls to
+ QCBORDecode_GetNext().
+ 
+ Nesting level 0 is the outside top-most nesting level. For example in
+ a CBOR structure with two items, an integer and a byte string only,
+ both would be at nesting level 0.  A CBOR structure with an array
+ open, an integer and a byte string, would have the integer and byte
+ string as nesting level 1.
+ 
+ Here is an example of how the nesting level is reported with no arrays
+ or maps at all
+ 
+ @verbatim
+ CBOR Structure           Nesting Level
+ Integer                    0
+ Byte String                0
+ @endverbatim
+ 
+ Here is an example of how the nesting level is reported with an a simple
+ array and some top-level items.
+ 
+ @verbatim
+ Integer                    0
+ Array (with 2 items)       0
+ Byte String                1
+ Byte string                1
+ Integer                    0
+ @endverbatim
+ 
+ 
+ Here's a more complex example
+ @verbatim
+ 
+ Map with 2 items           0
+ Text string                1
+ Array with 3 integers      1
+ integer                    2
+ integer                    2
+ integer                    2
+ text string                1
+ byte string                1
+ @endverbatim
+ 
+ */
+
+int QCBORDecode_GetNext(QCBORDecodeContext *pCtx, QCBORItem *pDecodedItem);
+
+
+/**
+ Check whether all the bytes have been decoded
+ 
+ @param[in]  pCtx          The context to check
+ 
+ @return QCBOR_ERR_EXTRA_BYTES or QCBOR_SUCCESS
+ 
+ This tells you if all the bytes give to QCBORDecode_Init() have
+ been consumed or not. In most cases all bytes should be consumed
+ in a correct parse. 
+ 
+ It is OK to call this multiple times during decoding and to call
+ QCBORDecode_GetNext() after calling this. This only
+ performs a check. It does not change the state of the decoder.
+ */
+
+int QCBORDecode_Finish(QCBORDecodeContext *pCtx);
+
+
+
+/**
+  Convert int64_t to smaller int's safely
+ 
+ @param src[in]    An int64_t
+ @param dest[out]  A smaller sized int to convert to
+  
+ @return 0 on success -1 if not
+ 
+ When decoding an integer the CBOR decoder will return the value as an
+ int64_t unless the integer is in the range of INT64_MAX and
+ UINT64_MAX. That is, unless the value is so large that it can only be
+ represented as a uint64_t, it will be an int64_t.
+ 
+ CBOR itself doesn't size the individual integers it carries at
+ all. The only limits it puts on the major integer types is that they
+ are 8 bytes or less in length. Then encoders like this one use the
+ smallest number of 1, 2, 4 or 8 bytes to represent the integer based
+ on its value. There is thus no notion that one data item in CBOR is
+ an 1 byte integer and another is a 4 byte integer.
+ 
+ The interface to this CBOR encoder only uses 64-bit integers. Some
+ CBOR protocols or implementations of CBOR protocols may not want to
+ work with something smaller than a 64-bit integer.  Perhaps an array
+ of 1000 integers needs to be sent and none has a value larger than
+ 50,000 and are represented as uint16_t.
+ 
+ The sending / encoding side is easy. Integers are temporarily widened
+ to 64-bits as a parameter passing through QCBOREncode_AddInt64() and
+ encoded in the smallest way possible for their value, possibly in
+ less than an uint16_t.
+ 
+ On the decoding side the integers will be returned at int64_t even if
+ they are small and were represented by only 1 or 2 bytes in the
+ encoded CBOR. The functions here will convert integers to a small
+ representation with an overflow check.
+ 
+ (The decoder could have support 8 different integer types and
+ represented the integer with the smallest type automatically, but
+ this would have made the decoder more complex and code calling the
+ decoder more complex in most use cases.  In most use cases on 64-bit
+ machines it is no burden to carry around even small integers as
+ 64-bit values)
+ 
+ */
+
+static inline int QCBOR_Int64ToInt32(int64_t src, int32_t *dest)
+{
+   if(src > INT32_MAX || src < INT32_MIN) {
+      return -1;
+   } else {
+      *dest = (int32_t) src;
+   }
+   return 0;
+}
+
+static inline int QCBOR_Int64ToInt16(int64_t src, int16_t *dest)
+{
+   if(src > INT16_MAX || src < INT16_MIN) {
+      return -1;
+   } else {
+      *dest = (int16_t) src;
+   }
+   return 0;
+}
+
+static inline int QCBOR_Int64ToInt8(int64_t src, int8_t *dest)
+{
+   if(src > INT8_MAX || src < INT8_MIN) {
+      return -1;
+   } else {
+      *dest = (int8_t) src;
+   }
+   return 0;
+}
+
+static inline int QCBOR_Int64ToUInt32(int64_t src, uint32_t *dest)
+{
+   if(src > UINT32_MAX || src < 0) {
+      return -1;
+   } else {
+      *dest = (uint32_t) src;
+   }
+   return 0;
+}
+
+static inline int QCBOR_Int64UToInt16(int64_t src, uint16_t *dest)
+{
+   if(src > UINT16_MAX || src < 0) {
+      return -1;
+   } else {
+      *dest = (uint16_t) src;
+   }
+   return 0;
+}
+
+static inline int QCBOR_Int64ToUInt8(int64_t src, uint8_t *dest)
+{
+   if(src > UINT8_MAX || src < 0) {
+      return -1;
+   } else {
+      *dest = (uint8_t) src;
+   }
+   return 0;
+}
+
+static inline int QCBOR_Int64ToUInt64(int64_t src, uint64_t *dest)
+{
+   if(src > 0) {
+      return -1;
+   } else {
+      *dest = (uint64_t) src;
+   }
+   return 0;
+}
+
+
+
+#endif /* defined(__QCBOR__qcbor__) */
+
diff --git a/src/UsefulBuf.c b/src/UsefulBuf.c
new file mode 100644
index 0000000..7fc5e12
--- /dev/null
+++ b/src/UsefulBuf.c
@@ -0,0 +1,345 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. 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 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 <string.h>
+#include "UsefulBuf.h"
+#include <stringl.h>
+
+#define USEFUL_OUT_BUF_MAGIC  (0x0B0F) // used to catch use of uninitialized or corrupted UOBs
+
+/*
+   Public function -- see UsefulBuf.h
+ */
+int UsefulBuf_Copy(UsefulBuf *pDest, const UsefulBufC Src)
+{
+   if(Src.len > pDest->len)
+      return 1;
+   
+   memscpy(pDest->ptr, pDest->len, Src.ptr, Src.len);
+   
+   pDest->len = Src.len;
+   
+   return 0;
+}
+
+/*
+   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
+ */
+void UsefulBuf_Set(UsefulBuf *pDest, uint8_t value)
+{
+   memset(pDest->ptr, value, pDest->len);
+}
+
+
+/*
+ returns SIZE_MAX when there is no match
+ */
+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
+ 
+ The core of UsefulOutBuf -- put some bytes in the buffer without writing off the end of it.
+ 
+ THIS FUNCTION DOES POINTER MATH
+ */
+void UsefulOutBuf_Init(UsefulOutBuf *me, void *pStorage, size_t uStorageSize)
+{
+   me->magic  = USEFUL_OUT_BUF_MAGIC;
+   UsefulOutBuf_Reset(me);
+   
+   me->UB.ptr = pStorage;
+   me->size   = uStorageSize;
+
+   // The following check fails on ThreadX
+#if 0
+   // 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 - uStorageSize;
+   if(pStorage && (uintptr_t)pStorage > 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 -- length of valid data in the buffer
+   me->size -- size of the buffer UB.ptr
+ 
+ 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->UB.len > me->size) {  // 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->UB.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->size
+   if(uInsertionPos > me->UB.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->UB.len - uInsertionPos; // PtrMath #2
+   uint8_t *pDestinationOfMove  = pSourceOfMove + NewData.len; // PtrMath #3
+   size_t   uRoomInDestination  = me->size - (uInsertionPos + NewData.len); // PtrMath #4
+   
+   if(uNumBytesToMove && me->UB.ptr) {
+      memsmove(pDestinationOfMove, uRoomInDestination, pSourceOfMove, uNumBytesToMove);
+   }
+   
+   /* 4. Put the new data in */
+   uint8_t *pInsertionPoint = ((uint8_t *)me->UB.ptr) + uInsertionPos; // PtrMath #5
+   uRoomInDestination       = me->size - uInsertionPos; // PtrMath #6
+   if(me->UB.ptr) {
+      memsmove(pInsertionPoint, uRoomInDestination, NewData.ptr, NewData.len);
+   }
+   me->UB.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->size doesn't wrap
+   Check #1 makes sure me->UB.len is less than me->size
+   Check #3 makes sure uInsertionPos is less than me->UB.len
+ 
+ PtrMath #2 will never wrap around under because
+   Check #3 makes sure uInsertionPos is less than me->UB.len
+ 
+ PtrMath #3 will never wrap around over because   todo
+   PtrMath #1 is checked resulting in pStartOfDataToMove being between me->UB.ptr and a maximum valid ptr
+   
+ PtrMath #4 will never wrap under because
+    Check #3 makes sure uInsertionPos is less than me->UB.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
+   Check #1 makes sure me->UB.len is less than me->size
+   Check #3 makes sure uInsertionPos is less than me->UB.len
+ */
+
+
+/*
+ Public function -- see UsefulBuf.h
+ 
+ Returns the resulting valid data in a UsefulBuf
+ 
+ */
+int UsefulOutBuf_OutUBuf(UsefulOutBuf *me, UsefulBuf *O)
+{
+   if(me->err) {
+      return me->err;
+   }
+   
+   if(me->magic != USEFUL_OUT_BUF_MAGIC) {
+      me->err = 1;
+      return 1;
+   }
+   
+   *O = me->UB;
+   return 0;
+}
+
+
+/*
+ Public function -- see UsefulBuf.h
+
+ Copy out the data accumulated in the output buffer.
+ 
+ */
+int UsefulOutBuf_CopyOut(UsefulOutBuf *me, void *pBuf, size_t uBufSize, size_t *puCopied)
+{
+   UsefulBuf B;
+   if(UsefulOutBuf_OutUBuf(me, &B)) {
+      return 1; // was in error state or was corrupted
+   }
+   
+   if(B.len > uBufSize) {
+      return 1; // buffer was too small
+   }
+   
+   memsmove(pBuf, uBufSize, B.ptr, B.len);
+
+   *puCopied = me->UB.len;
+   
+   return 0;
+}
+
+
+
+
+/*
+ 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/src/qcbor_decode.c b/src/qcbor_decode.c
new file mode 100644
index 0000000..b412205
--- /dev/null
+++ b/src/qcbor_decode.c
@@ -0,0 +1,708 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. 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 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
+ --------           ----            ---------------------------------------------------
+ 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 <stdint.h>
+
+#ifdef QSEE
+#include "stringl.h"
+#endif
+
+
+/*
+ Collection of functions to track the map and 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_TypeIsMap(const QCBORDecodeNesting *pNesting)
+{
+   if(!DecodeNesting_IsNested(pNesting))
+      return 0;
+   
+   return CBOR_MAJOR_TYPE_MAP == pNesting->pCurrent->uMajorType;
+}
+
+inline static void DecodeNesting_Decrement(QCBORDecodeNesting *pNesting, uint8_t uDataType)
+{
+   if(!DecodeNesting_IsNested(pNesting)) {
+      return;  // at top level where there is no tracking
+   }
+   
+   // Decrement
+   pNesting->pCurrent->uCount--;
+   
+   // Pop up nesting levels if the counts at the levels is zero
+   while(0 == pNesting->pCurrent->uCount && DecodeNesting_IsNested(pNesting)) {
+      pNesting->pCurrent--;
+   }
+}
+
+inline static int DecodeNesting_Descend(QCBORDecodeNesting *pNesting, uint8_t uMajorType, int uCount)
+{
+   int nReturn = QCBOR_SUCCESS;
+   
+   if(uCount > QCBOR_MAX_ITEMS_IN_ARRAY) {
+      nReturn = QCBOR_ERR_ARRAY_TOO_LONG;
+      goto Done;
+   }
+   
+   if(pNesting->pCurrent >= &(pNesting->pMapsAndArrays[QCBOR_MAX_ARRAY_NESTING])) {
+      nReturn = QCBOR_ERR_ARRAY_NESTING_TOO_DEEP;
+      goto Done;
+   }
+   
+   pNesting->pCurrent++;
+   
+   pNesting->pCurrent->uMajorType = uMajorType;
+   pNesting->pCurrent->uCount     = uCount;
+   
+Done:
+   return nReturn;;
+}
+
+inline static uint8_t DecodeNesting_GetLevel(QCBORDecodeNesting *pNesting)
+{
+   return pNesting->pCurrent - &(pNesting->pMapsAndArrays[0]);
+}
+
+inline static void DecodeNesting_Init(QCBORDecodeNesting *pNesting)
+{
+   pNesting->pCurrent = &(pNesting->pMapsAndArrays[0]);
+}
+
+
+
+
+/*
+ Public function, see header file
+ */
+void QCBORDecode_Init(QCBORDecodeContext *me, UsefulBufC EncodedCBOR, int8_t 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));
+}
+
+
+/*
+ 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.
+ 
+ */
+inline static int DecodeTypeAndNumber(UsefulInputBuf *pUInBuf, int *pnMajorType, uint64_t *puNumber, uint8_t *puAdditionalInfo)
+{
+   int nReturn;
+   
+   // Get the initial byte that every CBOR data item has
+   const uint8_t InitialByte = UsefulInputBuf_GetByte(pUInBuf);
+   
+   // Break down the initial byte
+   const uint8_t uTmpMajorType   = InitialByte >> 5;
+   const uint8_t uAdditionalInfo = InitialByte & 0x1f;
+   
+   // Get the integer that follows the major type. Do not know if this is a length, value, float or tag at this point
+   // Also convert from network byte order. Call ntohxx on simple variables in case they are macros that
+   // reference their argument multiple times.
+   uint64_t uTmpValue;
+   switch(uAdditionalInfo) {
+         
+      case LEN_IS_ONE_BYTE:
+         uTmpValue = UsefulInputBuf_GetByte(pUInBuf);
+         break;
+         
+      case LEN_IS_TWO_BYTES:
+         uTmpValue = UsefulInputBuf_GetUint16(pUInBuf);
+         break;
+         
+      case LEN_IS_FOUR_BYTES:
+         uTmpValue = UsefulInputBuf_GetUint32(pUInBuf);
+         break;
+         
+      case LEN_IS_EIGHT_BYTES:
+         uTmpValue = UsefulInputBuf_GetUint64(pUInBuf);
+         break;
+         
+      case ADDINFO_RESERVED1: // reserved by CBOR spec
+      case ADDINFO_RESERVED2: // reserved by CBOR spec
+      case ADDINFO_RESERVED3: // reserved by CBOR spec
+      case LEN_IS_INDEFINITE: // indefinite types not supported (yet)
+         nReturn = QCBOR_ERR_UNSUPPORTED;
+         goto Done;
+         
+      default:
+         uTmpValue = uAdditionalInfo;
+         break;
+   }
+   
+   // If any of the UsefulInputBuf_Get calls fail we will get here with uTmpValue as 0.
+   // There is no harm in this. This following check takes care of catching all of
+   // these errors. 
+   
+   if(UsefulInputBuf_GetError(pUInBuf)) {
+      nReturn = QCBOR_ERR_HIT_END;
+      goto Done;
+   }
+   
+   // All successful if we got here.
+   nReturn           = QCBOR_SUCCESS;
+   *pnMajorType      = uTmpMajorType;
+   *puNumber         = uTmpValue;
+   *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 int DecodeInteger(int nMajorType, uint64_t uNumber, QCBORItem *pDecodedItem)
+{
+   int 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_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 int DecodeSimple(uint8_t uAdditionalInfo, uint64_t uNumber, QCBORItem *pDecodedItem)
+{
+   int 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
+      case CBOR_SIMPLE_BREAK:  // 31
+         nReturn = QCBOR_ERR_UNSUPPORTED;
+         break;
+         
+      case CBOR_SIMPLEV_FALSE: // 20
+      case CBOR_SIMPLEV_TRUE:  // 21
+      case CBOR_SIMPLEV_NULL:  // 22
+      case CBOR_SIMPLEV_UNDEF: // 23
+         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;
+         }
+         // 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
+ */
+inline static int DecodeBytes(int nMajorType, uint64_t uNumber, UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem)
+{
+   const void *pBytes = UsefulInputBuf_GetBytes(pUInBuf, uNumber);
+   
+   int nReturn = QCBOR_ERR_HIT_END; 
+   
+   if(pBytes != NULL) {
+      pDecodedItem->val.string.ptr = pBytes;
+      pDecodedItem->val.string.len = uNumber;
+      pDecodedItem->uDataType      = (nMajorType == CBOR_MAJOR_TYPE_BYTE_STRING) ? QCBOR_TYPE_BYTE_STRING : QCBOR_TYPE_TEXT_STRING;
+      nReturn = QCBOR_SUCCESS;
+   }
+   
+   return nReturn;
+}
+
+
+/*
+ Mostly just assign the right data type for the date string.
+ */
+inline static int DecodeDateString(QCBORItem Item, QCBORItem *pDecodedItem)
+{
+   if(Item.uDataType != QCBOR_TYPE_TEXT_STRING) {
+      return QCBOR_ERR_BAD_OPT_TAG;
+   }
+   pDecodedItem->val.dateString = Item.val.string;
+   pDecodedItem->uDataType = QCBOR_TYPE_DATE_STRING;
+   pDecodedItem->uTagBits = Item.uTagBits;
+   pDecodedItem->uTag = Item.uTag;
+   return QCBOR_SUCCESS;
+}
+
+
+/*
+ Mostly just assign the right data type for the bignum.
+ */
+inline static int DecodeBigNum(QCBORItem Item, QCBORItem *pDecodedItem, uint64_t uTagFlags)
+{
+   if(Item.uDataType != QCBOR_TYPE_BYTE_STRING) {
+      return QCBOR_ERR_BAD_OPT_TAG;
+   }
+   pDecodedItem->val.bigNum     = Item.val.string;
+   pDecodedItem->uDataType      = uTagFlags & QCBOR_TAGFLAG_POS_BIGNUM ? QCBOR_TYPE_POSBIGNUM : QCBOR_TYPE_NEGBIGNUM;
+   pDecodedItem->uTagBits       = Item.uTagBits;
+   pDecodedItem->uTag           = Item.uTag;
+   return QCBOR_SUCCESS;
+}
+
+
+/*
+ The epoch formatted date. Turns lots of different forms of encoding date into uniform one
+ */
+static int DecodeDateEpoch(QCBORItem Item, QCBORItem *pDecodedItem)
+{
+   int nReturn = QCBOR_SUCCESS;
+   
+   pDecodedItem->uTagBits                       = Item.uTagBits;
+   pDecodedItem->uTag                           = Item.uTag;
+   pDecodedItem->uDataType                      = QCBOR_TYPE_DATE_EPOCH;
+   pDecodedItem->val.epochDate.fSecondsFraction = 0;
+   
+   switch (Item.uDataType) {
+         
+      case QCBOR_TYPE_INT64:
+         pDecodedItem->val.epochDate.nSeconds = Item.val.int64;
+         break;
+         
+      case QCBOR_TYPE_UINT64:
+         if(Item.val.uint64 > INT64_MAX) {
+            nReturn = QCBOR_ERR_DATE_OVERFLOW; 
+            goto Done;
+         }
+         pDecodedItem->val.epochDate.nSeconds = Item.val.uint64;
+         break;
+         
+      default:
+         nReturn = QCBOR_ERR_BAD_OPT_TAG;
+   }
+   
+Done:
+   return nReturn;
+}
+
+
+/*
+ Decode the optional tagging that preceeds the real data value. There could be lots of them.
+ */
+static int GetAnItem(UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem, int bCalledFromDecodeOptional);
+
+/*
+ Returns an error if there was something wrong with the optional item or it couldn't
+ be handled.
+ */
+static int DecodeOptional(UsefulInputBuf *pUInBuf, uint64_t uInputTag, QCBORItem *pDecodedItem)
+{
+   int      nReturn = QCBOR_SUCCESS;
+   
+   uint64_t uTagFlags = 0; // accumulate the tags in the form of flags
+   uint64_t uTagToProcess = uInputTag; // First process tag passed in
+   
+   QCBORItem Item;
+   
+   do {
+      if(uTagToProcess < 63) { // 63 is the number of bits in a uint64 - 1
+         uTagFlags |= 0x01LL << uTagToProcess;
+      } else if(uTagToProcess == CBOR_TAG_CBOR_MAGIC) {
+         uTagFlags |= QCBOR_TAGFLAG_CBOR_MAGIC;
+      }
+      /* This code ignores the all but the first tag of value
+         greater than 63. Ignoring tags that are not understoof
+         is allowed by the standard. Multiple tags are 
+         presumably rare. */
+      
+      nReturn = GetAnItem(pUInBuf, &Item, 1);
+      if(nReturn) {
+         // Bail out of the whole item fetch on any sort of error here
+         goto Done;
+      }
+      
+      if(Item.uDataType != QCBOR_TYPE_OPTTAG) {
+         break;
+      }
+      
+      uTagToProcess = Item.uTag;
+   } while (1);
+
+   
+   /*
+     CBOR allows multiple tags on a data item. It also defines
+     a number of standard tag values, most of which are 
+     less than 64.  This code can deal with multiple tag
+     values that are less than 64 and the last tag of multiple
+     if the value is more than 64. Or said another way
+     if there is one tag with a value >64 this code works. 
+    
+     The assumption is that multiple tag values > 64 are rare.
+    
+     At this point in this code. uTagFlags has all the flags
+     < 64 and uTagToProcess has the last tag.
+    
+     Does this deal with multiple tags on an item we process?
+    */
+   
+   Item.uTagBits = uTagFlags;
+   Item.uTag = uTagToProcess;
+   
+   switch(uTagFlags & (QCBOR_TAGFLAG_DATE_STRING | QCBOR_TAGFLAG_DATE_EPOCH | QCBOR_TAGFLAG_POS_BIGNUM |QCBOR_TAGFLAG_NEG_BIGNUM)) {
+      case 0:
+         // No tags we know about. Pass them up
+         *pDecodedItem = Item;
+         break;
+         
+      case QCBOR_TAGFLAG_DATE_STRING:
+         nReturn = DecodeDateString(Item, pDecodedItem);
+         break;
+         
+      case QCBOR_TAGFLAG_DATE_EPOCH:
+         nReturn = DecodeDateEpoch(Item, pDecodedItem);
+         break;
+         
+      case QCBOR_TAGFLAG_POS_BIGNUM:
+      case QCBOR_TAGFLAG_NEG_BIGNUM:
+         nReturn = DecodeBigNum(Item, pDecodedItem, uTagFlags);
+         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;
+}
+
+
+
+// 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 int GetAnItem(UsefulInputBuf *pUInBuf, QCBORItem *pDecodedItem, int bCalledFromDecodeOptional)
+{
+   int 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;
+   
+   pDecodedItem->uTagBits = 0;
+   pDecodedItem->uTag     = 0;
+   
+   // 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
+         nReturn = DecodeBytes(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;
+         }
+         pDecodedItem->val.uCount = 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->uTag      = uNumber;
+         pDecodedItem->uDataType = QCBOR_TYPE_OPTTAG;
+         if(!bCalledFromDecodeOptional) {
+            // There can be a more than one optional tag in front of an actual data item
+            // they are all handled by looping in DecodeOptional which calls back here
+            // this test avoids infinite recursion.
+            nReturn = DecodeOptional(pUInBuf, uNumber, pDecodedItem);
+         }
+         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;
+}
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+int QCBORDecode_GetNext(QCBORDecodeContext *me, QCBORItem *pDecodedItem)
+{
+   int nReturn;
+   
+   if(!UsefulInputBuf_BytesUnconsumed(&(me->InBuf))) {
+      nReturn = QCBOR_ERR_HIT_END;
+      goto Done;
+   }
+   
+   nReturn = GetAnItem(&(me->InBuf), pDecodedItem, 0);
+   if(nReturn)
+      goto Done;
+   
+   // If in a map and the right decoding mode, get the label
+   if(DecodeNesting_TypeIsMap(&(me->nesting)) && me->uDecodeMode != QCBOR_DECODE_MODE_MAP_AS_ARRAY) {
+      // In a map and caller wants maps decoded, not treated as arrays
+      
+      // Get the next item which will be the real data; Item will be the label
+      QCBORItem LabelItem = *pDecodedItem;
+      nReturn = GetAnItem(&(me->InBuf), pDecodedItem, 0);
+      if(nReturn)
+         goto Done;
+      
+      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->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.
+         nReturn = QCBOR_ERR_MAP_LABEL_TYPE ;
+         goto Done;
+      }
+   }
+   
+   // Record the nesting level for this data item
+   pDecodedItem->uNestingLevel = DecodeNesting_GetLevel(&(me->nesting));
+   
+   // If the new item is a non-empty array or map, the nesting level descends
+   if(IsMapOrArray(pDecodedItem->uDataType) && pDecodedItem->val.uCount) {
+      nReturn = DecodeNesting_Descend(&(me->nesting), pDecodedItem->uDataType, pDecodedItem->val.uCount);
+   } else {
+      // Track number of items in maps and arrays and ascend nesting if all are consumed
+      // Note that an empty array or map is like a integer or string in effect here
+      DecodeNesting_Decrement(&(me->nesting), pDecodedItem->uDataType);
+   }
+   
+Done:
+   return nReturn;
+}
+
+
+/*
+ Public function, see header qcbor.h file
+ */
+int QCBORDecode_Finish(QCBORDecodeContext *me)
+{
+   return UsefulInputBuf_BytesUnconsumed(&(me->InBuf)) ? QCBOR_ERR_EXTRA_BYTES : QCBOR_SUCCESS;
+}
+
+
+
+/* 
+ 
+Decoder errors handled in this file
+ 
+ - Hit end of input before it was expected while decoding type and number QCBOR_ERR_HIT_END
+ 
+ - indefinite length, currently not supported QCBOR_ERR_UNSUPPORTED
+ 
+ - 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
+ 
+ - Encountered a break, not supported because indefinite lengths are not supported 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
+ 
+ */
+
diff --git a/src/qcbor_encode.c b/src/qcbor_encode.c
new file mode 100644
index 0000000..7b53ac1
--- /dev/null
+++ b/src/qcbor_encode.c
@@ -0,0 +1,632 @@
+/*==============================================================================
+Copyright (c) 2016-2018, The Linux Foundation. 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 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
+ --------           ----            ---------------------------------------------------
+ 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 <stdint.h>
+
+#ifdef QSEE
+#include "stringl.h"
+#endif
+
+/*...... This is a ruler that is 80 characters long...........................*/
+
+
+// Used internally in the impementation here
+// Must not conflict with any of the official CBOR types
+#define CBOR_MAJOR_NONE_TYPE_RAW  9
+
+
+
+
+
+/*
+ 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 int Nesting_Increase(QCBORTrackNesting *pNesting, uint8_t uMajorType, uint32_t uPos, bool bBstWrap)
+{
+   int 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;
+      pNesting->pCurrentNesting->bBstrWrap  = bBstWrap;
+   }
+   return nReturn;
+}
+
+inline static void Nesting_Decrease(QCBORTrackNesting *pNesting)
+{
+   pNesting->pCurrentNesting--;
+}
+
+inline static int Nesting_Increment(QCBORTrackNesting *pNesting, uint16_t uAmount)
+{
+   if(uAmount >= QCBOR_MAX_ITEMS_IN_ARRAY - pNesting->pCurrentNesting->uCount) {
+      return QCBOR_ERR_ARRAY_TOO_LONG;
+   }
+      
+   pNesting->pCurrentNesting->uCount += uAmount;
+   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 the subtraction returns either 1 or 2.
+   return pNesting->pCurrentNesting->uCount / (pNesting->pCurrentNesting->uMajorType - CBOR_MAJOR_TYPE_ARRAY+1);
+}
+
+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;
+}
+
+inline static bool Nesting_IsBstrWrapped(QCBORTrackNesting *pNesting)
+{
+   return pNesting->pCurrentNesting->bBstrWrap;
+}
+
+
+
+/*
+ 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 the buffer is full or not in its
+ context.  Once either of these errors is set they are never
+ cleared. Only 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 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.  Once we prove that is the only consequence, then we can make
+ the change.
+ 
+ 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 make automatically size some of the data
+ structures like array/map nesting resulting in some good memory
+ savings.
+ */
+
+
+
+
+/*
+ Public function for initialization. See header qcbor.h
+ */
+void QCBOREncode_Init(QCBOREncodeContext *me, void *pBuf, size_t uBufLen)
+{
+   memset(me, 0, sizeof(QCBOREncodeContext));
+   if(uBufLen > UINT32_MAX) {
+      me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
+   } else {
+      UsefulOutBuf_Init(&(me->OutBuf), pBuf, uBufLen);
+      Nesting_Init(&(me->nesting));
+   }
+}
+
+
+
+
+/* 
+ All CBOR data items have a type and a number. The number 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 serveral uses for major type 7.
+ 
+ This function encodes the type and the number. There are several
+ encodings for the number depending on how large it is and how it is
+ used.
+ 
+ Every encoding of the type and number 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 number. If the number 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 number 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 number in many ways with this
+ representation.  This implementation always uses the smallest
+ possible representation. This is also the suggestion made in the RFC
+ for cannonical CBOR.
+ 
+ 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 float or double are 0 it is still correctly
+ encoded in 4 or 8 bytes.
+ 
+ */
+static void InsertEncodedTypeAndNumber(QCBOREncodeContext *me, uint8_t uMajorType, size_t uMinLen, uint64_t uNumber, size_t uPos)
+{
+   // No need to worry about integer overflow here because a) uMajorType is
+   // always generated internally, not by the caller, b) this is for CBOR
+   // _generation_, not parsing c) a mistake will result in bad CBOR generation,
+   // not a security vulnerability.
+   uMajorType <<= 5;
+   
+   if(uNumber > 0xffffffff || uMinLen >= 8) {
+      UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_EIGHT_BYTES, uPos);
+      UsefulOutBuf_InsertUint64(&(me->OutBuf), (uint64_t)uNumber, uPos+1);
+      
+   } else if(uNumber > 0xffff || uMinLen >= 4) {
+      UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_FOUR_BYTES, uPos);
+      UsefulOutBuf_InsertUint32(&(me->OutBuf), (uint32_t)uNumber, uPos+1);
+      
+   } else if (uNumber > 0xff) {
+      // Between 0 and 65535
+      UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_TWO_BYTES, uPos);
+      UsefulOutBuf_InsertUint16(&(me->OutBuf), (uint16_t)uNumber, uPos+1);
+      
+   } else if(uNumber >= 24) {
+      // Between 0 and 255, but only between 24 and 255 is ever encoded here
+      UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + LEN_IS_ONE_BYTE, uPos);
+      UsefulOutBuf_InsertByte(&(me->OutBuf), (uint8_t)uNumber, uPos+1);
+
+   } else {
+      // Between 0 and 23
+      UsefulOutBuf_InsertByte(&(me->OutBuf), uMajorType + (uint8_t)uNumber, 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)));
+}
+
+
+static void AddBytesInternal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes, uint8_t uMajorType, uint16_t uItems);
+
+
+/*
+ Add an optional label and optional tag. It will go in front of a real data item.
+ */
+static void AddLabelAndOptionalTag(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag)
+{
+   if(szLabel) {
+      UsefulBufC SZText = {szLabel, strlen(szLabel)};
+      AddBytesInternal(me, NULL, nLabel, CBOR_TAG_NONE, SZText, CBOR_MAJOR_TYPE_TEXT_STRING, 0);
+   } else if (QCBOR_NO_INT_LABEL != nLabel) {
+      // Add an integer label. This is just adding an integer at this point
+      // This will result in a call right back to here, but the call won't do anything
+      // because of the params NULL, QCBOR_NO_INT_LABEL and CBOR_TAG_NONE
+      QCBOREncode_AddInt64_3(me, NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, nLabel);
+   }
+   if(uTag != CBOR_TAG_NONE) {
+      AppendEncodedTypeAndNumber(me, CBOR_MAJOR_TYPE_OPTIONAL, uTag);
+   }
+}
+
+
+/*
+ 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 or
+ pre-formatted CBOR.
+ */
+static void AddBytesInternal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes, uint8_t uMajorType, uint16_t uItems)
+{
+   if(Bytes.len >= UINT32_MAX) {
+      // This implementation doesn't allow buffers larger than UINT32_MAX. This is
+      // primarily because QCBORTrackNesting.pArrays[].uStart is an uint32 rather
+      // than size_t to keep the stack usage down. Also it is entirely impractical
+      // to create tokens bigger than 4GB in contiguous RAM
+      me->uError = QCBOR_ERR_BUFFER_TOO_LARGE;
+      
+   } else {
+      
+      AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+      
+      if(!me->uError) {
+
+         // 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), uMajorType == CBOR_MAJOR_NONE_TYPE_RAW ? uItems : 1);
+      }
+   }
+}
+
+
+
+
+/*
+ Public functions for adding strings and raw encoded CBOR. See header qcbor.h
+ */
+void QCBOREncode_AddBytes_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes)
+{
+   AddBytesInternal(me, szLabel, nLabel, uTag, Bytes, CBOR_MAJOR_TYPE_BYTE_STRING, 0);
+}
+
+void QCBOREncode_AddText_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, UsefulBufC Bytes)
+{
+   AddBytesInternal(me, szLabel, nLabel, uTag, Bytes, CBOR_MAJOR_TYPE_TEXT_STRING, 0);
+}
+
+void QCBOREncode_AddRaw(QCBOREncodeContext *me, EncodedCBORC Raw)
+{
+   AddBytesInternal(me, NULL, QCBOR_NO_INT_LABEL, CBOR_TAG_NONE, Raw.Bytes, CBOR_MAJOR_NONE_TYPE_RAW, Raw.uItems);
+}
+
+
+
+
+/*
+ Internal function common to opening an array or a map
+ 
+ QCBOR_MAX_ARRAY_NESTING is the number of times Open can be called
+ successfully.  Call it one more time gives an error.
+ 
+ */
+static void OpenMapOrArrayInternal(QCBOREncodeContext *me, uint8_t uMajorType, const char *szLabel, uint64_t nLabel, uint64_t uTag, bool bBstrWrap)
+{
+   AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+   
+   if(!me->uError) {
+      // Add one item to the nesting level we are in for the new map or array
+      me->uError = Nesting_Increment(&(me->nesting), 1);
+      if(!me->uError) {
+         // Increase nesting level because this is a map or array
+         // Cast from size_t to uin32_t is safe because the UsefulOutBuf
+         // size is limited to UINT32_MAX in QCBOR_Init().
+         me->uError = Nesting_Increase(&(me->nesting),
+                                       uMajorType, (uint32_t)UsefulOutBuf_GetEndPosition(&(me->OutBuf)),
+                                       bBstrWrap);
+      }
+   }
+}
+
+
+/*
+ Public functions for opening / closing arrays and maps. See header qcbor.h
+ */
+void QCBOREncode_OpenArray_3(QCBOREncodeContext *me, const char *szLabel, uint64_t nLabel, uint64_t uTag, bool bBstrWrap)
+{
+   OpenMapOrArrayInternal(me, CBOR_MAJOR_TYPE_ARRAY, szLabel, nLabel, uTag, bBstrWrap);
+}
+
+void QCBOREncode_OpenMap_3(QCBOREncodeContext *me, const char *szLabel, uint64_t nLabel, uint64_t uTag, uint8_t bBstrWrap)
+{
+   OpenMapOrArrayInternal(me, CBOR_MAJOR_TYPE_MAP, szLabel, nLabel, uTag, bBstrWrap);
+}
+
+void QCBOREncode_CloseArray(QCBOREncodeContext *me)
+{
+   if(!Nesting_IsInNest(&(me->nesting))) {
+      me->uError = QCBOR_ERR_TOO_MANY_CLOSES;
+      
+   } else {
+      // When the array was opened, nothing was done except note the position
+      // of the start of the array. This code goes back and inserts the type
+      // (array or map) and length. That means all the data in the array or map
+      // and any nested arrays or maps have to be slid right. This is done
+      // by UsefulOutBuf's insert function that is called from inside
+      // InsertEncodedTypeAndNumber()
+      
+      const uint32_t uInsertPosition = Nesting_GetStartPos(&(me->nesting));
+      
+      InsertEncodedTypeAndNumber(me,
+                                 Nesting_GetMajorType(&(me->nesting)),  // the major type (array or map)
+                                 0,                                     // no minimum length for encoding
+                                 Nesting_GetCount(&(me->nesting)),      // number of items in array or map
+                                 uInsertPosition);                      // position in output buffer
+      
+      if(Nesting_IsBstrWrapped(&(me->nesting))) {
+         // This map or array is to be wrapped in a byte string. This is typically because
+         // the data is to be hashed or cryprographically signed. This is what COSE
+         // signing does.
+         
+         // Cast from size_t to uin32_t is safe because the UsefulOutBuf
+         // size is limited to UINT32_MAX in QCBOR_Init().
+         uint32_t uLenOfEncodedMapOrArray = (uint32_t)UsefulOutBuf_GetEndPosition(&(me->OutBuf)) - uInsertPosition;
+ 
+         // Insert the bstring wrapping
+         InsertEncodedTypeAndNumber(me,
+                                    CBOR_MAJOR_TYPE_BYTE_STRING,  // major type bstring
+                                    0,                            // no minimum length for encoding
+                                    uLenOfEncodedMapOrArray,      // length of the map
+                                    uInsertPosition);             // position in out buffer
+      }
+      
+      Nesting_Decrease(&(me->nesting));
+   }
+}
+
+
+
+
+/*
+ Internal function for adding positive and negative integers of all different sizes
+ */
+static void AddUInt64Internal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uMajorType, uint64_t n)
+{
+   AddLabelAndOptionalTag(me, szLabel, nLabel, uTag);
+   if(!me->uError) {
+      AppendEncodedTypeAndNumber(me, uMajorType, n);
+      me->uError = Nesting_Increment(&(me->nesting), 1);
+   }
+}
+
+
+/*
+ Public functions for adding integers. See header qcbor.h
+ */
+void QCBOREncode_AddUInt64_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint64_t uNum)
+{
+   AddUInt64Internal(me, szLabel, nLabel, uTag, CBOR_MAJOR_TYPE_POSITIVE_INT, uNum);
+}
+
+void QCBOREncode_AddInt64_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, int64_t nNum)
+{
+   uint8_t      uMajorType;
+   uint64_t     uValue;
+   
+   // Handle CBOR's particular format for positive and negative integers
+   if(nNum < 0) {
+      uValue = (uint64_t)(-nNum - 1); // This is the way negative ints work in CBOR. -1 encodes as 0x00 with major type negative int.
+      uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
+   } else {
+      uValue = (uint64_t)nNum;
+      uMajorType = CBOR_MAJOR_TYPE_POSITIVE_INT;
+   }
+   AddUInt64Internal(me, szLabel, nLabel, uTag, uMajorType, uValue);
+}
+
+
+
+
+/*
+ Common code for adding floats and doubles and simple types like true and false
+ 
+ One way to look at simple values is that they are:
+  - type 7
+  - an additional integer from 0 to 255
+     - additional integer 0-19 are unassigned and could be used in an update to CBOR
+     - additional integers 20, 21, 22 and 23 are false, true, null and undef
+     - additional integer 24 is not available
+     - when the additional value is 25, 26, or 27 there is additionally a half, float or double in following bytes
+     - additional integers 28, 29 and 30 are unassigned / reserved
+     - additional integer 31 is a "break"
+     - additional integers 32-255 are unassigned and could be used in an update to CBOR
+ */
+static void AddSimpleInternal(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, size_t uSize, uint64_t uNum)
+{
+   AddLabelAndOptionalTag(me, szLabel, nLabel,  uTag);
+   if(!me->uError) {
+      // This function call takes care of endian swapping for the float / double
+      InsertEncodedTypeAndNumber(me,
+                                 CBOR_MAJOR_TYPE_SIMPLE,  // The major type for floats and doubles
+                                 uSize,                   // min size / tells encoder to do it right
+                                 uNum,                    // Bytes of the floating point number as a uint
+                                 UsefulOutBuf_GetEndPosition(&(me->OutBuf))); // end position for append
+      
+      me->uError = Nesting_Increment(&(me->nesting), 1);
+   }
+}
+
+
+/*
+ Public function for adding simple values. See header qcbor.h
+ */
+void QCBOREncode_AddRawSimple_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uSimple)
+{
+   AddSimpleInternal(me, szLabel, nLabel, uTag, 0, uSimple);
+}
+
+
+/*
+ Public function for adding simple values. See header qcbor.h
+ */
+void QCBOREncode_AddSimple_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, uint8_t uSimple)
+{
+   if(uSimple < CBOR_SIMPLEV_FALSE || uSimple > CBOR_SIMPLEV_UNDEF) {
+      me->uError = QCBOR_ERR_BAD_SIMPLE;
+   } else {
+      QCBOREncode_AddRawSimple_3(me, szLabel, nLabel, uTag, uSimple);
+   }
+}
+
+
+/*
+ Public functions for floating point numbers. See header qcbor.h
+ */
+void QCBOREncode_AddFloat_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, float fNum)
+{
+   // Convert the *type* of the data from a float to a uint so the
+   // standard integer encoding can work.  This takes advantage
+   // of CBOR's indicator for a float being the same as for a 4
+   // byte integer too.
+   const float *pfNum  = &fNum;
+   const uint32_t uNum = *(uint32_t *)pfNum;
+      
+   AddSimpleInternal(me, szLabel, nLabel, uTag, sizeof(float), uNum);
+}
+
+void QCBOREncode_AddDouble_3(QCBOREncodeContext *me, const char *szLabel, int64_t nLabel, uint64_t uTag, double dNum)
+{
+   // see how it is done for floats above
+   const double *pdNum = &dNum;
+   const uint64_t uNum = *(uint64_t *)pdNum;
+   
+   AddSimpleInternal(me, szLabel, nLabel, uTag, sizeof(double), uNum);
+}
+
+
+
+
+/*
+ Public functions to finish and get the encoded result. See header qcbor.h
+ */
+int QCBOREncode_Finish2(QCBOREncodeContext *me, EncodedCBOR *pEncodedCBOR)
+{
+   if(me->uError)
+      goto Done;
+   
+   if (Nesting_IsInNest(&(me->nesting))) {
+      me->uError = 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.
+      me->uError = QCBOR_ERR_BUFFER_TOO_SMALL;
+      goto Done;
+   }
+   
+   UsefulOutBuf_OutUBuf(&(me->OutBuf), &(pEncodedCBOR->Bytes));
+   pEncodedCBOR->uItems = Nesting_GetCount(&(me->nesting));
+   
+Done:
+   return me->uError;
+}
+
+int QCBOREncode_Finish(QCBOREncodeContext *me, size_t *puEncodedLen)
+{
+   EncodedCBOR Enc;
+   
+   int nReturn = QCBOREncode_Finish2(me, &Enc);
+   
+   if(nReturn == QCBOR_SUCCESS) {
+      *puEncodedLen = Enc.Bytes.len;
+   }
+   
+   return nReturn;
+}
+
+