blob: ef1bc0b7a678efe09713b22eb63cec1e569a0986 [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 Macieiraf1cadf02015-05-08 17:19:17 -070027#include "cbor.h"
28#include "cborconstants_p.h"
29#include "compilersupport_p.h"
30
31#include <assert.h>
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070032#include <stdlib.h>
33#include <string.h>
34
Thiago Macieira8f3fb782015-06-16 16:27:01 -070035#include "assert_p.h" /* Always include last */
36
Thiago Macieira46a818e2015-10-08 15:13:05 +020037/**
38 * \defgroup CborEncoding Encoding to CBOR
39 * \brief Group of functions used to encode data to CBOR.
40 *
41 * CborEncoder is used to encode data into a CBOR stream. The outermost
42 * CborEncoder is initialized by calling cbor_encoder_init(), with the buffer
43 * where the CBOR stream will be stored. The outermost CborEncoder is usually
44 * used to encode exactly one item, most often an array or map. It is possible
45 * to encode more than one item, but care must then be taken on the decoder
46 * side to ensure the state is reset after each item was decoded.
47 *
48 * Nested CborEncoder objects are created using cbor_encoder_create_array() and
49 * cbor_encoder_create_map(), later closed with cbor_encoder_close_container()
50 * or cbor_encoder_close_container_checked(). The pairs of creation and closing
51 * must be exactly matched and their parameters are always the same.
52 *
53 * CborEncoder writes directly to the user-supplied buffer, without extra
54 * buffering. CborEncoder does not allocate memory and CborEncoder objects are
55 * usually created on the stack of the encoding functions.
56 *
57 * The example below initializes a CborEncoder object with a buffer and encodes
58 * a single integer.
59 *
60 * \code
61 * uint8_t buf[16];
62 * CborEncoder encoder;
63 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
64 * cbor_encode_int(&encoder, some_value);
65 * \endcode
66 *
67 * As explained before, usually the outermost CborEncoder object is used to add
68 * one array or map, which in turn contains multiple elements. The example
69 * below creates a CBOR map with one element: a key "foo" and a boolean value.
70 *
71 * \code
72 * uint8_t buf[16];
73 * CborEncoder encoder, mapEncoder;
74 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
75 * cbor_encoder_create_map(&encoder, &mapEncoder, 1);
76 * cbor_encode_text_stringz(&mapEncoder, "foo");
77 * cbor_encode_boolean(&mapEncoder, some_value);
78 * cbor_encoder_close_container(&encoder, &mapEncoder);
79 * \endcode
80 *
81 * <h3 class="groupheader">Error checking and buffer size</h2>
82 *
83 * All functions operating on CborEncoder return a condition of type CborError.
84 * If the encoding was successful, they return CborNoError. Some functions do
85 * extra checking on the input provided and may return some other error
86 * conditions (for example, cbor_encode_simple_value() checks that the type is
87 * of the correct type).
88 *
89 * In addition, all functions check whether the buffer has enough bytes to
90 * encode the item being appended. If that is not possible, they return
91 * CborErrorOutOfMemory.
92 *
93 * It is possible to continue with the encoding of data past the first function
94 * that returns CborErrorOutOfMemory. CborEncoder functions will not overrun
95 * the buffer, but will instead count how many more bytes are needed to
Thiago Macieira7ae36a72015-10-28 16:19:23 -070096 * complete the encoding. At the end, you can obtain that count by calling
97 * cbor_encoder_get_extra_bytes_needed().
Thiago Macieira46a818e2015-10-08 15:13:05 +020098 *
99 * \section1 Finalizing the encoding
100 *
101 * Once all items have been appended and the containers have all been properly
102 * closed, the user-supplied buffer will contain the CBOR stream and may be
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700103 * immediately used. To obtain the size of the buffer, call
104 * cbor_encoder_get_buffer_size() with the original buffer pointer.
Thiago Macieira46a818e2015-10-08 15:13:05 +0200105 *
106 * The example below illustrates how one can encode an item with error checking
107 * and then pass on the buffer for network sending.
108 *
109 * \code
110 * uint8_t buf[16];
111 * CborError err;
112 * CborEncoder encoder, mapEncoder;
113 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
114 * err = cbor_encoder_create_map(&encoder, &mapEncoder, 1);
115 * if (!err)
116 * return err;
117 * err = cbor_encode_text_stringz(&mapEncoder, "foo");
118 * if (!err)
119 * return err;
120 * err = cbor_encode_boolean(&mapEncoder, some_value);
121 * if (!err)
122 * return err;
123 * err = cbor_encoder_close_container_checked(&encoder, &mapEncoder);
124 * if (!err)
125 * return err;
126 *
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700127 * size_t len = cbor_encoder_get_buffer_size(&encoder, buf);
Thiago Macieira46a818e2015-10-08 15:13:05 +0200128 * send_payload(buf, len);
129 * return CborNoError;
130 * \endcode
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700131 *
132 * Finally, the example below illustrates expands on the one above and also
133 * deals with dynamically growing the buffer if the initial allocation wasn't
134 * big enough. Note the two places where the error checking was replaced with
135 * an assertion, showing where the author assumes no error can occur.
136 *
137 * \code
138 * uint8_t *encode_string_array(const char **strings, int n, size_t *bufsize)
139 * {
140 * CborError err;
141 * CborEncoder encoder, arrayEncoder;
142 * size_t size = 256;
143 * uint8_t *buf = NULL;
144 *
145 * while (1) {
146 * int i;
147 * size_t more_bytes;
148 * uint8_t *nbuf = realloc(buf, size);
149 * if (nbuf == NULL)
150 * goto error;
151 * buf = nbuf;
152 *
153 * cbor_encoder_init(&encoder, &buf, size, 0);
154 * err = cbor_encoder_create_array(&encoder, &arrayEncoder, n);
155 * assert(err); // can't fail, the buffer is always big enough
156 *
157 * for (i = 0; i < n; ++i) {
158 * err = cbor_encode_text_stringz(&arrayEncoder, strings[i]);
159 * if (err && err != CborErrorOutOfMemory)
160 * goto error;
161 * }
162 *
163 * err = cbor_encoder_close_container_checked(&encoder, &arrayEncoder);
164 * assert(err); // shouldn't fail!
165 *
166 * more_bytes = cbor_encoder_get_extra_bytes_needed(encoder);
167 * if (more_size) {
168 * // buffer wasn't big enough, try again
169 * size += more_bytes;
170 * continue;
171 * }
172 *
173 * *bufsize = cbor_encoder_get_buffer_size(encoder, buf);
174 * return buf;
175 * }
176 * error:
177 * free(buf);
178 * return NULL;
179 * }
180 * \endcode
Thiago Macieira46a818e2015-10-08 15:13:05 +0200181 */
182
183/**
184 * \addtogroup CborEncoding
185 * @{
186 */
187
188/**
189 * \struct CborEncoder
190 * Structure used to encode to CBOR.
191 */
192
193/**
194 * Initializes a CborEncoder structure \a encoder by pointing it to buffer \a
195 * buffer of size \a size. The \a flags field is currently unused and must be
196 * zero.
197 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700198void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700199{
Thiago Macieira4628a112016-07-30 23:04:46 -0700200 encoder->ptr = buffer;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700201 encoder->end = buffer + size;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700202 encoder->added = 0;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700203 encoder->flags = flags;
204}
205
Thiago Macieira5752ce52015-06-16 12:10:03 -0700206static inline void put16(void *where, uint16_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700207{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700208 v = cbor_htons(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700209 memcpy(where, &v, sizeof(v));
210}
211
Thiago Macieiradbc01292016-06-06 17:02:25 -0700212/* Note: Since this is currently only used in situations where OOM is the only
213 * valid error, we KNOW this to be true. Thus, this function now returns just 'true',
214 * but if in the future, any function starts returning a non-OOM error, this will need
215 * to be changed to the test. At the moment, this is done to prevent more branches
216 * being created in the tinycbor output */
Erich Keane47a78562015-08-10 15:19:50 -0700217static inline bool isOomError(CborError err)
218{
219 (void) err;
220 return true;
221}
222
Thiago Macieira5752ce52015-06-16 12:10:03 -0700223static inline void put32(void *where, uint32_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700224{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700225 v = cbor_htonl(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700226 memcpy(where, &v, sizeof(v));
227}
228
Thiago Macieira5752ce52015-06-16 12:10:03 -0700229static inline void put64(void *where, uint64_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700230{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700231 v = cbor_htonll(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700232 memcpy(where, &v, sizeof(v));
233}
234
Thiago Macieira397f9792015-09-18 19:36:26 -0700235static inline bool would_overflow(CborEncoder *encoder, size_t len)
236{
237 ptrdiff_t remaining = (ptrdiff_t)encoder->end;
Thiago Macieira4628a112016-07-30 23:04:46 -0700238 remaining -= remaining ? (ptrdiff_t)encoder->ptr : encoder->bytes_needed;
Thiago Macieira397f9792015-09-18 19:36:26 -0700239 remaining -= (ptrdiff_t)len;
240 return unlikely(remaining < 0);
241}
242
243static inline void advance_ptr(CborEncoder *encoder, size_t n)
244{
245 if (encoder->end)
Thiago Macieira4628a112016-07-30 23:04:46 -0700246 encoder->ptr += n;
Thiago Macieira397f9792015-09-18 19:36:26 -0700247 else
Thiago Macieira4628a112016-07-30 23:04:46 -0700248 encoder->bytes_needed += n;
Thiago Macieira397f9792015-09-18 19:36:26 -0700249}
250
Thiago Macieira5752ce52015-06-16 12:10:03 -0700251static inline CborError append_to_buffer(CborEncoder *encoder, const void *data, size_t len)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700252{
Thiago Macieira397f9792015-09-18 19:36:26 -0700253 if (would_overflow(encoder, len)) {
Erich Keane47a78562015-08-10 15:19:50 -0700254 if (encoder->end != NULL) {
Thiago Macieira4628a112016-07-30 23:04:46 -0700255 len -= encoder->end - encoder->ptr;
Thiago Macieira397f9792015-09-18 19:36:26 -0700256 encoder->end = NULL;
Thiago Macieira4628a112016-07-30 23:04:46 -0700257 encoder->bytes_needed = 0;
Erich Keane47a78562015-08-10 15:19:50 -0700258 }
259
Thiago Macieira397f9792015-09-18 19:36:26 -0700260 advance_ptr(encoder, len);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700261 return CborErrorOutOfMemory;
Erich Keane47a78562015-08-10 15:19:50 -0700262 }
263
Thiago Macieira4628a112016-07-30 23:04:46 -0700264 memcpy(encoder->ptr, data, len);
265 encoder->ptr += len;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700266 return CborNoError;
267}
268
Thiago Macieira5752ce52015-06-16 12:10:03 -0700269static inline CborError append_byte_to_buffer(CborEncoder *encoder, uint8_t byte)
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900270{
Thiago Macieira618d2f12015-09-22 09:14:29 -0700271 return append_to_buffer(encoder, &byte, 1);
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900272}
273
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700274static inline CborError encode_number_no_update(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700275{
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700276 /* Little-endian would have been so much more convenient here:
277 * We could just write at the beginning of buf but append_to_buffer
278 * only the necessary bytes.
279 * Since it has to be big endian, do it the other way around:
280 * write from the end. */
Thiago Macieira510e5b82015-09-21 16:05:02 -0700281 uint64_t buf[2];
282 uint8_t *const bufend = (uint8_t *)buf + sizeof(buf);
Thiago Macieira5752ce52015-06-16 12:10:03 -0700283 uint8_t *bufstart = bufend - 1;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700284 put64(buf + 1, ui); /* we probably have a bunch of zeros in the beginning */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700285
286 if (ui < Value8Bit) {
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700287 *bufstart += shiftedMajorType;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700288 } else {
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700289 unsigned more = 0;
Thiago Macieira13c85792015-07-07 16:15:41 -0700290 if (ui > 0xffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700291 ++more;
Thiago Macieira13c85792015-07-07 16:15:41 -0700292 if (ui > 0xffffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700293 ++more;
Thiago Macieira13c85792015-07-07 16:15:41 -0700294 if (ui > 0xffffffffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700295 ++more;
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700296 bufstart -= (size_t)1 << more;
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700297 *bufstart = shiftedMajorType + Value8Bit + more;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700298 }
299
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700300 return append_to_buffer(encoder, bufstart, bufend - bufstart);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700301}
302
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700303static inline CborError encode_number(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
304{
305 ++encoder->added;
306 return encode_number_no_update(encoder, ui, shiftedMajorType);
307}
308
Thiago Macieira46a818e2015-10-08 15:13:05 +0200309/**
310 * Appends the unsigned 64-bit integer \a value to the CBOR stream provided by
311 * \a encoder.
312 *
313 * \sa cbor_encode_negative_int, cbor_encode_int
314 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700315CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value)
316{
317 return encode_number(encoder, value, UnsignedIntegerType << MajorTypeShift);
318}
319
Thiago Macieira46a818e2015-10-08 15:13:05 +0200320/**
321 * Appends the negative 64-bit integer whose absolute value is \a
322 * absolute_value to the CBOR stream provided by \a encoder.
323 *
324 * \sa cbor_encode_uint, cbor_encode_int
325 */
Thiago Macieira78632b32015-09-26 14:18:48 -0700326CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value)
327{
328 return encode_number(encoder, absolute_value, NegativeIntegerType << MajorTypeShift);
329}
330
Thiago Macieira46a818e2015-10-08 15:13:05 +0200331/**
332 * Appends the signed 64-bit integer \a value to the CBOR stream provided by
333 * \a encoder.
334 *
335 * \sa cbor_encode_negative_int, cbor_encode_uint
336 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700337CborError cbor_encode_int(CborEncoder *encoder, int64_t value)
338{
Thiago Macieiradbc01292016-06-06 17:02:25 -0700339 /* adapted from code in RFC 7049 appendix C (pseudocode) */
340 uint64_t ui = value >> 63; /* extend sign to whole length */
341 uint8_t majorType = ui & 0x20; /* extract major type */
342 ui ^= value; /* complement negatives */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700343 return encode_number(encoder, ui, majorType);
344}
345
Thiago Macieira46a818e2015-10-08 15:13:05 +0200346/**
347 * Appends the CBOR Simple Type of value \a value to the CBOR stream provided by
348 * \a encoder.
349 *
350 * This function may return error CborErrorIllegalSimpleType if the \a value
351 * variable contains a number that is not a valid simple type.
352 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700353CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value)
354{
355#ifndef CBOR_ENCODER_NO_CHECK_USER
Thiago Macieiradbc01292016-06-06 17:02:25 -0700356 /* check if this is a valid simple type */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700357 if (value >= HalfPrecisionFloat && value <= Break)
358 return CborErrorIllegalSimpleType;
359#endif
360 return encode_number(encoder, value, SimpleTypesType << MajorTypeShift);
361}
362
Thiago Macieira46a818e2015-10-08 15:13:05 +0200363/**
364 * Appends the floating-point value of type \a fpType and pointed to by \a
365 * value to the CBOR stream provided by \a encoder. The value of \a fpType must
366 * be one of CborHalfFloatType, CborFloatType or CborDoubleType, otherwise the
367 * behavior of this function is undefined.
368 *
369 * This function is useful for code that needs to pass through floating point
370 * values but does not wish to have the actual floating-point code.
371 *
372 * \sa cbor_encode_half_float, cbor_encode_float, cbor_encode_double
373 */
Thiago Macieira81f33432015-07-02 16:16:28 -0700374CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700375{
Thiago Macieira81f33432015-07-02 16:16:28 -0700376 uint8_t buf[1 + sizeof(uint64_t)];
377 assert(fpType == CborHalfFloatType || fpType == CborFloatType || fpType == CborDoubleType);
378 buf[0] = fpType;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700379
Thiago Macieira81f33432015-07-02 16:16:28 -0700380 unsigned size = 2U << (fpType - CborHalfFloatType);
381 if (size == 8)
382 put64(buf + 1, *(const uint64_t*)value);
383 else if (size == 4)
384 put32(buf + 1, *(const uint32_t*)value);
385 else
386 put16(buf + 1, *(const uint16_t*)value);
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700387 ++encoder->added;
Thiago Macieira81f33432015-07-02 16:16:28 -0700388 return append_to_buffer(encoder, buf, size + 1);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700389}
Thiago Macieira8f98a112015-05-08 17:25:29 -0700390
Thiago Macieira46a818e2015-10-08 15:13:05 +0200391/**
392 * Appends the CBOR tag \a tag to the CBOR stream provided by \a encoder.
393 *
394 * \sa CborTag
395 */
Thiago Macieira8f98a112015-05-08 17:25:29 -0700396CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag)
397{
Thiago Macieiradbc01292016-06-06 17:02:25 -0700398 /* tags don't count towards the number of elements in an array or map */
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700399 return encode_number_no_update(encoder, tag, TagType << MajorTypeShift);
Thiago Macieira8f98a112015-05-08 17:25:29 -0700400}
Thiago Macieirab54debe2015-05-08 17:42:39 -0700401
Thiago Macieira5752ce52015-06-16 12:10:03 -0700402static CborError encode_string(CborEncoder *encoder, size_t length, uint8_t shiftedMajorType, const void *string)
Thiago Macieirab54debe2015-05-08 17:42:39 -0700403{
404 CborError err = encode_number(encoder, length, shiftedMajorType);
Erich Keane47a78562015-08-10 15:19:50 -0700405 if (err && !isOomError(err))
Thiago Macieirab54debe2015-05-08 17:42:39 -0700406 return err;
407 return append_to_buffer(encoder, string, length);
408}
409
Thiago Macieira46a818e2015-10-08 15:13:05 +0200410/**
411 * \fn CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
412 *
413 * Appends the null-terminated text string \a string to the CBOR stream
414 * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
415 * TinyCBOR makes no verification of correctness. The terminating null is not
416 * included in the stream.
417 *
418 * \sa cbor_encode_text_string, cbor_encode_byte_string
419 */
420
421/**
422 * Appends the text string \a string of length \a length to the CBOR stream
423 * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
424 * TinyCBOR makes no verification of correctness.
425 *
426 * \sa CborError cbor_encode_text_stringz, cbor_encode_byte_string
427 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700428CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length)
Thiago Macieirab54debe2015-05-08 17:42:39 -0700429{
430 return encode_string(encoder, length, ByteStringType << MajorTypeShift, string);
431}
432
Thiago Macieira46a818e2015-10-08 15:13:05 +0200433/**
434 * Appends the byte string \a string of length \a length to the CBOR stream
435 * provided by \a encoder. CBOR byte strings are arbitrary raw data.
436 *
437 * \sa cbor_encode_text_stringz, cbor_encode_text_string
438 */
Thiago Macieirab54debe2015-05-08 17:42:39 -0700439CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length)
440{
441 return encode_string(encoder, length, TextStringType << MajorTypeShift, string);
442}
Thiago Macieira355817e2015-05-08 18:38:18 -0700443
Thiago Macieira56635242015-09-20 17:44:51 -0700444#ifdef __GNUC__
445__attribute__((noinline))
446#endif
447static CborError create_container(CborEncoder *encoder, CborEncoder *container, size_t length, uint8_t shiftedMajorType)
Thiago Macieira355817e2015-05-08 18:38:18 -0700448{
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900449 CborError err;
Thiago Macieira4628a112016-07-30 23:04:46 -0700450 container->ptr = encoder->ptr;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700451 container->end = encoder->end;
452 ++encoder->added;
453 container->added = 0;
454
455 cbor_static_assert(((MapType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == CborIteratorFlag_ContainerIsMap);
456 cbor_static_assert(((ArrayType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == 0);
457 container->flags = shiftedMajorType & CborIteratorFlag_ContainerIsMap;
458
459 if (length == CborIndefiniteLength) {
460 container->flags |= CborIteratorFlag_UnknownLength;
461 err = append_byte_to_buffer(container, shiftedMajorType + IndefiniteLength);
462 } else {
463 err = encode_number_no_update(container, length, shiftedMajorType);
464 }
Erich Keane47a78562015-08-10 15:19:50 -0700465 if (err && !isOomError(err))
Thiago Macieira355817e2015-05-08 18:38:18 -0700466 return err;
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900467
Thiago Macieira355817e2015-05-08 18:38:18 -0700468 return CborNoError;
469}
470
Thiago Macieira46a818e2015-10-08 15:13:05 +0200471/**
472 * Creates a CBOR array in the CBOR stream provided by \a encoder and
473 * initializes \a arrayEncoder so that items can be added to the array using
474 * the CborEncoder functions. The array must be terminated by calling either
475 * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
476 * with the same \a encoder and \a arrayEncoder parameters.
477 *
478 * The number of items inserted into the array must be exactly \a length items,
479 * otherwise the stream is invalid. If the number of items is not known when
480 * creating the array, the constant \ref CborIndefiniteLength may be passed as
481 * length instead.
482 *
483 * \sa cbor_encoder_create_map
484 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700485CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length)
486{
Thiago Macieira56635242015-09-20 17:44:51 -0700487 return create_container(encoder, arrayEncoder, length, ArrayType << MajorTypeShift);
Thiago Macieira355817e2015-05-08 18:38:18 -0700488}
489
Thiago Macieira46a818e2015-10-08 15:13:05 +0200490/**
491 * Creates a CBOR map in the CBOR stream provided by \a encoder and
492 * initializes \a mapEncoder so that items can be added to the map using
493 * the CborEncoder functions. The map must be terminated by calling either
494 * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
495 * with the same \a encoder and \a mapEncoder parameters.
496 *
497 * The number of pair of items inserted into the map must be exactly \a length
498 * items, otherwise the stream is invalid. If the number of items is not known
499 * when creating the map, the constant \ref CborIndefiniteLength may be passed as
500 * length instead.
501 *
502 * \b{Implementation limitation:} TinyCBOR cannot encode more than SIZE_MAX/2
503 * key-value pairs in the stream. If the length \a length is larger than this
504 * value, this function returns error CborErrorDataTooLarge.
505 *
506 * \sa cbor_encoder_create_array
507 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700508CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length)
509{
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700510 if (length != CborIndefiniteLength && length > SIZE_MAX / 2)
511 return CborErrorDataTooLarge;
Thiago Macieira56635242015-09-20 17:44:51 -0700512 return create_container(encoder, mapEncoder, length, MapType << MajorTypeShift);
Thiago Macieira355817e2015-05-08 18:38:18 -0700513}
514
Thiago Macieira46a818e2015-10-08 15:13:05 +0200515/**
516 * Closes the CBOR container (array or map) provided by \a containerEncoder and
517 * updates the CBOR stream provided by \a encoder. Both parameters must be the
518 * same as were passed to cbor_encoder_create_array() or
519 * cbor_encoder_create_map().
520 *
521 * This function does not verify that the number of items (or pair of items, in
522 * the case of a map) was correct. To execute that verification, call
523 * cbor_encoder_close_container_checked() instead.
524 *
525 * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
526 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700527CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
528{
Thiago Macieira397f9792015-09-18 19:36:26 -0700529 if (encoder->end)
Thiago Macieira4628a112016-07-30 23:04:46 -0700530 encoder->ptr = containerEncoder->ptr;
Thiago Macieira397f9792015-09-18 19:36:26 -0700531 else
Thiago Macieira4628a112016-07-30 23:04:46 -0700532 encoder->bytes_needed = containerEncoder->bytes_needed;
Erich Keane47a78562015-08-10 15:19:50 -0700533 encoder->end = containerEncoder->end;
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900534 if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
535 return append_byte_to_buffer(encoder, BreakByte);
Thiago Macieira355817e2015-05-08 18:38:18 -0700536 return CborNoError;
537}
Thiago Macieira46a818e2015-10-08 15:13:05 +0200538
539/**
540 * \fn CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
541 *
542 * Appends the boolean value \a value to the CBOR stream provided by \a encoder.
543 */
544
545/**
546 * \fn CborError cbor_encode_null(CborEncoder *encoder)
547 *
548 * Appends the CBOR type representing a null value to the CBOR stream provided
549 * by \a encoder.
550 *
551 * \sa cbor_encode_undefined()
552 */
553
554/**
555 * \fn CborError cbor_encode_undefined(CborEncoder *encoder)
556 *
557 * Appends the CBOR type representing an undefined value to the CBOR stream
558 * provided by \a encoder.
559 *
560 * \sa cbor_encode_null()
561 */
562
563/**
564 * \fn CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
565 *
566 * Appends the IEEE 754 half-precision (16-bit) floating point value pointed to
567 * by \a value to the CBOR stream provided by \a encoder.
568 *
569 * \sa cbor_encode_floating_point(), cbor_encode_float(), cbor_encode_double()
570 */
571
572/**
573 * \fn CborError cbor_encode_float(CborEncoder *encoder, float value)
574 *
575 * Appends the IEEE 754 single-precision (32-bit) floating point value \a value
576 * to the CBOR stream provided by \a encoder.
577 *
578 * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_double()
579 */
580
581/**
582 * \fn CborError cbor_encode_double(CborEncoder *encoder, double value)
583 *
584 * Appends the IEEE 754 double-precision (64-bit) floating point value \a value
585 * to the CBOR stream provided by \a encoder.
586 *
587 * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_float()
588 */
589
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700590/**
591 * \fn size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
592 *
593 * Returns the total size of the buffer starting at \a buffer after the
594 * encoding finished without errors. The \a encoder and \a buffer arguments
595 * must be the same as supplied to cbor_encoder_init().
596 *
597 * If the encoding process had errors, the return value of this function is
598 * meaningless. If the only errors were CborErrorOutOfMemory, instead use
599 * cbor_encoder_get_extra_bytes_needed() to find out by how much to grow the
600 * buffer before encoding again.
601 *
602 * See \ref CborEncoding for an example of using this function.
603 *
604 * \sa cbor_encoder_init(), cbor_encoder_get_extra_bytes_needed(), CborEncoding
605 */
606
607/**
608 * \fn size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
609 *
610 * Returns how many more bytes the original buffer supplied to
611 * cbor_encoder_init() needs to be extended by so that no CborErrorOutOfMemory
612 * condition will happen for the encoding. If the buffer was big enough, this
613 * function returns 0. The \a encoder must be the original argument as passed
614 * to cbor_encoder_init().
615 *
616 * This function is usually called after an encoding sequence ended with one or
617 * more CborErrorOutOfMemory errors, but no other error. If any other error
618 * happened, the return value of this function is meaningless.
619 *
620 * See \ref CborEncoding for an example of using this function.
621 *
622 * \sa cbor_encoder_init(), cbor_encoder_get_buffer_size(), CborEncoding
623 */
624
Thiago Macieira46a818e2015-10-08 15:13:05 +0200625/** @} */