blob: a60e8930ee6be6eb61807f31896e962848ab007d [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
Vipul Rahane650c31f2017-12-15 12:48:40 -080025#ifndef _BSD_SOURCE
Thiago Macieiraed5b57c2015-07-07 16:38:27 -070026#define _BSD_SOURCE 1
Vipul Rahane650c31f2017-12-15 12:48:40 -080027#endif
28#ifndef _DEFAULT_SOURCE
Otavio Pontese2d5dd52016-07-08 09:49:38 -030029#define _DEFAULT_SOURCE 1
Vipul Rahane650c31f2017-12-15 12:48:40 -080030#endif
Thiago Macieira86c81862016-08-04 13:56:48 -070031#ifndef __STDC_LIMIT_MACROS
32# define __STDC_LIMIT_MACROS 1
33#endif
34
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070035#include "cbor.h"
Thiago Macieiracf3116e2017-03-04 23:36:23 -060036#include "cborinternal_p.h"
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070037#include "compilersupport_p.h"
38
Thiago Macieiraf1cadf02015-05-08 17:19:17 -070039#include <stdlib.h>
40#include <string.h>
41
Thiago Macieira46a818e2015-10-08 15:13:05 +020042/**
43 * \defgroup CborEncoding Encoding to CBOR
44 * \brief Group of functions used to encode data to CBOR.
45 *
46 * CborEncoder is used to encode data into a CBOR stream. The outermost
47 * CborEncoder is initialized by calling cbor_encoder_init(), with the buffer
48 * where the CBOR stream will be stored. The outermost CborEncoder is usually
49 * used to encode exactly one item, most often an array or map. It is possible
50 * to encode more than one item, but care must then be taken on the decoder
51 * side to ensure the state is reset after each item was decoded.
52 *
53 * Nested CborEncoder objects are created using cbor_encoder_create_array() and
54 * cbor_encoder_create_map(), later closed with cbor_encoder_close_container()
55 * or cbor_encoder_close_container_checked(). The pairs of creation and closing
56 * must be exactly matched and their parameters are always the same.
57 *
58 * CborEncoder writes directly to the user-supplied buffer, without extra
59 * buffering. CborEncoder does not allocate memory and CborEncoder objects are
60 * usually created on the stack of the encoding functions.
61 *
62 * The example below initializes a CborEncoder object with a buffer and encodes
63 * a single integer.
64 *
65 * \code
66 * uint8_t buf[16];
67 * CborEncoder encoder;
68 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
69 * cbor_encode_int(&encoder, some_value);
70 * \endcode
71 *
72 * As explained before, usually the outermost CborEncoder object is used to add
73 * one array or map, which in turn contains multiple elements. The example
74 * below creates a CBOR map with one element: a key "foo" and a boolean value.
75 *
76 * \code
77 * uint8_t buf[16];
78 * CborEncoder encoder, mapEncoder;
79 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
80 * cbor_encoder_create_map(&encoder, &mapEncoder, 1);
81 * cbor_encode_text_stringz(&mapEncoder, "foo");
82 * cbor_encode_boolean(&mapEncoder, some_value);
83 * cbor_encoder_close_container(&encoder, &mapEncoder);
84 * \endcode
85 *
86 * <h3 class="groupheader">Error checking and buffer size</h2>
87 *
88 * All functions operating on CborEncoder return a condition of type CborError.
89 * If the encoding was successful, they return CborNoError. Some functions do
90 * extra checking on the input provided and may return some other error
91 * conditions (for example, cbor_encode_simple_value() checks that the type is
92 * of the correct type).
93 *
94 * In addition, all functions check whether the buffer has enough bytes to
95 * encode the item being appended. If that is not possible, they return
96 * CborErrorOutOfMemory.
97 *
98 * It is possible to continue with the encoding of data past the first function
99 * that returns CborErrorOutOfMemory. CborEncoder functions will not overrun
100 * the buffer, but will instead count how many more bytes are needed to
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700101 * complete the encoding. At the end, you can obtain that count by calling
102 * cbor_encoder_get_extra_bytes_needed().
Thiago Macieira46a818e2015-10-08 15:13:05 +0200103 *
104 * \section1 Finalizing the encoding
105 *
106 * Once all items have been appended and the containers have all been properly
107 * closed, the user-supplied buffer will contain the CBOR stream and may be
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700108 * immediately used. To obtain the size of the buffer, call
109 * cbor_encoder_get_buffer_size() with the original buffer pointer.
Thiago Macieira46a818e2015-10-08 15:13:05 +0200110 *
111 * The example below illustrates how one can encode an item with error checking
112 * and then pass on the buffer for network sending.
113 *
114 * \code
115 * uint8_t buf[16];
116 * CborError err;
117 * CborEncoder encoder, mapEncoder;
118 * cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
119 * err = cbor_encoder_create_map(&encoder, &mapEncoder, 1);
120 * if (!err)
121 * return err;
122 * err = cbor_encode_text_stringz(&mapEncoder, "foo");
123 * if (!err)
124 * return err;
125 * err = cbor_encode_boolean(&mapEncoder, some_value);
126 * if (!err)
127 * return err;
128 * err = cbor_encoder_close_container_checked(&encoder, &mapEncoder);
129 * if (!err)
130 * return err;
131 *
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700132 * size_t len = cbor_encoder_get_buffer_size(&encoder, buf);
Thiago Macieira46a818e2015-10-08 15:13:05 +0200133 * send_payload(buf, len);
134 * return CborNoError;
135 * \endcode
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700136 *
137 * Finally, the example below illustrates expands on the one above and also
138 * deals with dynamically growing the buffer if the initial allocation wasn't
139 * big enough. Note the two places where the error checking was replaced with
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100140 * an cbor_assertion, showing where the author assumes no error can occur.
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700141 *
142 * \code
143 * uint8_t *encode_string_array(const char **strings, int n, size_t *bufsize)
144 * {
145 * CborError err;
146 * CborEncoder encoder, arrayEncoder;
147 * size_t size = 256;
148 * uint8_t *buf = NULL;
149 *
150 * while (1) {
151 * int i;
152 * size_t more_bytes;
153 * uint8_t *nbuf = realloc(buf, size);
154 * if (nbuf == NULL)
155 * goto error;
156 * buf = nbuf;
157 *
158 * cbor_encoder_init(&encoder, &buf, size, 0);
159 * err = cbor_encoder_create_array(&encoder, &arrayEncoder, n);
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100160 * cbor_assert(err); // can't fail, the buffer is always big enough
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700161 *
162 * for (i = 0; i < n; ++i) {
163 * err = cbor_encode_text_stringz(&arrayEncoder, strings[i]);
164 * if (err && err != CborErrorOutOfMemory)
165 * goto error;
166 * }
167 *
168 * err = cbor_encoder_close_container_checked(&encoder, &arrayEncoder);
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100169 * cbor_assert(err); // shouldn't fail!
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700170 *
171 * more_bytes = cbor_encoder_get_extra_bytes_needed(encoder);
172 * if (more_size) {
173 * // buffer wasn't big enough, try again
174 * size += more_bytes;
175 * continue;
176 * }
177 *
178 * *bufsize = cbor_encoder_get_buffer_size(encoder, buf);
179 * return buf;
180 * }
181 * error:
182 * free(buf);
183 * return NULL;
184 * }
185 * \endcode
Thiago Macieira46a818e2015-10-08 15:13:05 +0200186 */
187
188/**
189 * \addtogroup CborEncoding
190 * @{
191 */
192
193/**
194 * \struct CborEncoder
195 * Structure used to encode to CBOR.
196 */
197
198/**
199 * Initializes a CborEncoder structure \a encoder by pointing it to buffer \a
200 * buffer of size \a size. The \a flags field is currently unused and must be
201 * zero.
202 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700203void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700204{
Thiago Macieiraede7f142016-07-30 23:08:39 -0700205 encoder->data.ptr = buffer;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700206 encoder->end = buffer + size;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700207 encoder->added = 0;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700208 encoder->flags = flags;
209}
210
Thiago Macieira5752ce52015-06-16 12:10:03 -0700211static inline void put16(void *where, uint16_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700212{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700213 v = cbor_htons(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700214 memcpy(where, &v, sizeof(v));
215}
216
Thiago Macieiradbc01292016-06-06 17:02:25 -0700217/* Note: Since this is currently only used in situations where OOM is the only
218 * valid error, we KNOW this to be true. Thus, this function now returns just 'true',
219 * but if in the future, any function starts returning a non-OOM error, this will need
220 * to be changed to the test. At the moment, this is done to prevent more branches
221 * being created in the tinycbor output */
Erich Keane47a78562015-08-10 15:19:50 -0700222static inline bool isOomError(CborError err)
223{
224 (void) err;
225 return true;
226}
227
Thiago Macieira5752ce52015-06-16 12:10:03 -0700228static inline void put32(void *where, uint32_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700229{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700230 v = cbor_htonl(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700231 memcpy(where, &v, sizeof(v));
232}
233
Thiago Macieira5752ce52015-06-16 12:10:03 -0700234static inline void put64(void *where, uint64_t v)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700235{
Thiago Macieira5934a9f2015-06-16 11:55:28 -0700236 v = cbor_htonll(v);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700237 memcpy(where, &v, sizeof(v));
238}
239
Thiago Macieira397f9792015-09-18 19:36:26 -0700240static inline bool would_overflow(CborEncoder *encoder, size_t len)
241{
242 ptrdiff_t remaining = (ptrdiff_t)encoder->end;
Thiago Macieiraede7f142016-07-30 23:08:39 -0700243 remaining -= remaining ? (ptrdiff_t)encoder->data.ptr : encoder->data.bytes_needed;
Thiago Macieira397f9792015-09-18 19:36:26 -0700244 remaining -= (ptrdiff_t)len;
245 return unlikely(remaining < 0);
246}
247
248static inline void advance_ptr(CborEncoder *encoder, size_t n)
249{
250 if (encoder->end)
Thiago Macieiraede7f142016-07-30 23:08:39 -0700251 encoder->data.ptr += n;
Thiago Macieira397f9792015-09-18 19:36:26 -0700252 else
Thiago Macieiraede7f142016-07-30 23:08:39 -0700253 encoder->data.bytes_needed += n;
Thiago Macieira397f9792015-09-18 19:36:26 -0700254}
255
Thiago Macieira5752ce52015-06-16 12:10:03 -0700256static inline CborError append_to_buffer(CborEncoder *encoder, const void *data, size_t len)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700257{
Thiago Macieira397f9792015-09-18 19:36:26 -0700258 if (would_overflow(encoder, len)) {
Erich Keane47a78562015-08-10 15:19:50 -0700259 if (encoder->end != NULL) {
Thiago Macieiraede7f142016-07-30 23:08:39 -0700260 len -= encoder->end - encoder->data.ptr;
Thiago Macieira397f9792015-09-18 19:36:26 -0700261 encoder->end = NULL;
Thiago Macieiraede7f142016-07-30 23:08:39 -0700262 encoder->data.bytes_needed = 0;
Erich Keane47a78562015-08-10 15:19:50 -0700263 }
264
Thiago Macieira397f9792015-09-18 19:36:26 -0700265 advance_ptr(encoder, len);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700266 return CborErrorOutOfMemory;
Erich Keane47a78562015-08-10 15:19:50 -0700267 }
268
Thiago Macieiraede7f142016-07-30 23:08:39 -0700269 memcpy(encoder->data.ptr, data, len);
270 encoder->data.ptr += len;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700271 return CborNoError;
272}
273
Thiago Macieira5752ce52015-06-16 12:10:03 -0700274static inline CborError append_byte_to_buffer(CborEncoder *encoder, uint8_t byte)
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900275{
Thiago Macieira618d2f12015-09-22 09:14:29 -0700276 return append_to_buffer(encoder, &byte, 1);
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900277}
278
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700279static inline CborError encode_number_no_update(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700280{
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700281 /* Little-endian would have been so much more convenient here:
282 * We could just write at the beginning of buf but append_to_buffer
283 * only the necessary bytes.
284 * Since it has to be big endian, do it the other way around:
285 * write from the end. */
Thiago Macieira510e5b82015-09-21 16:05:02 -0700286 uint64_t buf[2];
287 uint8_t *const bufend = (uint8_t *)buf + sizeof(buf);
Thiago Macieira5752ce52015-06-16 12:10:03 -0700288 uint8_t *bufstart = bufend - 1;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700289 put64(buf + 1, ui); /* we probably have a bunch of zeros in the beginning */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700290
291 if (ui < Value8Bit) {
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700292 *bufstart += shiftedMajorType;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700293 } else {
alradmsft9ba47912016-10-11 17:56:15 -0700294 uint8_t more = 0;
Thiago Macieira13c85792015-07-07 16:15:41 -0700295 if (ui > 0xffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700296 ++more;
Thiago Macieira13c85792015-07-07 16:15:41 -0700297 if (ui > 0xffffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700298 ++more;
Thiago Macieira13c85792015-07-07 16:15:41 -0700299 if (ui > 0xffffffffU)
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700300 ++more;
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700301 bufstart -= (size_t)1 << more;
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700302 *bufstart = shiftedMajorType + Value8Bit + more;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700303 }
304
Thiago Macieiraafa4ff62015-05-09 10:09:55 -0700305 return append_to_buffer(encoder, bufstart, bufend - bufstart);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700306}
307
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700308static inline CborError encode_number(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
309{
310 ++encoder->added;
311 return encode_number_no_update(encoder, ui, shiftedMajorType);
312}
313
Thiago Macieira46a818e2015-10-08 15:13:05 +0200314/**
315 * Appends the unsigned 64-bit integer \a value to the CBOR stream provided by
316 * \a encoder.
317 *
318 * \sa cbor_encode_negative_int, cbor_encode_int
319 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700320CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value)
321{
322 return encode_number(encoder, value, UnsignedIntegerType << MajorTypeShift);
323}
324
Thiago Macieira46a818e2015-10-08 15:13:05 +0200325/**
326 * Appends the negative 64-bit integer whose absolute value is \a
327 * absolute_value to the CBOR stream provided by \a encoder.
328 *
329 * \sa cbor_encode_uint, cbor_encode_int
330 */
Thiago Macieira78632b32015-09-26 14:18:48 -0700331CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value)
332{
333 return encode_number(encoder, absolute_value, NegativeIntegerType << MajorTypeShift);
334}
335
Thiago Macieira46a818e2015-10-08 15:13:05 +0200336/**
337 * Appends the signed 64-bit integer \a value to the CBOR stream provided by
338 * \a encoder.
339 *
340 * \sa cbor_encode_negative_int, cbor_encode_uint
341 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700342CborError cbor_encode_int(CborEncoder *encoder, int64_t value)
343{
Thiago Macieiradbc01292016-06-06 17:02:25 -0700344 /* adapted from code in RFC 7049 appendix C (pseudocode) */
345 uint64_t ui = value >> 63; /* extend sign to whole length */
346 uint8_t majorType = ui & 0x20; /* extract major type */
347 ui ^= value; /* complement negatives */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700348 return encode_number(encoder, ui, majorType);
349}
350
Thiago Macieira46a818e2015-10-08 15:13:05 +0200351/**
352 * Appends the CBOR Simple Type of value \a value to the CBOR stream provided by
353 * \a encoder.
354 *
355 * This function may return error CborErrorIllegalSimpleType if the \a value
356 * variable contains a number that is not a valid simple type.
357 */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700358CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value)
359{
360#ifndef CBOR_ENCODER_NO_CHECK_USER
Thiago Macieiradbc01292016-06-06 17:02:25 -0700361 /* check if this is a valid simple type */
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700362 if (value >= HalfPrecisionFloat && value <= Break)
363 return CborErrorIllegalSimpleType;
364#endif
365 return encode_number(encoder, value, SimpleTypesType << MajorTypeShift);
366}
367
Thiago Macieira46a818e2015-10-08 15:13:05 +0200368/**
369 * Appends the floating-point value of type \a fpType and pointed to by \a
370 * value to the CBOR stream provided by \a encoder. The value of \a fpType must
371 * be one of CborHalfFloatType, CborFloatType or CborDoubleType, otherwise the
372 * behavior of this function is undefined.
373 *
374 * This function is useful for code that needs to pass through floating point
375 * values but does not wish to have the actual floating-point code.
376 *
377 * \sa cbor_encode_half_float, cbor_encode_float, cbor_encode_double
378 */
Thiago Macieira81f33432015-07-02 16:16:28 -0700379CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value)
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700380{
Thiago Macieira81f33432015-07-02 16:16:28 -0700381 uint8_t buf[1 + sizeof(uint64_t)];
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100382 cbor_assert(fpType == CborHalfFloatType || fpType == CborFloatType || fpType == CborDoubleType);
Thiago Macieira81f33432015-07-02 16:16:28 -0700383 buf[0] = fpType;
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700384
Thiago Macieira81f33432015-07-02 16:16:28 -0700385 unsigned size = 2U << (fpType - CborHalfFloatType);
386 if (size == 8)
387 put64(buf + 1, *(const uint64_t*)value);
388 else if (size == 4)
389 put32(buf + 1, *(const uint32_t*)value);
390 else
391 put16(buf + 1, *(const uint16_t*)value);
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700392 ++encoder->added;
Thiago Macieira81f33432015-07-02 16:16:28 -0700393 return append_to_buffer(encoder, buf, size + 1);
Thiago Macieiraf1cadf02015-05-08 17:19:17 -0700394}
Thiago Macieira8f98a112015-05-08 17:25:29 -0700395
Thiago Macieira46a818e2015-10-08 15:13:05 +0200396/**
397 * Appends the CBOR tag \a tag to the CBOR stream provided by \a encoder.
398 *
399 * \sa CborTag
400 */
Thiago Macieira8f98a112015-05-08 17:25:29 -0700401CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag)
402{
Thiago Macieiradbc01292016-06-06 17:02:25 -0700403 /* tags don't count towards the number of elements in an array or map */
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700404 return encode_number_no_update(encoder, tag, TagType << MajorTypeShift);
Thiago Macieira8f98a112015-05-08 17:25:29 -0700405}
Thiago Macieirab54debe2015-05-08 17:42:39 -0700406
Thiago Macieira5752ce52015-06-16 12:10:03 -0700407static CborError encode_string(CborEncoder *encoder, size_t length, uint8_t shiftedMajorType, const void *string)
Thiago Macieirab54debe2015-05-08 17:42:39 -0700408{
409 CborError err = encode_number(encoder, length, shiftedMajorType);
Erich Keane47a78562015-08-10 15:19:50 -0700410 if (err && !isOomError(err))
Thiago Macieirab54debe2015-05-08 17:42:39 -0700411 return err;
412 return append_to_buffer(encoder, string, length);
413}
414
Thiago Macieira46a818e2015-10-08 15:13:05 +0200415/**
416 * \fn CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
417 *
418 * Appends the null-terminated text string \a string to the CBOR stream
419 * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
420 * TinyCBOR makes no verification of correctness. The terminating null is not
421 * included in the stream.
422 *
423 * \sa cbor_encode_text_string, cbor_encode_byte_string
424 */
425
426/**
427 * Appends the text string \a string of length \a length to the CBOR stream
428 * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
429 * TinyCBOR makes no verification of correctness.
430 *
431 * \sa CborError cbor_encode_text_stringz, cbor_encode_byte_string
432 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700433CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length)
Thiago Macieirab54debe2015-05-08 17:42:39 -0700434{
435 return encode_string(encoder, length, ByteStringType << MajorTypeShift, string);
436}
437
Thiago Macieira46a818e2015-10-08 15:13:05 +0200438/**
439 * Appends the byte string \a string of length \a length to the CBOR stream
440 * provided by \a encoder. CBOR byte strings are arbitrary raw data.
441 *
442 * \sa cbor_encode_text_stringz, cbor_encode_text_string
443 */
Thiago Macieirab54debe2015-05-08 17:42:39 -0700444CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length)
445{
446 return encode_string(encoder, length, TextStringType << MajorTypeShift, string);
447}
Thiago Macieira355817e2015-05-08 18:38:18 -0700448
Thiago Macieira56635242015-09-20 17:44:51 -0700449#ifdef __GNUC__
450__attribute__((noinline))
451#endif
452static CborError create_container(CborEncoder *encoder, CborEncoder *container, size_t length, uint8_t shiftedMajorType)
Thiago Macieira355817e2015-05-08 18:38:18 -0700453{
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900454 CborError err;
Thiago Macieiraede7f142016-07-30 23:08:39 -0700455 container->data.ptr = encoder->data.ptr;
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700456 container->end = encoder->end;
457 ++encoder->added;
458 container->added = 0;
459
460 cbor_static_assert(((MapType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == CborIteratorFlag_ContainerIsMap);
461 cbor_static_assert(((ArrayType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == 0);
462 container->flags = shiftedMajorType & CborIteratorFlag_ContainerIsMap;
463
464 if (length == CborIndefiniteLength) {
465 container->flags |= CborIteratorFlag_UnknownLength;
466 err = append_byte_to_buffer(container, shiftedMajorType + IndefiniteLength);
467 } else {
468 err = encode_number_no_update(container, length, shiftedMajorType);
469 }
Thiago Macieira863a4802016-10-26 20:48:54 -0700470 return err;
Thiago Macieira355817e2015-05-08 18:38:18 -0700471}
472
Thiago Macieira46a818e2015-10-08 15:13:05 +0200473/**
474 * Creates a CBOR array in the CBOR stream provided by \a encoder and
475 * initializes \a arrayEncoder so that items can be added to the array using
476 * the CborEncoder functions. The array must be terminated by calling either
477 * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
478 * with the same \a encoder and \a arrayEncoder parameters.
479 *
480 * The number of items inserted into the array must be exactly \a length items,
481 * otherwise the stream is invalid. If the number of items is not known when
482 * creating the array, the constant \ref CborIndefiniteLength may be passed as
483 * length instead.
484 *
485 * \sa cbor_encoder_create_map
486 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700487CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length)
488{
Thiago Macieira56635242015-09-20 17:44:51 -0700489 return create_container(encoder, arrayEncoder, length, ArrayType << MajorTypeShift);
Thiago Macieira355817e2015-05-08 18:38:18 -0700490}
491
Thiago Macieira46a818e2015-10-08 15:13:05 +0200492/**
493 * Creates a CBOR map in the CBOR stream provided by \a encoder and
494 * initializes \a mapEncoder so that items can be added to the map using
495 * the CborEncoder functions. The map must be terminated by calling either
496 * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
497 * with the same \a encoder and \a mapEncoder parameters.
498 *
499 * The number of pair of items inserted into the map must be exactly \a length
500 * items, otherwise the stream is invalid. If the number of items is not known
501 * when creating the map, the constant \ref CborIndefiniteLength may be passed as
502 * length instead.
503 *
504 * \b{Implementation limitation:} TinyCBOR cannot encode more than SIZE_MAX/2
505 * key-value pairs in the stream. If the length \a length is larger than this
506 * value, this function returns error CborErrorDataTooLarge.
507 *
508 * \sa cbor_encoder_create_array
509 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700510CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length)
511{
Thiago Macieira4e9626c2015-09-21 14:57:17 -0700512 if (length != CborIndefiniteLength && length > SIZE_MAX / 2)
513 return CborErrorDataTooLarge;
Thiago Macieira56635242015-09-20 17:44:51 -0700514 return create_container(encoder, mapEncoder, length, MapType << MajorTypeShift);
Thiago Macieira355817e2015-05-08 18:38:18 -0700515}
516
Thiago Macieira46a818e2015-10-08 15:13:05 +0200517/**
518 * Closes the CBOR container (array or map) provided by \a containerEncoder and
519 * updates the CBOR stream provided by \a encoder. Both parameters must be the
520 * same as were passed to cbor_encoder_create_array() or
521 * cbor_encoder_create_map().
522 *
523 * This function does not verify that the number of items (or pair of items, in
524 * the case of a map) was correct. To execute that verification, call
525 * cbor_encoder_close_container_checked() instead.
526 *
527 * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
528 */
Thiago Macieira355817e2015-05-08 18:38:18 -0700529CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
530{
Thiago Macieira397f9792015-09-18 19:36:26 -0700531 if (encoder->end)
Thiago Macieiraede7f142016-07-30 23:08:39 -0700532 encoder->data.ptr = containerEncoder->data.ptr;
Thiago Macieira397f9792015-09-18 19:36:26 -0700533 else
Thiago Macieiraede7f142016-07-30 23:08:39 -0700534 encoder->data.bytes_needed = containerEncoder->data.bytes_needed;
Erich Keane47a78562015-08-10 15:19:50 -0700535 encoder->end = containerEncoder->end;
Thiago Macieira8f7bd9e2015-05-12 13:37:46 +0900536 if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
537 return append_byte_to_buffer(encoder, BreakByte);
Thiago Macieira5433fc32017-12-17 15:15:50 -0800538 if (!encoder->end)
Thiago Macieira3369dd12017-11-13 11:14:27 -0800539 return CborErrorOutOfMemory; /* keep the state */
Thiago Macieira355817e2015-05-08 18:38:18 -0700540 return CborNoError;
541}
Thiago Macieira46a818e2015-10-08 15:13:05 +0200542
543/**
544 * \fn CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
545 *
546 * Appends the boolean value \a value to the CBOR stream provided by \a encoder.
547 */
548
549/**
550 * \fn CborError cbor_encode_null(CborEncoder *encoder)
551 *
552 * Appends the CBOR type representing a null value to the CBOR stream provided
553 * by \a encoder.
554 *
555 * \sa cbor_encode_undefined()
556 */
557
558/**
559 * \fn CborError cbor_encode_undefined(CborEncoder *encoder)
560 *
561 * Appends the CBOR type representing an undefined value to the CBOR stream
562 * provided by \a encoder.
563 *
564 * \sa cbor_encode_null()
565 */
566
567/**
568 * \fn CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
569 *
570 * Appends the IEEE 754 half-precision (16-bit) floating point value pointed to
571 * by \a value to the CBOR stream provided by \a encoder.
572 *
573 * \sa cbor_encode_floating_point(), cbor_encode_float(), cbor_encode_double()
574 */
575
576/**
577 * \fn CborError cbor_encode_float(CborEncoder *encoder, float value)
578 *
579 * Appends the IEEE 754 single-precision (32-bit) floating point value \a value
580 * to the CBOR stream provided by \a encoder.
581 *
582 * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_double()
583 */
584
585/**
586 * \fn CborError cbor_encode_double(CborEncoder *encoder, double value)
587 *
588 * Appends the IEEE 754 double-precision (64-bit) floating point value \a value
589 * to the CBOR stream provided by \a encoder.
590 *
591 * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_float()
592 */
593
Thiago Macieira7ae36a72015-10-28 16:19:23 -0700594/**
595 * \fn size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
596 *
597 * Returns the total size of the buffer starting at \a buffer after the
598 * encoding finished without errors. The \a encoder and \a buffer arguments
599 * must be the same as supplied to cbor_encoder_init().
600 *
601 * If the encoding process had errors, the return value of this function is
602 * meaningless. If the only errors were CborErrorOutOfMemory, instead use
603 * cbor_encoder_get_extra_bytes_needed() to find out by how much to grow the
604 * buffer before encoding again.
605 *
606 * See \ref CborEncoding for an example of using this function.
607 *
608 * \sa cbor_encoder_init(), cbor_encoder_get_extra_bytes_needed(), CborEncoding
609 */
610
611/**
612 * \fn size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
613 *
614 * Returns how many more bytes the original buffer supplied to
615 * cbor_encoder_init() needs to be extended by so that no CborErrorOutOfMemory
616 * condition will happen for the encoding. If the buffer was big enough, this
617 * function returns 0. The \a encoder must be the original argument as passed
618 * to cbor_encoder_init().
619 *
620 * This function is usually called after an encoding sequence ended with one or
621 * more CborErrorOutOfMemory errors, but no other error. If any other error
622 * happened, the return value of this function is meaningless.
623 *
624 * See \ref CborEncoding for an example of using this function.
625 *
626 * \sa cbor_encoder_init(), cbor_encoder_get_buffer_size(), CborEncoding
627 */
628
Thiago Macieira46a818e2015-10-08 15:13:05 +0200629/** @} */