blob: cc585f8f96bbd4a785b85c89adf118f5114f46db [file] [log] [blame]
Thiago Macieiraf1cadf02015-05-08 17:19:17 -07001/****************************************************************************
2**
Thiago Macieira46a818e2015-10-08 15:13:05 +02003** Copyright (C) 2016 Intel Corporation
Thiago Macieiraf1cadf02015-05-08 17:19:17 -07004**
5** Permission is hereby granted, free of charge, to any person obtaining a copy
6** of this software and associated documentation files (the "Software"), to deal
7** in the Software without restriction, including without limitation the rights
8** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9** copies of the Software, and to permit persons to whom the Software is
10** furnished to do so, subject to the following conditions:
11**
12** The above copyright notice and this permission notice shall be included in
13** all copies or substantial portions of the Software.
14**
15** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21** THE SOFTWARE.
22**
23****************************************************************************/
24
Thiago Macieiraed5b57c2015-07-07 16:38:27 -070025#define _BSD_SOURCE 1
Otavio Pontese2d5dd52016-07-08 09:49:38 -030026#define _DEFAULT_SOURCE 1
Thiago Macieira86c81862016-08-04 13:56:48 -070027#ifndef __STDC_LIMIT_MACROS
28# define __STDC_LIMIT_MACROS 1
29#endif
30
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070031#include "cbor.h"
Thiago Macieiracf3116e2017-03-04 23:36:23 -060032#include "cborinternal_p.h"
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070033#include "compilersupport_p.h"
34
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070035#include <stdlib.h>
36#include <string.h>
37
Thiago Macieira46a818e2015-10-08 15:13:05 +020038/**
39 * \defgroup CborEncoding Encoding to CBOR
40 * \brief Group of functions used to encode data to CBOR.
41 *
42 * CborEncoder is used to encode data into a CBOR stream. The outermost
43 * CborEncoder is initialized by calling cbor_encoder_init(), with the buffer
44 * where the CBOR stream will be stored. The outermost CborEncoder is usually
45 * used to encode exactly one item, most often an array or map. It is possible
46 * to encode more than one item, but care must then be taken on the decoder
47 * side to ensure the state is reset after each item was decoded.
48 *
49 * Nested CborEncoder objects are created using cbor_encoder_create_array() and
50 * cbor_encoder_create_map(), later closed with cbor_encoder_close_container()
51 * or cbor_encoder_close_container_checked(). The pairs of creation and closing
52 * must be exactly matched and their parameters are always the same.
53 *
54 * CborEncoder writes directly to the user-supplied buffer, without extra
55 * buffering. CborEncoder does not allocate memory and CborEncoder objects are
56 * usually created on the stack of the encoding functions.
57 *
58 * The example below initializes a CborEncoder object with a buffer and encodes
59 * a single integer.
60 *
61 * \code
62 * uint8_t buf[16];
63 * CborEncoder encoder;
64 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
65 * cbor_encode_int(&encoder, some_value);
66 * \endcode
67 *
68 * As explained before, usually the outermost CborEncoder object is used to add
69 * one array or map, which in turn contains multiple elements. The example
70 * below creates a CBOR map with one element: a key "foo" and a boolean value.
71 *
72 * \code
73 * uint8_t buf[16];
74 * CborEncoder encoder, mapEncoder;
75 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
76 * cbor_encoder_create_map(&encoder, &mapEncoder, 1);
77 * cbor_encode_text_stringz(&mapEncoder, "foo");
78 * cbor_encode_boolean(&mapEncoder, some_value);
79 * cbor_encoder_close_container(&encoder, &mapEncoder);
80 * \endcode
81 *
82 * <h3 class="groupheader">Error checking and buffer size</h2>
83 *
84 * All functions operating on CborEncoder return a condition of type CborError.
85 * If the encoding was successful, they return CborNoError. Some functions do
86 * extra checking on the input provided and may return some other error
87 * conditions (for example, cbor_encode_simple_value() checks that the type is
88 * of the correct type).
89 *
90 * In addition, all functions check whether the buffer has enough bytes to
91 * encode the item being appended. If that is not possible, they return
92 * CborErrorOutOfMemory.
93 *
94 * It is possible to continue with the encoding of data past the first function
95 * that returns CborErrorOutOfMemory. CborEncoder functions will not overrun
96 * the buffer, but will instead count how many more bytes are needed to
Thiago Macieira7ae36a72015-10-28 16:19:23 -070097 * complete the encoding. At the end, you can obtain that count by calling
98 * cbor_encoder_get_extra_bytes_needed().
Thiago Macieira46a818e2015-10-08 15:13:05 +020099 *
100 * \section1 Finalizing the encoding
101 *
102 * Once all items have been appended and the containers have all been properly
103 * closed, the user-supplied buffer will contain the CBOR stream and may be
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700104 * immediately used. To obtain the size of the buffer, call
105 * cbor_encoder_get_buffer_size() with the original buffer pointer.
Thiago Macieira46a818e2015-10-08 15:13:05 +0200106 *
107 * The example below illustrates how one can encode an item with error checking
108 * and then pass on the buffer for network sending.
109 *
110 * \code
111 * uint8_t buf[16];
112 * CborError err;
113 * CborEncoder encoder, mapEncoder;
114 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
115 * err = cbor_encoder_create_map(&encoder, &mapEncoder, 1);
116 * if (!err)
117 * return err;
118 * err = cbor_encode_text_stringz(&mapEncoder, "foo");
119 * if (!err)
120 * return err;
121 * err = cbor_encode_boolean(&mapEncoder, some_value);
122 * if (!err)
123 * return err;
124 * err = cbor_encoder_close_container_checked(&encoder, &mapEncoder);
125 * if (!err)
126 * return err;
127 *
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700128 * size_t len = cbor_encoder_get_buffer_size(&encoder, buf);
Thiago Macieira46a818e2015-10-08 15:13:05 +0200129 * send_payload(buf, len);
130 * return CborNoError;
131 * \endcode
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700132 *
133 * Finally, the example below illustrates expands on the one above and also
134 * deals with dynamically growing the buffer if the initial allocation wasn't
135 * big enough. Note the two places where the error checking was replaced with
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100136 * an cbor_assertion, showing where the author assumes no error can occur.
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700137 *
138 * \code
139 * uint8_t *encode_string_array(const char **strings, int n, size_t *bufsize)
140 * {
141 * CborError err;
142 * CborEncoder encoder, arrayEncoder;
143 * size_t size = 256;
144 * uint8_t *buf = NULL;
145 *
146 * while (1) {
147 * int i;
148 * size_t more_bytes;
149 * uint8_t *nbuf = realloc(buf, size);
150 * if (nbuf == NULL)
151 * goto error;
152 * buf = nbuf;
153 *
154 * cbor_encoder_init(&encoder, &buf, size, 0);
155 * err = cbor_encoder_create_array(&encoder, &arrayEncoder, n);
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100156 * cbor_assert(err); // can't fail, the buffer is always big enough
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700157 *
158 * for (i = 0; i < n; ++i) {
159 * err = cbor_encode_text_stringz(&arrayEncoder, strings[i]);
160 * if (err && err != CborErrorOutOfMemory)
161 * goto error;
162 * }
163 *
164 * err = cbor_encoder_close_container_checked(&encoder, &arrayEncoder);
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100165 * cbor_assert(err); // shouldn't fail!
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700166 *
167 * more_bytes = cbor_encoder_get_extra_bytes_needed(encoder);
168 * if (more_size) {
169 * // buffer wasn't big enough, try again
170 * size += more_bytes;
171 * continue;
172 * }
173 *
174 * *bufsize = cbor_encoder_get_buffer_size(encoder, buf);
175 * return buf;
176 * }
177 * error:
178 * free(buf);
179 * return NULL;
180 * }
181 * \endcode
Thiago Macieira46a818e2015-10-08 15:13:05 +0200182 */
183
184/**
185 * \addtogroup CborEncoding
186 * @{
187 */
188
189/**
190 * \struct CborEncoder
191 * Structure used to encode to CBOR.
192 */
193
194/**
195 * Initializes a CborEncoder structure \a encoder by pointing it to buffer \a
196 * buffer of size \a size. The \a flags field is currently unused and must be
197 * zero.
198 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700199void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700200{
Thiago Macieiraede7f142016-07-30 23:08:39 -0700201 encoder->data.ptr = buffer;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700202 encoder->end = buffer + size;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700203 encoder->added = 0;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700204 encoder->flags = flags;
205}
206
Thiago Macieira5752ce52015-06-16 12:10:03 -0700207static inline void put16(void *where, uint16_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700208{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700209 v = cbor_htons(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700210 memcpy(where, &v, sizeof(v));
211}
212
Thiago Macieiradbc01292016-06-06 17:02:25 -0700213/* Note: Since this is currently only used in situations where OOM is the only
214 * valid error, we KNOW this to be true. Thus, this function now returns just 'true',
215 * but if in the future, any function starts returning a non-OOM error, this will need
216 * to be changed to the test. At the moment, this is done to prevent more branches
217 * being created in the tinycbor output */
Erich Keane47a78562015-08-10 15:19:50 -0700218static inline bool isOomError(CborError err)
219{
220 (void) err;
221 return true;
222}
223
Thiago Macieira5752ce52015-06-16 12:10:03 -0700224static inline void put32(void *where, uint32_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700225{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700226 v = cbor_htonl(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700227 memcpy(where, &v, sizeof(v));
228}
229
Thiago Macieira5752ce52015-06-16 12:10:03 -0700230static inline void put64(void *where, uint64_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700231{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700232 v = cbor_htonll(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700233 memcpy(where, &v, sizeof(v));
234}
235
Thiago Macieira397f9792015-09-18 19:36:26 -0700236static inline bool would_overflow(CborEncoder *encoder, size_t len)
237{
238 ptrdiff_t remaining = (ptrdiff_t)encoder->end;
Thiago Macieiraede7f142016-07-30 23:08:39 -0700239 remaining -= remaining ? (ptrdiff_t)encoder->data.ptr : encoder->data.bytes_needed;
Thiago Macieira397f9792015-09-18 19:36:26 -0700240 remaining -= (ptrdiff_t)len;
241 return unlikely(remaining < 0);
242}
243
244static inline void advance_ptr(CborEncoder *encoder, size_t n)
245{
246 if (encoder->end)
Thiago Macieiraede7f142016-07-30 23:08:39 -0700247 encoder->data.ptr += n;
Thiago Macieira397f9792015-09-18 19:36:26 -0700248 else
Thiago Macieiraede7f142016-07-30 23:08:39 -0700249 encoder->data.bytes_needed += n;
Thiago Macieira397f9792015-09-18 19:36:26 -0700250}
251
Thiago Macieira5752ce52015-06-16 12:10:03 -0700252static inline CborError append_to_buffer(CborEncoder *encoder, const void *data, size_t len)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700253{
Thiago Macieira397f9792015-09-18 19:36:26 -0700254 if (would_overflow(encoder, len)) {
Erich Keane47a78562015-08-10 15:19:50 -0700255 if (encoder->end != NULL) {
Thiago Macieiraede7f142016-07-30 23:08:39 -0700256 len -= encoder->end - encoder->data.ptr;
Thiago Macieira397f9792015-09-18 19:36:26 -0700257 encoder->end = NULL;
Thiago Macieiraede7f142016-07-30 23:08:39 -0700258 encoder->data.bytes_needed = 0;
Erich Keane47a78562015-08-10 15:19:50 -0700259 }
260
Thiago Macieira397f9792015-09-18 19:36:26 -0700261 advance_ptr(encoder, len);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700262 return CborErrorOutOfMemory;
Erich Keane47a78562015-08-10 15:19:50 -0700263 }
264
Thiago Macieiraede7f142016-07-30 23:08:39 -0700265 memcpy(encoder->data.ptr, data, len);
266 encoder->data.ptr += len;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700267 return CborNoError;
268}
269
Thiago Macieira5752ce52015-06-16 12:10:03 -0700270static inline CborError append_byte_to_buffer(CborEncoder *encoder, uint8_t byte)
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900271{
Thiago Macieira618d2f12015-09-22 09:14:29 -0700272 return append_to_buffer(encoder, &byte, 1);
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900273}
274
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700275static inline CborError encode_number_no_update(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700276{
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700277 /* Little-endian would have been so much more convenient here:
278 * We could just write at the beginning of buf but append_to_buffer
279 * only the necessary bytes.
280 * Since it has to be big endian, do it the other way around:
281 * write from the end. */
Thiago Macieira510e5b82015-09-21 16:05:02 -0700282 uint64_t buf[2];
283 uint8_t *const bufend = (uint8_t *)buf + sizeof(buf);
Thiago Macieira5752ce52015-06-16 12:10:03 -0700284 uint8_t *bufstart = bufend - 1;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700285 put64(buf + 1, ui); /* we probably have a bunch of zeros in the beginning */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700286
287 if (ui < Value8Bit) {
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700288 *bufstart += shiftedMajorType;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700289 } else {
alradmsft9ba47912016-10-11 17:56:15 -0700290 uint8_t more = 0;
Thiago Macieira13c85792015-07-07 16:15:41 -0700291 if (ui > 0xffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700292 ++more;
Thiago Macieira13c85792015-07-07 16:15:41 -0700293 if (ui > 0xffffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700294 ++more;
Thiago Macieira13c85792015-07-07 16:15:41 -0700295 if (ui > 0xffffffffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700296 ++more;
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700297 bufstart -= (size_t)1 << more;
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700298 *bufstart = shiftedMajorType + Value8Bit + more;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700299 }
300
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700301 return append_to_buffer(encoder, bufstart, bufend - bufstart);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700302}
303
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700304static inline CborError encode_number(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
305{
306 ++encoder->added;
307 return encode_number_no_update(encoder, ui, shiftedMajorType);
308}
309
Thiago Macieira46a818e2015-10-08 15:13:05 +0200310/**
311 * Appends the unsigned 64-bit integer \a value to the CBOR stream provided by
312 * \a encoder.
313 *
314 * \sa cbor_encode_negative_int, cbor_encode_int
315 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700316CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value)
317{
318 return encode_number(encoder, value, UnsignedIntegerType << MajorTypeShift);
319}
320
Thiago Macieira46a818e2015-10-08 15:13:05 +0200321/**
322 * Appends the negative 64-bit integer whose absolute value is \a
323 * absolute_value to the CBOR stream provided by \a encoder.
324 *
325 * \sa cbor_encode_uint, cbor_encode_int
326 */
Thiago Macieira78632b32015-09-26 14:18:48 -0700327CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value)
328{
329 return encode_number(encoder, absolute_value, NegativeIntegerType << MajorTypeShift);
330}
331
Thiago Macieira46a818e2015-10-08 15:13:05 +0200332/**
333 * Appends the signed 64-bit integer \a value to the CBOR stream provided by
334 * \a encoder.
335 *
336 * \sa cbor_encode_negative_int, cbor_encode_uint
337 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700338CborError cbor_encode_int(CborEncoder *encoder, int64_t value)
339{
Thiago Macieiradbc01292016-06-06 17:02:25 -0700340 /* adapted from code in RFC 7049 appendix C (pseudocode) */
341 uint64_t ui = value >> 63; /* extend sign to whole length */
342 uint8_t majorType = ui & 0x20; /* extract major type */
343 ui ^= value; /* complement negatives */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700344 return encode_number(encoder, ui, majorType);
345}
346
Thiago Macieira46a818e2015-10-08 15:13:05 +0200347/**
348 * Appends the CBOR Simple Type of value \a value to the CBOR stream provided by
349 * \a encoder.
350 *
351 * This function may return error CborErrorIllegalSimpleType if the \a value
352 * variable contains a number that is not a valid simple type.
353 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700354CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value)
355{
356#ifndef CBOR_ENCODER_NO_CHECK_USER
Thiago Macieiradbc01292016-06-06 17:02:25 -0700357 /* check if this is a valid simple type */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700358 if (value >= HalfPrecisionFloat && value <= Break)
359 return CborErrorIllegalSimpleType;
360#endif
361 return encode_number(encoder, value, SimpleTypesType << MajorTypeShift);
362}
363
Thiago Macieira46a818e2015-10-08 15:13:05 +0200364/**
365 * Appends the floating-point value of type \a fpType and pointed to by \a
366 * value to the CBOR stream provided by \a encoder. The value of \a fpType must
367 * be one of CborHalfFloatType, CborFloatType or CborDoubleType, otherwise the
368 * behavior of this function is undefined.
369 *
370 * This function is useful for code that needs to pass through floating point
371 * values but does not wish to have the actual floating-point code.
372 *
373 * \sa cbor_encode_half_float, cbor_encode_float, cbor_encode_double
374 */
Thiago Macieira81f33432015-07-02 16:16:28 -0700375CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700376{
Thiago Macieira81f33432015-07-02 16:16:28 -0700377 uint8_t buf[1 + sizeof(uint64_t)];
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100378 cbor_assert(fpType == CborHalfFloatType || fpType == CborFloatType || fpType == CborDoubleType);
Thiago Macieira81f33432015-07-02 16:16:28 -0700379 buf[0] = fpType;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700380
Thiago Macieira81f33432015-07-02 16:16:28 -0700381 unsigned size = 2U << (fpType - CborHalfFloatType);
382 if (size == 8)
383 put64(buf + 1, *(const uint64_t*)value);
384 else if (size == 4)
385 put32(buf + 1, *(const uint32_t*)value);
386 else
387 put16(buf + 1, *(const uint16_t*)value);
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700388 ++encoder->added;
Thiago Macieira81f33432015-07-02 16:16:28 -0700389 return append_to_buffer(encoder, buf, size + 1);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700390}
Thiago Macieira8f98a112015-05-08 17:25:29 -0700391
Thiago Macieira46a818e2015-10-08 15:13:05 +0200392/**
393 * Appends the CBOR tag \a tag to the CBOR stream provided by \a encoder.
394 *
395 * \sa CborTag
396 */
Thiago Macieira8f98a112015-05-08 17:25:29 -0700397CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag)
398{
Thiago Macieiradbc01292016-06-06 17:02:25 -0700399 /* tags don't count towards the number of elements in an array or map */
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700400 return encode_number_no_update(encoder, tag, TagType << MajorTypeShift);
Thiago Macieira8f98a112015-05-08 17:25:29 -0700401}
Thiago Macieirab54debe2015-05-08 17:42:39 -0700402
Thiago Macieira5752ce52015-06-16 12:10:03 -0700403static CborError encode_string(CborEncoder *encoder, size_t length, uint8_t shiftedMajorType, const void *string)
Thiago Macieirab54debe2015-05-08 17:42:39 -0700404{
405 CborError err = encode_number(encoder, length, shiftedMajorType);
Erich Keane47a78562015-08-10 15:19:50 -0700406 if (err && !isOomError(err))
Thiago Macieirab54debe2015-05-08 17:42:39 -0700407 return err;
408 return append_to_buffer(encoder, string, length);
409}
410
Thiago Macieira46a818e2015-10-08 15:13:05 +0200411/**
412 * \fn CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
413 *
414 * Appends the null-terminated text string \a string to the CBOR stream
415 * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
416 * TinyCBOR makes no verification of correctness. The terminating null is not
417 * included in the stream.
418 *
419 * \sa cbor_encode_text_string, cbor_encode_byte_string
420 */
421
422/**
423 * Appends the text string \a string of length \a length to the CBOR stream
424 * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
425 * TinyCBOR makes no verification of correctness.
426 *
427 * \sa CborError cbor_encode_text_stringz, cbor_encode_byte_string
428 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700429CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length)
Thiago Macieirab54debe2015-05-08 17:42:39 -0700430{
431 return encode_string(encoder, length, ByteStringType << MajorTypeShift, string);
432}
433
Thiago Macieira46a818e2015-10-08 15:13:05 +0200434/**
435 * Appends the byte string \a string of length \a length to the CBOR stream
436 * provided by \a encoder. CBOR byte strings are arbitrary raw data.
437 *
438 * \sa cbor_encode_text_stringz, cbor_encode_text_string
439 */
Thiago Macieirab54debe2015-05-08 17:42:39 -0700440CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length)
441{
442 return encode_string(encoder, length, TextStringType << MajorTypeShift, string);
443}
Thiago Macieira355817e2015-05-08 18:38:18 -0700444
Thiago Macieira56635242015-09-20 17:44:51 -0700445#ifdef __GNUC__
446__attribute__((noinline))
447#endif
448static CborError create_container(CborEncoder *encoder, CborEncoder *container, size_t length, uint8_t shiftedMajorType)
Thiago Macieira355817e2015-05-08 18:38:18 -0700449{
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900450 CborError err;
Thiago Macieiraede7f142016-07-30 23:08:39 -0700451 container->data.ptr = encoder->data.ptr;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700452 container->end = encoder->end;
453 ++encoder->added;
454 container->added = 0;
455
456 cbor_static_assert(((MapType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == CborIteratorFlag_ContainerIsMap);
457 cbor_static_assert(((ArrayType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == 0);
458 container->flags = shiftedMajorType & CborIteratorFlag_ContainerIsMap;
459
460 if (length == CborIndefiniteLength) {
461 container->flags |= CborIteratorFlag_UnknownLength;
462 err = append_byte_to_buffer(container, shiftedMajorType + IndefiniteLength);
463 } else {
464 err = encode_number_no_update(container, length, shiftedMajorType);
465 }
Thiago Macieira863a4802016-10-26 20:48:54 -0700466 return err;
Thiago Macieira355817e2015-05-08 18:38:18 -0700467}
468
Thiago Macieira46a818e2015-10-08 15:13:05 +0200469/**
470 * Creates a CBOR array in the CBOR stream provided by \a encoder and
471 * initializes \a arrayEncoder so that items can be added to the array using
472 * the CborEncoder functions. The array must be terminated by calling either
473 * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
474 * with the same \a encoder and \a arrayEncoder parameters.
475 *
476 * The number of items inserted into the array must be exactly \a length items,
477 * otherwise the stream is invalid. If the number of items is not known when
478 * creating the array, the constant \ref CborIndefiniteLength may be passed as
479 * length instead.
480 *
481 * \sa cbor_encoder_create_map
482 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700483CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length)
484{
Thiago Macieira56635242015-09-20 17:44:51 -0700485 return create_container(encoder, arrayEncoder, length, ArrayType << MajorTypeShift);
Thiago Macieira355817e2015-05-08 18:38:18 -0700486}
487
Thiago Macieira46a818e2015-10-08 15:13:05 +0200488/**
489 * Creates a CBOR map in the CBOR stream provided by \a encoder and
490 * initializes \a mapEncoder so that items can be added to the map using
491 * the CborEncoder functions. The map must be terminated by calling either
492 * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
493 * with the same \a encoder and \a mapEncoder parameters.
494 *
495 * The number of pair of items inserted into the map must be exactly \a length
496 * items, otherwise the stream is invalid. If the number of items is not known
497 * when creating the map, the constant \ref CborIndefiniteLength may be passed as
498 * length instead.
499 *
500 * \b{Implementation limitation:} TinyCBOR cannot encode more than SIZE_MAX/2
501 * key-value pairs in the stream. If the length \a length is larger than this
502 * value, this function returns error CborErrorDataTooLarge.
503 *
504 * \sa cbor_encoder_create_array
505 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700506CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length)
507{
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700508 if (length != CborIndefiniteLength && length > SIZE_MAX / 2)
509 return CborErrorDataTooLarge;
Thiago Macieira56635242015-09-20 17:44:51 -0700510 return create_container(encoder, mapEncoder, length, MapType << MajorTypeShift);
Thiago Macieira355817e2015-05-08 18:38:18 -0700511}
512
Thiago Macieira46a818e2015-10-08 15:13:05 +0200513/**
514 * Closes the CBOR container (array or map) provided by \a containerEncoder and
515 * updates the CBOR stream provided by \a encoder. Both parameters must be the
516 * same as were passed to cbor_encoder_create_array() or
517 * cbor_encoder_create_map().
518 *
519 * This function does not verify that the number of items (or pair of items, in
520 * the case of a map) was correct. To execute that verification, call
521 * cbor_encoder_close_container_checked() instead.
522 *
523 * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
524 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700525CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
526{
Thiago Macieira397f9792015-09-18 19:36:26 -0700527 if (encoder->end)
Thiago Macieiraede7f142016-07-30 23:08:39 -0700528 encoder->data.ptr = containerEncoder->data.ptr;
Thiago Macieira397f9792015-09-18 19:36:26 -0700529 else
Thiago Macieiraede7f142016-07-30 23:08:39 -0700530 encoder->data.bytes_needed = containerEncoder->data.bytes_needed;
Erich Keane47a78562015-08-10 15:19:50 -0700531 encoder->end = containerEncoder->end;
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900532 if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
533 return append_byte_to_buffer(encoder, BreakByte);
Thiago Macieira355817e2015-05-08 18:38:18 -0700534 return CborNoError;
535}
Thiago Macieira46a818e2015-10-08 15:13:05 +0200536
537/**
538 * \fn CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
539 *
540 * Appends the boolean value \a value to the CBOR stream provided by \a encoder.
541 */
542
543/**
544 * \fn CborError cbor_encode_null(CborEncoder *encoder)
545 *
546 * Appends the CBOR type representing a null value to the CBOR stream provided
547 * by \a encoder.
548 *
549 * \sa cbor_encode_undefined()
550 */
551
552/**
553 * \fn CborError cbor_encode_undefined(CborEncoder *encoder)
554 *
555 * Appends the CBOR type representing an undefined value to the CBOR stream
556 * provided by \a encoder.
557 *
558 * \sa cbor_encode_null()
559 */
560
561/**
562 * \fn CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
563 *
564 * Appends the IEEE 754 half-precision (16-bit) floating point value pointed to
565 * by \a value to the CBOR stream provided by \a encoder.
566 *
567 * \sa cbor_encode_floating_point(), cbor_encode_float(), cbor_encode_double()
568 */
569
570/**
571 * \fn CborError cbor_encode_float(CborEncoder *encoder, float value)
572 *
573 * Appends the IEEE 754 single-precision (32-bit) floating point value \a value
574 * to the CBOR stream provided by \a encoder.
575 *
576 * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_double()
577 */
578
579/**
580 * \fn CborError cbor_encode_double(CborEncoder *encoder, double value)
581 *
582 * Appends the IEEE 754 double-precision (64-bit) floating point value \a value
583 * to the CBOR stream provided by \a encoder.
584 *
585 * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_float()
586 */
587
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700588/**
589 * \fn size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
590 *
591 * Returns the total size of the buffer starting at \a buffer after the
592 * encoding finished without errors. The \a encoder and \a buffer arguments
593 * must be the same as supplied to cbor_encoder_init().
594 *
595 * If the encoding process had errors, the return value of this function is
596 * meaningless. If the only errors were CborErrorOutOfMemory, instead use
597 * cbor_encoder_get_extra_bytes_needed() to find out by how much to grow the
598 * buffer before encoding again.
599 *
600 * See \ref CborEncoding for an example of using this function.
601 *
602 * \sa cbor_encoder_init(), cbor_encoder_get_extra_bytes_needed(), CborEncoding
603 */
604
605/**
606 * \fn size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
607 *
608 * Returns how many more bytes the original buffer supplied to
609 * cbor_encoder_init() needs to be extended by so that no CborErrorOutOfMemory
610 * condition will happen for the encoding. If the buffer was big enough, this
611 * function returns 0. The \a encoder must be the original argument as passed
612 * to cbor_encoder_init().
613 *
614 * This function is usually called after an encoding sequence ended with one or
615 * more CborErrorOutOfMemory errors, but no other error. If any other error
616 * happened, the return value of this function is meaningless.
617 *
618 * See \ref CborEncoding for an example of using this function.
619 *
620 * \sa cbor_encoder_init(), cbor_encoder_get_buffer_size(), CborEncoding
621 */
622
Thiago Macieira46a818e2015-10-08 15:13:05 +0200623/** @} */