blob: 8aa1298372e330adce6102515355f868d7a4e7f8 [file] [log] [blame]
Thiago Macieira54a0e102015-05-05 21:25:06 -07001/****************************************************************************
2**
Thiago Macieira51b56062017-02-23 16:03:13 -08003** Copyright (C) 2017 Intel Corporation
Thiago Macieira54a0e102015-05-05 21:25:06 -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 Macieira54a0e102015-05-05 21:25:06 -070035#include "cbor.h"
Thiago Macieiracf3116e2017-03-04 23:36:23 -060036#include "cborinternal_p.h"
Thiago Macieira54a0e102015-05-05 21:25:06 -070037#include "compilersupport_p.h"
38
Thiago Macieira54a0e102015-05-05 21:25:06 -070039#include <string.h>
40
Thiago Macieira4a99af92015-05-12 10:41:45 +090041#ifndef CBOR_PARSER_MAX_RECURSIONS
42# define CBOR_PARSER_MAX_RECURSIONS 1024
43#endif
44
Thiago Macieira54a0e102015-05-05 21:25:06 -070045/**
Thiago Macieira46a818e2015-10-08 15:13:05 +020046 * \defgroup CborParsing Parsing CBOR streams
47 * \brief Group of functions used to parse CBOR streams.
Thiago Macieira54a0e102015-05-05 21:25:06 -070048 *
Thiago Macieira46a818e2015-10-08 15:13:05 +020049 * TinyCBOR provides functions for pull-based stream parsing of a CBOR-encoded
50 * payload. The main data type for the parsing is a CborValue, which behaves
51 * like an iterator and can be used to extract the encoded data. It is first
52 * initialized with a call to cbor_parser_init() and is usually used to extract
53 * exactly one item, most often an array or map.
Thiago Macieira54a0e102015-05-05 21:25:06 -070054 *
Thiago Macieira46a818e2015-10-08 15:13:05 +020055 * Nested CborValue objects can be parsed using cbor_value_enter_container().
56 * Each call to cbor_value_enter_container() must be matched by a call to
57 * cbor_value_leave_container(), with the exact same parameters.
Thiago Macieira54a0e102015-05-05 21:25:06 -070058 *
Thiago Macieira46a818e2015-10-08 15:13:05 +020059 * The example below initializes a CborParser object, begins the parsing with a
60 * CborValue and decodes a single integer:
61 *
62 * \code
63 * int extract_int(const uint8_t *buffer, size_t len)
64 * {
65 * CborParser parser;
66 * CborValue value;
67 * int result;
68 * cbor_parser_init(buffer, len, 0, &buffer, &value);
69 * cbor_value_get_int(&value, &result);
70 * return result;
71 * }
72 * \endcode
73 *
74 * The code above does no error checking, which means it assumes the data comes
75 * from a source trusted to send one properly-encoded integer. The following
76 * example does the exact same operation, but includes error parsing and
77 * returns 0 on parsing failure:
78 *
79 * \code
80 * int extract_int(const uint8_t *buffer, size_t len)
81 * {
82 * CborParser parser;
83 * CborValue value;
84 * int result;
85 * if (cbor_parser_init(buffer, len, 0, &buffer, &value) != CborNoError)
86 * return 0;
87 * if (!cbor_value_is_integer(&value) ||
88 * cbor_value_get_int(&value, &result) != CborNoError)
89 * return 0;
90 * return result;
91 * }
92 * \endcode
93 *
94 * Note, in the example above, that one can't distinguish a parsing failure
95 * from an encoded value of zero. Reporting a parsing error is left as an
96 * exercise to the reader.
97 *
98 * The code above does not execute a range-check either: it is possible that
99 * the value decoded from the CBOR stream encodes a number larger than what can
100 * be represented in a variable of type \c{int}. If detecting that case is
101 * important, the code should call cbor_value_get_int_checked() instead.
102 *
103 * <h3 class="groupheader">Memory and parsing constraints</h3>
104 *
105 * TinyCBOR is designed to run with little memory and with minimal overhead.
106 * Except where otherwise noted, the parser functions always run on constant
107 * time (O(1)), do not recurse and never allocate memory (thus, stack usage is
108 * bounded and is O(1)).
109 *
110 * <h3 class="groupheader">Error handling and preconditions</h3>
111 *
112 * All functions operating on a CborValue return a CborError condition, with
113 * CborNoError standing for the normal situation in which no parsing error
114 * occurred. All functions may return parsing errors in case the stream cannot
115 * be decoded properly, be it due to corrupted data or due to reaching the end
116 * of the input buffer.
117 *
118 * Error conditions must not be ignored. All decoder functions have undefined
119 * behavior if called after an error has been reported, and may crash.
120 *
121 * Some functions are also documented to have preconditions, like
122 * cbor_value_get_int() requiring that the input be an integral value.
123 * Violation of preconditions also results in undefined behavior and the
124 * program may crash.
125 */
126
127/**
128 * \addtogroup CborParsing
129 * @{
130 */
131
132/**
133 * \struct CborValue
134 *
135 * This type contains one value parsed from the CBOR stream. Each CborValue
136 * behaves as an iterator in a StAX-style parser.
137 *
138 * \if privatedocs
Thiago Macieira54a0e102015-05-05 21:25:06 -0700139 * Implementation details: the CborValue contains these fields:
140 * \list
141 * \li ptr: pointer to the actual data
142 * \li flags: flags from the decoder
Thiago Macieira2312efd2015-05-06 16:07:48 -0700143 * \li extra: partially decoded integer value (0, 1 or 2 bytes)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700144 * \li remaining: remaining items in this collection after this item or UINT32_MAX if length is unknown
145 * \endlist
Thiago Macieira46a818e2015-10-08 15:13:05 +0200146 * \endif
Thiago Macieira54a0e102015-05-05 21:25:06 -0700147 */
148
Thiago Macieira2c22d712017-03-05 00:17:35 -0600149static inline uint16_t get16(const uint8_t *ptr)
150{
151 uint16_t result;
152 memcpy(&result, ptr, sizeof(result));
153 return cbor_ntohs(result);
154}
155
156static inline uint32_t get32(const uint8_t *ptr)
157{
158 uint32_t result;
159 memcpy(&result, ptr, sizeof(result));
160 return cbor_ntohl(result);
161}
162
163static inline uint64_t get64(const uint8_t *ptr)
164{
165 uint64_t result;
166 memcpy(&result, ptr, sizeof(result));
167 return cbor_ntohll(result);
168}
169
Thiago Macieira2f5d20e2017-03-06 10:11:52 +0100170CBOR_INTERNAL_API_CC CborError _cbor_value_extract_number(const uint8_t **ptr, const uint8_t *end, uint64_t *len)
Thiago Macieira2c22d712017-03-05 00:17:35 -0600171{
172 uint8_t additional_information = **ptr & SmallValueMask;
173 ++*ptr;
174 if (additional_information < Value8Bit) {
175 *len = additional_information;
176 return CborNoError;
177 }
178 if (unlikely(additional_information > Value64Bit))
179 return CborErrorIllegalNumber;
180
181 size_t bytesNeeded = (size_t)(1 << (additional_information - Value8Bit));
182 if (unlikely(bytesNeeded > (size_t)(end - *ptr))) {
183 return CborErrorUnexpectedEOF;
184 } else if (bytesNeeded == 1) {
185 *len = (uint8_t)(*ptr)[0];
186 } else if (bytesNeeded == 2) {
187 *len = get16(*ptr);
188 } else if (bytesNeeded == 4) {
189 *len = get32(*ptr);
190 } else {
191 *len = get64(*ptr);
192 }
193 *ptr += bytesNeeded;
194 return CborNoError;
195}
196
Thiago Macieiraf5cb94b2015-06-16 16:10:49 -0700197static CborError extract_length(const CborParser *parser, const uint8_t **ptr, size_t *len)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700198{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700199 uint64_t v;
Thiago Macieira2c22d712017-03-05 00:17:35 -0600200 CborError err = _cbor_value_extract_number(ptr, parser->end, &v);
Mike Colagrosso629d5b72016-02-24 15:12:34 -0700201 if (err) {
202 *len = 0;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700203 return err;
Mike Colagrosso629d5b72016-02-24 15:12:34 -0700204 }
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700205
alradmsft9ba47912016-10-11 17:56:15 -0700206 *len = (size_t)v;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700207 if (v != *len)
208 return CborErrorDataTooLarge;
209 return CborNoError;
210}
211
212static bool is_fixed_type(uint8_t type)
213{
214 return type != CborTextStringType && type != CborByteStringType && type != CborArrayType &&
215 type != CborMapType;
216}
217
218static CborError preparse_value(CborValue *it)
219{
220 const CborParser *parser = it->parser;
Thiago Macieira11e913f2015-05-07 13:01:18 -0700221 it->type = CborInvalidType;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700222
Thiago Macieiradbc01292016-06-06 17:02:25 -0700223 /* are we at the end? */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700224 if (it->ptr == parser->end)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700225 return CborErrorUnexpectedEOF;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700226
227 uint8_t descriptor = *it->ptr;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700228 uint8_t type = descriptor & MajorTypeMask;
Thiago Macieira851c4812015-05-08 15:23:20 -0700229 it->type = type;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700230 it->flags = 0;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700231 it->extra = (descriptor &= SmallValueMask);
232
Thiago Macieira56d99832015-05-07 14:34:27 -0700233 if (descriptor > Value64Bit) {
234 if (unlikely(descriptor != IndefiniteLength))
Thiago Macieira3f76f632015-05-12 10:10:09 +0900235 return type == CborSimpleType ? CborErrorUnknownType : CborErrorIllegalNumber;
Thiago Macieira56d99832015-05-07 14:34:27 -0700236 if (likely(!is_fixed_type(type))) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700237 /* special case */
Thiago Macieira56d99832015-05-07 14:34:27 -0700238 it->flags |= CborIteratorFlag_UnknownLength;
239 it->type = type;
240 return CborNoError;
241 }
242 return type == CborSimpleType ? CborErrorUnexpectedBreak : CborErrorIllegalNumber;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700243 }
Thiago Macieira54a0e102015-05-05 21:25:06 -0700244
Thiago Macieirac70169f2015-05-06 07:49:44 -0700245 size_t bytesNeeded = descriptor < Value8Bit ? 0 : (1 << (descriptor - Value8Bit));
Thiago Macieira63abed92015-10-28 17:01:14 -0700246 if (bytesNeeded + 1 > (size_t)(parser->end - it->ptr))
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700247 return CborErrorUnexpectedEOF;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700248
Thiago Macieira851c4812015-05-08 15:23:20 -0700249 uint8_t majortype = type >> MajorTypeShift;
250 if (majortype == NegativeIntegerType) {
Thiago Macieira54a0e102015-05-05 21:25:06 -0700251 it->flags |= CborIteratorFlag_NegativeInteger;
Thiago Macieira851c4812015-05-08 15:23:20 -0700252 it->type = CborIntegerType;
253 } else if (majortype == SimpleTypesType) {
Thiago Macieira54a0e102015-05-05 21:25:06 -0700254 switch (descriptor) {
255 case FalseValue:
256 it->extra = false;
Thiago Macieira851c4812015-05-08 15:23:20 -0700257 it->type = CborBooleanType;
Thiago Macieira991dd922015-05-07 11:57:59 -0700258 break;
259
Thiago Macieira851c4812015-05-08 15:23:20 -0700260 case SinglePrecisionFloat:
261 case DoublePrecisionFloat:
262 it->flags |= CborIteratorFlag_IntegerValueTooLarge;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700263 /* fall through */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700264 case TrueValue:
265 case NullValue:
266 case UndefinedValue:
267 case HalfPrecisionFloat:
Thiago Macieira851c4812015-05-08 15:23:20 -0700268 it->type = *it->ptr;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700269 break;
270
271 case SimpleTypeInNextByte:
Thiago Macieira851c4812015-05-08 15:23:20 -0700272 it->extra = (uint8_t)it->ptr[1];
Thiago Macieira54a0e102015-05-05 21:25:06 -0700273#ifndef CBOR_PARSER_NO_STRICT_CHECKS
Thiago Macieira851c4812015-05-08 15:23:20 -0700274 if (unlikely(it->extra < 32)) {
275 it->type = CborInvalidType;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700276 return CborErrorIllegalSimpleType;
Thiago Macieira851c4812015-05-08 15:23:20 -0700277 }
Thiago Macieira54a0e102015-05-05 21:25:06 -0700278#endif
Thiago Macieira991dd922015-05-07 11:57:59 -0700279 break;
280
Thiago Macieira54a0e102015-05-05 21:25:06 -0700281 case 28:
282 case 29:
283 case 30:
Thiago Macieira54a0e102015-05-05 21:25:06 -0700284 case Break:
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100285 cbor_assert(false); /* these conditions can't be reached */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700286 return CborErrorUnexpectedBreak;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700287 }
Thiago Macieira851c4812015-05-08 15:23:20 -0700288 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700289 }
290
Thiago Macieiradbc01292016-06-06 17:02:25 -0700291 /* try to decode up to 16 bits */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700292 if (descriptor < Value8Bit)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700293 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700294
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700295 if (descriptor == Value8Bit)
296 it->extra = (uint8_t)it->ptr[1];
297 else if (descriptor == Value16Bit)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700298 it->extra = get16(it->ptr + 1);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700299 else
Thiago Macieiradbc01292016-06-06 17:02:25 -0700300 it->flags |= CborIteratorFlag_IntegerValueTooLarge; /* Value32Bit or Value64Bit */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700301 return CborNoError;
302}
Thiago Macieira54a0e102015-05-05 21:25:06 -0700303
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700304static CborError preparse_next_value(CborValue *it)
305{
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700306 if (it->remaining != UINT32_MAX) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700307 /* don't decrement the item count if the current item is tag: they don't count */
Thiago Macieira11e913f2015-05-07 13:01:18 -0700308 if (it->type != CborTagType && !--it->remaining) {
309 it->type = CborInvalidType;
Thiago Macieira56d99832015-05-07 14:34:27 -0700310 return CborNoError;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700311 }
Thiago Macieira5752ce52015-06-16 12:10:03 -0700312 } else if (it->remaining == UINT32_MAX && it->ptr != it->parser->end && *it->ptr == (uint8_t)BreakByte) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700313 /* end of map or array */
Thiago Macieira56d99832015-05-07 14:34:27 -0700314 ++it->ptr;
315 it->type = CborInvalidType;
316 it->remaining = 0;
317 return CborNoError;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700318 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700319
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700320 return preparse_value(it);
321}
322
323static CborError advance_internal(CborValue *it)
324{
325 uint64_t length;
Thiago Macieira2c22d712017-03-05 00:17:35 -0600326 CborError err = _cbor_value_extract_number(&it->ptr, it->parser->end, &length);
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100327 cbor_assert(err == CborNoError);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700328
Thiago Macieira56d99832015-05-07 14:34:27 -0700329 if (it->type == CborByteStringType || it->type == CborTextStringType) {
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100330 cbor_assert(length == (size_t)length);
331 cbor_assert((it->flags & CborIteratorFlag_UnknownLength) == 0);
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700332 it->ptr += length;
333 }
334
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700335 return preparse_next_value(it);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700336}
337
Thiago Macieira2312efd2015-05-06 16:07:48 -0700338/** \internal
339 *
340 * Decodes the CBOR integer value when it is larger than the 16 bits available
341 * in value->extra. This function requires that value->flags have the
342 * CborIteratorFlag_IntegerValueTooLarge flag set.
343 *
344 * This function is also used to extract single- and double-precision floating
345 * point values (SinglePrecisionFloat == Value32Bit and DoublePrecisionFloat ==
346 * Value64Bit).
347 */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700348uint64_t _cbor_value_decode_int64_internal(const CborValue *value)
349{
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100350 cbor_assert(value->flags & CborIteratorFlag_IntegerValueTooLarge ||
351 value->type == CborFloatType || value->type == CborDoubleType);
Thiago Macieira851c4812015-05-08 15:23:20 -0700352
Thiago Macieiradbc01292016-06-06 17:02:25 -0700353 /* since the additional information can only be Value32Bit or Value64Bit,
354 * we just need to test for the one bit those two options differ */
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100355 cbor_assert((*value->ptr & SmallValueMask) == Value32Bit || (*value->ptr & SmallValueMask) == Value64Bit);
Thiago Macieira851c4812015-05-08 15:23:20 -0700356 if ((*value->ptr & 1) == (Value32Bit & 1))
Thiago Macieira54a0e102015-05-05 21:25:06 -0700357 return get32(value->ptr + 1);
358
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100359 cbor_assert((*value->ptr & SmallValueMask) == Value64Bit);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700360 return get64(value->ptr + 1);
361}
362
363/**
364 * Initializes the CBOR parser for parsing \a size bytes beginning at \a
365 * buffer. Parsing will use flags set in \a flags. The iterator to the first
366 * element is returned in \a it.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700367 *
368 * The \a parser structure needs to remain valid throughout the decoding
369 * process. It is not thread-safe to share one CborParser among multiple
370 * threads iterating at the same time, but the object can be copied so multiple
371 * threads can iterate.
Thiago Macieira54a0e102015-05-05 21:25:06 -0700372 */
Thiago Macieira5752ce52015-06-16 12:10:03 -0700373CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700374{
375 memset(parser, 0, sizeof(*parser));
376 parser->end = buffer + size;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700377 parser->flags = flags;
378 it->parser = parser;
379 it->ptr = buffer;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700380 it->remaining = 1; /* there's one type altogether, usually an array or map */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700381 return preparse_value(it);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700382}
383
384/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200385 * \fn bool cbor_value_at_end(const CborValue *it)
386 *
387 * Returns true if \a it has reached the end of the iteration, usually when
Thiago Macieira740e29d2016-07-07 13:32:47 -0700388 * advancing after the last item in an array or map.
Thiago Macieira46a818e2015-10-08 15:13:05 +0200389 *
Thiago Macieira740e29d2016-07-07 13:32:47 -0700390 * In the case of the outermost CborValue object, this function returns true
391 * after decoding a single element. A pointer to the first byte of the
392 * remaining data (if any) can be obtained with cbor_value_get_next_byte().
393 *
394 * \sa cbor_value_advance(), cbor_value_is_valid(), cbor_value_get_next_byte()
395 */
396
397/**
398 * \fn const uint8_t *cbor_value_get_next_byte(const CborValue *it)
399 *
400 * Returns a pointer to the next byte that would be decoded if this CborValue
401 * object were advanced.
402 *
403 * This function is useful if cbor_value_at_end() returns true for the
404 * outermost CborValue: the pointer returned is the first byte of the data
405 * remaining in the buffer, if any. Code can decide whether to begin decoding a
406 * new CBOR data stream from this point, or parse some other data appended to
407 * the same buffer.
408 *
409 * This function may be used even after a parsing error. If that occurred,
410 * then this function returns a pointer to where the parsing error occurred.
411 * Note that the error recovery is not precise and the pointer may not indicate
412 * the exact byte containing bad data.
413 *
414 * \sa cbor_value_at_end()
Thiago Macieira46a818e2015-10-08 15:13:05 +0200415 */
416
417/**
418 * \fn bool cbor_value_is_valid(const CborValue *it)
419 *
420 * Returns true if the iterator \a it contains a valid value. Invalid iterators
421 * happen when iteration reaches the end of a container (see \ref
422 * cbor_value_at_end()) or when a search function resulted in no matches.
423 *
424 * \sa cbor_value_advance(), cbor_valie_at_end(), cbor_value_get_type()
425 */
426
427/**
Thiago Macieira73881122017-02-26 00:20:47 -0800428 * Performs a basic validation of the CBOR stream pointed by \a it and returns
429 * the error it found. If no error was found, it returns CborNoError and the
430 * application can iterate over the items with certainty that no other errors
431 * will appear during parsing.
432 *
433 * A basic validation checks for:
434 * \list
435 * \li absence of undefined additional information bytes;
436 * \li well-formedness of all numbers, lengths, and simple values;
437 * \li string contents match reported sizes;
438 * \li arrays and maps contain the number of elements they are reported to have;
439 * \endlist
440 *
441 * For further checks, see cbor_value_validate().
442 *
443 * This function has the same timing and memory requirements as
444 * cbor_value_advance().
445 *
446 * \sa cbor_value_validate(), cbor_value_advance()
447 */
448CborError cbor_value_validate_basic(const CborValue *it)
449{
450 CborValue value = *it;
451 return cbor_value_advance(&value);
452}
453
454/**
Thiago Macieira2312efd2015-05-06 16:07:48 -0700455 * Advances the CBOR value \a it by one fixed-size position. Fixed-size types
456 * are: integers, tags, simple types (including boolean, null and undefined
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700457 * values) and floating point types.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700458 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200459 * If the type is not of fixed size, this function has undefined behavior. Code
460 * must be sure that the current type is one of the fixed-size types before
461 * calling this function. This function is provided because it can guarantee
462 * that runs in constant time (O(1)).
463 *
464 * If the caller is not able to determine whether the type is fixed or not, code
465 * can use the cbor_value_advance() function instead.
466 *
467 * \sa cbor_value_at_end(), cbor_value_advance(), cbor_value_enter_container(), cbor_value_leave_container()
Thiago Macieira2312efd2015-05-06 16:07:48 -0700468 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700469CborError cbor_value_advance_fixed(CborValue *it)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700470{
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100471 cbor_assert(it->type != CborInvalidType);
472 cbor_assert(is_fixed_type(it->type));
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700473 if (!it->remaining)
474 return CborErrorAdvancePastEOF;
475 return advance_internal(it);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700476}
477
Thiago Macieira4a99af92015-05-12 10:41:45 +0900478static CborError advance_recursive(CborValue *it, int nestingLevel)
479{
480 if (is_fixed_type(it->type))
481 return advance_internal(it);
482
483 if (!cbor_value_is_container(it)) {
484 size_t len = SIZE_MAX;
Thiago Macieiraff130bc2015-06-19 15:15:33 -0700485 return _cbor_value_copy_string(it, NULL, &len, it);
Thiago Macieira4a99af92015-05-12 10:41:45 +0900486 }
487
Thiago Macieiradbc01292016-06-06 17:02:25 -0700488 /* map or array */
Thiago Macieira4a99af92015-05-12 10:41:45 +0900489 if (nestingLevel == CBOR_PARSER_MAX_RECURSIONS)
490 return CborErrorNestingTooDeep;
491
492 CborError err;
493 CborValue recursed;
494 err = cbor_value_enter_container(it, &recursed);
495 if (err)
496 return err;
497 while (!cbor_value_at_end(&recursed)) {
498 err = advance_recursive(&recursed, nestingLevel + 1);
499 if (err)
500 return err;
501 }
502 return cbor_value_leave_container(it, &recursed);
503}
504
505
Thiago Macieira2312efd2015-05-06 16:07:48 -0700506/**
507 * Advances the CBOR value \a it by one element, skipping over containers.
508 * Unlike cbor_value_advance_fixed(), this function can be called on a CBOR
509 * value of any type. However, if the type is a container (map or array) or a
510 * string with a chunked payload, this function will not run in constant time
511 * and will recurse into itself (it will run on O(n) time for the number of
512 * elements or chunks and will use O(n) memory for the number of nested
513 * containers).
514 *
Thiago Macieira73881122017-02-26 00:20:47 -0800515 * The number of recursions can be limited at compile time to avoid stack
516 * exhaustion in constrained systems.
517 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200518 * \sa cbor_value_at_end(), cbor_value_advance_fixed(), cbor_value_enter_container(), cbor_value_leave_container()
Thiago Macieira2312efd2015-05-06 16:07:48 -0700519 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700520CborError cbor_value_advance(CborValue *it)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700521{
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100522 cbor_assert(it->type != CborInvalidType);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700523 if (!it->remaining)
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700524 return CborErrorAdvancePastEOF;
Thiago Macieira4a99af92015-05-12 10:41:45 +0900525 return advance_recursive(it, 0);
Thiago Macieira2312efd2015-05-06 16:07:48 -0700526}
527
528/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200529 * \fn bool cbor_value_is_tag(const CborValue *value)
530 *
531 * Returns true if the iterator \a value is valid and points to a CBOR tag.
532 *
533 * \sa cbor_value_get_tag(), cbor_value_skip_tag()
534 */
535
536/**
537 * \fn CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
538 *
539 * Retrieves the CBOR tag value that \a value points to and stores it in \a
540 * result. If the iterator \a value does not point to a CBOR tag value, the
541 * behavior is undefined, so checking with \ref cbor_value_get_type or with
542 * \ref cbor_value_is_tag is recommended.
543 *
544 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_tag()
545 */
546
547/**
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700548 * Advances the CBOR value \a it until it no longer points to a tag. If \a it is
549 * already not pointing to a tag, then this function returns it unchanged.
550 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200551 * This function does not run in constant time: it will run on O(n) for n being
552 * the number of tags. It does use constant memory (O(1) memory requirements).
553 *
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700554 * \sa cbor_value_advance_fixed(), cbor_value_advance()
555 */
556CborError cbor_value_skip_tag(CborValue *it)
557{
558 while (cbor_value_is_tag(it)) {
559 CborError err = cbor_value_advance_fixed(it);
560 if (err)
561 return err;
562 }
563 return CborNoError;
564}
565
Thiago Macieirac4a73c62015-05-09 18:14:11 -0700566/**
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700567 * \fn bool cbor_value_is_container(const CborValue *it)
568 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700569 * Returns true if the \a it value is a container and requires recursion in
570 * order to decode (maps and arrays), false otherwise.
571 */
Thiago Macieira54a0e102015-05-05 21:25:06 -0700572
Thiago Macieira2312efd2015-05-06 16:07:48 -0700573/**
574 * Creates a CborValue iterator pointing to the first element of the container
575 * represented by \a it and saves it in \a recursed. The \a it container object
576 * needs to be kept and passed again to cbor_value_leave_container() in order
577 * to continue iterating past this container.
578 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200579 * The \a it CborValue iterator must point to a container.
580 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700581 * \sa cbor_value_is_container(), cbor_value_leave_container(), cbor_value_advance()
582 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700583CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed)
Thiago Macieira54a0e102015-05-05 21:25:06 -0700584{
Thiago Macieira56d99832015-05-07 14:34:27 -0700585 CborError err;
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100586 cbor_assert(cbor_value_is_container(it));
Thiago Macieira54a0e102015-05-05 21:25:06 -0700587 *recursed = *it;
Thiago Macieira56d99832015-05-07 14:34:27 -0700588
Thiago Macieira54a0e102015-05-05 21:25:06 -0700589 if (it->flags & CborIteratorFlag_UnknownLength) {
590 recursed->remaining = UINT32_MAX;
Thiago Macieira56d99832015-05-07 14:34:27 -0700591 ++recursed->ptr;
592 err = preparse_value(recursed);
593 if (err != CborErrorUnexpectedBreak)
594 return err;
Thiago Macieiradbc01292016-06-06 17:02:25 -0700595 /* actually, break was expected here
596 * it's just an empty container */
Thiago Macieira56d99832015-05-07 14:34:27 -0700597 ++recursed->ptr;
Thiago Macieira54a0e102015-05-05 21:25:06 -0700598 } else {
Thiago Macieira56d99832015-05-07 14:34:27 -0700599 uint64_t len;
Thiago Macieira2c22d712017-03-05 00:17:35 -0600600 err = _cbor_value_extract_number(&recursed->ptr, recursed->parser->end, &len);
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100601 cbor_assert(err == CborNoError);
Thiago Macieira56d99832015-05-07 14:34:27 -0700602
Thiago Macieirae12dfd02016-06-07 16:29:25 -0700603 recursed->remaining = (uint32_t)len;
Thiago Macieira3f76f632015-05-12 10:10:09 +0900604 if (recursed->remaining != len || len == UINT32_MAX) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700605 /* back track the pointer to indicate where the error occurred */
Thiago Macieira3f76f632015-05-12 10:10:09 +0900606 recursed->ptr = it->ptr;
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700607 return CborErrorDataTooLarge;
Thiago Macieira3f76f632015-05-12 10:10:09 +0900608 }
Thiago Macieirace16f052015-05-07 23:14:25 -0700609 if (recursed->type == CborMapType) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700610 /* maps have keys and values, so we need to multiply by 2 */
Thiago Macieira3f76f632015-05-12 10:10:09 +0900611 if (recursed->remaining > UINT32_MAX / 2) {
Thiago Macieiradbc01292016-06-06 17:02:25 -0700612 /* back track the pointer to indicate where the error occurred */
Thiago Macieira3f76f632015-05-12 10:10:09 +0900613 recursed->ptr = it->ptr;
Thiago Macieirace16f052015-05-07 23:14:25 -0700614 return CborErrorDataTooLarge;
Thiago Macieira3f76f632015-05-12 10:10:09 +0900615 }
Thiago Macieirace16f052015-05-07 23:14:25 -0700616 recursed->remaining *= 2;
617 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700618 if (len != 0)
619 return preparse_value(recursed);
Thiago Macieira54a0e102015-05-05 21:25:06 -0700620 }
Thiago Macieira56d99832015-05-07 14:34:27 -0700621
Thiago Macieiradbc01292016-06-06 17:02:25 -0700622 /* the case of the empty container */
Thiago Macieira56d99832015-05-07 14:34:27 -0700623 recursed->type = CborInvalidType;
624 recursed->remaining = 0;
625 return CborNoError;
Thiago Macieirac70169f2015-05-06 07:49:44 -0700626}
627
Thiago Macieira2312efd2015-05-06 16:07:48 -0700628/**
629 * Updates \a it to point to the next element after the container. The \a
Thiago Macieira56d99832015-05-07 14:34:27 -0700630 * recursed object needs to point to the element obtained either by advancing
631 * the last element of the container (via cbor_value_advance(),
632 * cbor_value_advance_fixed(), a nested cbor_value_leave_container(), or the \c
633 * next pointer from cbor_value_copy_string() or cbor_value_dup_string()).
Thiago Macieira2312efd2015-05-06 16:07:48 -0700634 *
Thiago Macieira46a818e2015-10-08 15:13:05 +0200635 * The \a it and \a recursed parameters must be the exact same as passed to
636 * cbor_value_enter_container().
637 *
Thiago Macieira2312efd2015-05-06 16:07:48 -0700638 * \sa cbor_value_enter_container(), cbor_value_at_end()
639 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700640CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed)
Thiago Macieirac70169f2015-05-06 07:49:44 -0700641{
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100642 cbor_assert(cbor_value_is_container(it));
643 cbor_assert(recursed->type == CborInvalidType);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700644 it->ptr = recursed->ptr;
Thiago Macieira56d99832015-05-07 14:34:27 -0700645 return preparse_next_value(it);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700646}
647
Thiago Macieira46a818e2015-10-08 15:13:05 +0200648
Thiago Macieira2312efd2015-05-06 16:07:48 -0700649/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200650 * \fn CborType cbor_value_get_type(const CborValue *value)
651 *
652 * Returns the type of the CBOR value that the iterator \a value points to. If
653 * \a value does not point to a valid value, this function returns \ref
654 * CborInvalidType.
655 *
656 * TinyCBOR also provides functions to test directly if a given CborValue object
657 * is of a given type, like cbor_value_is_text_string() and cbor_value_is_null().
658 *
659 * \sa cbor_value_is_valid()
660 */
661
662/**
663 * \fn bool cbor_value_is_null(const CborValue *value)
664 *
665 * Returns true if the iterator \a value is valid and points to a CBOR null type.
666 *
667 * \sa cbor_value_is_valid(), cbor_value_is_undefined()
668 */
669
670/**
671 * \fn bool cbor_value_is_undefined(const CborValue *value)
672 *
673 * Returns true if the iterator \a value is valid and points to a CBOR undefined type.
674 *
675 * \sa cbor_value_is_valid(), cbor_value_is_null()
676 */
677
678/**
679 * \fn bool cbor_value_is_boolean(const CborValue *value)
680 *
681 * Returns true if the iterator \a value is valid and points to a CBOR boolean
682 * type (true or false).
683 *
684 * \sa cbor_value_is_valid(), cbor_value_get_boolean()
685 */
686
687/**
688 * \fn CborError cbor_value_get_boolean(const CborValue *value, bool *result)
689 *
690 * Retrieves the boolean value that \a value points to and stores it in \a
691 * result. If the iterator \a value does not point to a boolean value, the
692 * behavior is undefined, so checking with \ref cbor_value_get_type or with
693 * \ref cbor_value_is_boolean is recommended.
694 *
695 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_boolean()
696 */
697
698/**
699 * \fn bool cbor_value_is_simple_type(const CborValue *value)
700 *
701 * Returns true if the iterator \a value is valid and points to a CBOR Simple Type
702 * type (other than true, false, null and undefined).
703 *
704 * \sa cbor_value_is_valid(), cbor_value_get_simple_type()
705 */
706
707/**
708 * \fn CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
709 *
710 * Retrieves the CBOR Simple Type value that \a value points to and stores it
711 * in \a result. If the iterator \a value does not point to a simple_type
712 * value, the behavior is undefined, so checking with \ref cbor_value_get_type
713 * or with \ref cbor_value_is_simple_type is recommended.
714 *
715 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_simple_type()
716 */
717
718/**
719 * \fn bool cbor_value_is_integer(const CborValue *value)
720 *
721 * Returns true if the iterator \a value is valid and points to a CBOR integer
722 * type.
723 *
724 * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_uint64, cbor_value_get_raw_integer
725 */
726
727/**
728 * \fn bool cbor_value_is_unsigned_integer(const CborValue *value)
729 *
730 * Returns true if the iterator \a value is valid and points to a CBOR unsigned
731 * integer type (positive values or zero).
732 *
733 * \sa cbor_value_is_valid(), cbor_value_get_uint64()
734 */
735
736/**
737 * \fn bool cbor_value_is_negative_integer(const CborValue *value)
738 *
739 * Returns true if the iterator \a value is valid and points to a CBOR negative
740 * integer type.
741 *
742 * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_raw_integer
743 */
744
745/**
746 * \fn CborError cbor_value_get_int(const CborValue *value, int *result)
747 *
748 * Retrieves the CBOR integer value that \a value points to and stores it in \a
749 * result. If the iterator \a value does not point to an integer value, the
750 * behavior is undefined, so checking with \ref cbor_value_get_type or with
751 * \ref cbor_value_is_integer is recommended.
752 *
753 * Note that this function does not do range-checking: integral values that do
754 * not fit in a variable of type \c{int} are silently truncated to fit. Use
755 * cbor_value_get_int_checked() that is not acceptable.
756 *
757 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
758 */
759
760/**
761 * \fn CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
762 *
763 * Retrieves the CBOR integer value that \a value points to and stores it in \a
764 * result. If the iterator \a value does not point to an integer value, the
765 * behavior is undefined, so checking with \ref cbor_value_get_type or with
766 * \ref cbor_value_is_integer is recommended.
767 *
768 * Note that this function does not do range-checking: integral values that do
769 * not fit in a variable of type \c{int64_t} are silently truncated to fit. Use
770 * cbor_value_get_int64_checked() that is not acceptable.
771 *
772 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
773 */
774
775/**
776 * \fn CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
777 *
778 * Retrieves the CBOR integer value that \a value points to and stores it in \a
779 * result. If the iterator \a value does not point to an unsigned integer
780 * value, the behavior is undefined, so checking with \ref cbor_value_get_type
781 * or with \ref cbor_value_is_unsigned_integer is recommended.
782 *
783 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_unsigned_integer()
784 */
785
786/**
787 * \fn CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
788 *
789 * Retrieves the CBOR integer value that \a value points to and stores it in \a
790 * result. If the iterator \a value does not point to an integer value, the
791 * behavior is undefined, so checking with \ref cbor_value_get_type or with
792 * \ref cbor_value_is_integer is recommended.
793 *
794 * This function is provided because CBOR negative integers can assume values
795 * that cannot be represented with normal 64-bit integer variables.
796 *
797 * If the integer is unsigned (that is, if cbor_value_is_unsigned_integer()
798 * returns true), then \a result will contain the actual value. If the integer
799 * is negative, then \a result will contain the absolute value of that integer,
800 * minus one. That is, \c {actual = -result - 1}. On architectures using two's
801 * complement for representation of negative integers, it is equivalent to say
802 * that \a result will contain the bitwise negation of the actual value.
803 *
804 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
805 */
806
807/**
Thiago Macieira0f02e792016-07-07 19:55:08 -0700808 * Retrieves the CBOR integer value that \a value points to and stores it in \a
809 * result. If the iterator \a value does not point to an integer value, the
810 * behavior is undefined, so checking with \ref cbor_value_get_type or with
811 * \ref cbor_value_is_integer is recommended.
812 *
813 * Unlike cbor_value_get_int64(), this function performs a check to see if the
814 * stored integer fits in \a result without data loss. If the number is outside
815 * the valid range for the data type, this function returns the recoverable
816 * error CborErrorDataTooLarge. In that case, use either
817 * cbor_value_get_uint64() (if the number is positive) or
818 * cbor_value_get_raw_integer().
819 *
820 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64()
821 */
822CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result)
823{
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100824 cbor_assert(cbor_value_is_integer(value));
Thiago Macieira0f02e792016-07-07 19:55:08 -0700825 uint64_t v = _cbor_value_extract_int64_helper(value);
826
827 /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
828 * "[if] the new type is signed and the value cannot be represented in it; either the
829 * result is implementation-defined or an implementation-defined signal is raised."
830 *
831 * The range for int64_t is -2^63 to 2^63-1 (int64_t is required to be
832 * two's complement, C11 7.20.1.1 paragraph 3), which in CBOR is
833 * represented the same way, differing only on the "sign bit" (the major
834 * type).
835 */
836
837 if (unlikely(v > (uint64_t)INT64_MAX))
838 return CborErrorDataTooLarge;
839
840 *result = v;
841 if (value->flags & CborIteratorFlag_NegativeInteger)
842 *result = -*result - 1;
843 return CborNoError;
844}
845
846/**
847 * Retrieves the CBOR integer value that \a value points to and stores it in \a
848 * result. If the iterator \a value does not point to an integer value, the
849 * behavior is undefined, so checking with \ref cbor_value_get_type or with
850 * \ref cbor_value_is_integer is recommended.
851 *
852 * Unlike cbor_value_get_int(), this function performs a check to see if the
853 * stored integer fits in \a result without data loss. If the number is outside
854 * the valid range for the data type, this function returns the recoverable
855 * error CborErrorDataTooLarge. In that case, use one of the other integer
856 * functions to obtain the value.
857 *
858 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64(),
859 * cbor_value_get_uint64(), cbor_value_get_int64_checked(), cbor_value_get_raw_integer()
860 */
861CborError cbor_value_get_int_checked(const CborValue *value, int *result)
862{
Thiago Macieirada8e35e2017-03-05 09:58:01 +0100863 cbor_assert(cbor_value_is_integer(value));
Thiago Macieira0f02e792016-07-07 19:55:08 -0700864 uint64_t v = _cbor_value_extract_int64_helper(value);
865
866 /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
867 * "[if] the new type is signed and the value cannot be represented in it; either the
868 * result is implementation-defined or an implementation-defined signal is raised."
869 *
870 * But we can convert from signed to unsigned without fault (paragraph 2).
871 *
872 * The range for int is implementation-defined and int is not guaranteed use
873 * two's complement representation (int32_t is).
874 */
875
876 if (value->flags & CborIteratorFlag_NegativeInteger) {
877 if (unlikely(v > (unsigned) -(INT_MIN + 1)))
878 return CborErrorDataTooLarge;
879
alradmsft9ba47912016-10-11 17:56:15 -0700880 *result = (int)v;
Thiago Macieira0f02e792016-07-07 19:55:08 -0700881 *result = -*result - 1;
882 } else {
883 if (unlikely(v > (uint64_t)INT_MAX))
884 return CborErrorDataTooLarge;
885
alradmsft9ba47912016-10-11 17:56:15 -0700886 *result = (int)v;
Thiago Macieira0f02e792016-07-07 19:55:08 -0700887 }
888 return CborNoError;
889
890}
891
892/**
Thiago Macieira46a818e2015-10-08 15:13:05 +0200893 * \fn bool cbor_value_is_length_known(const CborValue *value)
894 *
895 * Returns true if the length of this type is known without calculation. That
896 * is, if the length of this CBOR string, map or array is encoded in the data
897 * stream, this function returns true. If the length is not encoded, it returns
898 * false.
899 *
900 * If the length is known, code can call cbor_value_get_string_length(),
901 * cbor_value_get_array_length() or cbor_value_get_map_length() to obtain the
902 * length. If the length is not known but is necessary, code can use the
903 * cbor_value_calculate_string_length() function (no equivalent function is
904 * provided for maps and arrays).
905 */
906
907/**
908 * \fn bool cbor_value_is_text_string(const CborValue *value)
909 *
910 * Returns true if the iterator \a value is valid and points to a CBOR text
911 * string. CBOR text strings are UTF-8 encoded and usually contain
912 * human-readable text.
913 *
914 * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
915 * cbor_value_copy_text_string(), cbor_value_dup_text_string()
916 */
917
918/**
919 * \fn bool cbor_value_is_byte_string(const CborValue *value)
920 *
921 * Returns true if the iterator \a value is valid and points to a CBOR text
922 * string. CBOR byte strings are binary data with no specified encoding or
923 * format.
924 *
925 * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
926 * cbor_value_copy_byte_string(), cbor_value_dup_byte_string()
927 */
928
929/**
930 * \fn CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
931 *
932 * Extracts the length of the byte or text string that \a value points to and
933 * stores it in \a result. If the iterator \a value does not point to a text
934 * string or a byte string, the behaviour is undefined, so checking with \ref
935 * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
936 * cbor_value_is_byte_string is recommended.
937 *
938 * If the length of this string is not encoded in the CBOR data stream, this
939 * function will return the recoverable error CborErrorUnknownLength. You may
940 * also check whether that is the case by using cbor_value_is_length_known().
941 *
942 * If the length of the string is required but the length was not encoded, use
943 * cbor_value_calculate_string_length(), but note that that function does not
944 * run in constant time.
945 *
946 * \note On 32-bit platforms, this function will return error condition of \ref
947 * CborErrorDataTooLarge if the stream indicates a length that is too big to
948 * fit in 32-bit.
949 *
950 * \sa cbor_value_is_valid(), cbor_value_is_length_known(), cbor_value_calculate_string_length()
951 */
952
953/**
954 * Calculates the length of the byte or text string that \a value points to and
955 * stores it in \a len. If the iterator \a value does not point to a text
956 * string or a byte string, the behaviour is undefined, so checking with \ref
957 * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
958 * cbor_value_is_byte_string is recommended.
959 *
960 * This function is different from cbor_value_get_string_length() in that it
961 * calculates the length even for strings sent in chunks. For that reason, this
962 * function may not run in constant time (it will run in O(n) time on the
963 * number of chunks). It does use constant memory (O(1)).
Thiago Macieira2312efd2015-05-06 16:07:48 -0700964 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700965 * \note On 32-bit platforms, this function will return error condition of \ref
966 * CborErrorDataTooLarge if the stream indicates a length that is too big to
967 * fit in 32-bit.
Thiago Macieira2312efd2015-05-06 16:07:48 -0700968 *
Thiago Macieira51b56062017-02-23 16:03:13 -0800969 * \sa cbor_value_get_string_length(), cbor_value_copy_text_string(), cbor_value_copy_byte_string(), cbor_value_is_length_known()
Thiago Macieira2312efd2015-05-06 16:07:48 -0700970 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -0700971CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len)
Thiago Macieira2312efd2015-05-06 16:07:48 -0700972{
Thiago Macieira9ae05812015-05-11 15:09:09 +0900973 *len = SIZE_MAX;
Thiago Macieiraff130bc2015-06-19 15:15:33 -0700974 return _cbor_value_copy_string(value, NULL, len, NULL);
Thiago Macieirac70169f2015-05-06 07:49:44 -0700975}
976
Thiago Macieira57ba7c92017-02-25 22:32:20 -0800977static inline void prepare_string_iteration(CborValue *it)
978{
979 if (!cbor_value_is_length_known(it)) {
980 /* chunked string: we're before the first chunk;
981 * advance to the first chunk */
982 ++it->ptr;
983 it->flags |= CborIteratorFlag_IteratingStringChunks;
984 }
985}
986
987CBOR_INTERNAL_API_CC CborError _cbor_value_prepare_string_iteration(CborValue *it)
988{
989 cbor_assert((it->flags & CborIteratorFlag_IteratingStringChunks) == 0);
990 prepare_string_iteration(it);
991
992 /* are we at the end? */
993 if (it->ptr == it->parser->end)
994 return CborErrorUnexpectedEOF;
995 return CborNoError;
996}
997
Thiago Macieira51b56062017-02-23 16:03:13 -0800998static CborError get_string_chunk(CborValue *it, const void **bufferptr, size_t *len)
999{
1000 CborError err;
1001
1002 /* Possible states:
1003 * length known | iterating | meaning
1004 * no | no | before the first chunk of a chunked string
1005 * yes | no | at a non-chunked string
1006 * no | yes | second or later chunk
1007 * yes | yes | after a non-chunked string
1008 */
1009 if (it->flags & CborIteratorFlag_IteratingStringChunks) {
1010 /* already iterating */
1011 if (cbor_value_is_length_known(it)) {
1012 /* if the length was known, it wasn't chunked, so finish iteration */
1013 goto last_chunk;
1014 }
Thiago Macieira57ba7c92017-02-25 22:32:20 -08001015 } else {
1016 prepare_string_iteration(it);
Thiago Macieira51b56062017-02-23 16:03:13 -08001017 }
1018
1019 /* are we at the end? */
1020 if (it->ptr == it->parser->end)
1021 return CborErrorUnexpectedEOF;
1022
1023 if (*it->ptr == BreakByte) {
1024 /* last chunk */
1025 ++it->ptr;
1026last_chunk:
1027 *bufferptr = NULL;
1028 return preparse_next_value(it);
1029 } else if ((uint8_t)(*it->ptr & MajorTypeMask) == it->type) {
1030 err = extract_length(it->parser, &it->ptr, len);
1031 if (err)
1032 return err;
1033 if (*len > (size_t)(it->parser->end - it->ptr))
1034 return CborErrorUnexpectedEOF;
1035
1036 *bufferptr = it->ptr;
1037 it->ptr += *len;
1038 } else {
1039 return CborErrorIllegalType;
1040 }
1041
1042 it->flags |= CborIteratorFlag_IteratingStringChunks;
1043 return CborNoError;
1044}
1045
1046/**
1047 * \fn CborError cbor_value_get_text_string_chunk(const CborValue *value, const char **bufferptr, size_t *len, CborValue *next)
1048 *
1049 * Extracts one text string chunk pointed to by \a value and stores a pointer
1050 * to the data in \a buffer and the size in \a len, which must not be null. If
1051 * no more chunks are available, then \a bufferptr will be set to null. This
1052 * function may be used to iterate over any string without causing its contents
1053 * to be copied to a separate buffer, like the convenience function
1054 * cbor_value_copy_text_string() does.
1055 *
1056 * It is designed to be used in code like:
1057 *
1058 * \code
1059 * if (cbor_value_is_text_string(value)) {
1060 * char *ptr;
1061 * size_t len;
1062 * while (1) {
1063 * err = cbor_value_get_text_string_chunk(value, &ptr, &len, &value));
1064 * if (err) return err;
1065 * if (ptr == NULL) return CborNoError;
1066 * consume(ptr, len);
1067 * }
1068 * }
1069 * \endcode
1070 *
1071 * If the iterator \a value does not point to a text string, the behaviour is
1072 * undefined, so checking with \ref cbor_value_get_type or \ref
1073 * cbor_value_is_text_string is recommended.
1074 *
1075 * The \a next pointer, if not null, will be updated to point to the next item
1076 * after this string. During iteration, the pointer must only be passed back
1077 * again to this function; passing it to any other function in this library
1078 * results in undefined behavior. If there are no more chunks to be read from
1079 * \a value, then \a next will be set to the next item after this string; if \a
1080 * value points to the last item, then \a next will be invalid.
1081 *
1082 * \note This function does not perform UTF-8 validation on the incoming text
1083 * string.
1084 *
1085 * \sa cbor_value_dup_text_string(), cbor_value_copy_text_string(), cbor_value_caculate_string_length(), cbor_value_get_byte_string_chunk()
1086 */
1087
1088/**
1089 * \fn CborError cbor_value_get_byte_string_chunk(const CborValue *value, const char **bufferptr, size_t *len, CborValue *next)
1090 *
1091 * Extracts one byte string chunk pointed to by \a value and stores a pointer
1092 * to the data in \a buffer and the size in \a len, which must not be null. If
1093 * no more chunks are available, then \a bufferptr will be set to null. This
1094 * function may be used to iterate over any string without causing its contents
1095 * to be copied to a separate buffer, like the convenience function
1096 * cbor_value_copy_byte_string() does.
1097 *
1098 * It is designed to be used in code like:
1099 *
1100 * \code
1101 * if (cbor_value_is_byte_string(value)) {
1102 * char *ptr;
1103 * size_t len;
1104 * while (1) {
1105 * err = cbor_value_get_byte_string_chunk(value, &ptr, &len, &value));
1106 * if (err) return err;
1107 * if (ptr == NULL) return CborNoError;
1108 * consume(ptr, len);
1109 * }
1110 * }
1111 * \endcode
1112 *
1113 * If the iterator \a value does not point to a byte string, the behaviour is
1114 * undefined, so checking with \ref cbor_value_get_type or \ref
1115 * cbor_value_is_byte_string is recommended.
1116 *
1117 * The \a next pointer, if not null, will be updated to point to the next item
1118 * after this string. During iteration, the pointer must only be passed back
1119 * again to this function; passing it to any other function in this library
1120 * results in undefined behavior. If there are no more chunks to be read from
1121 * \a value, then \a next will be set to the next item after this string; if \a
1122 * value points to the last item, then \a next will be invalid.
1123 *
1124 * \sa cbor_value_dup_byte_string(), cbor_value_copy_byte_string(), cbor_value_caculate_string_length(), cbor_value_get_text_string_chunk()
1125 */
1126
1127CborError _cbor_value_get_string_chunk(const CborValue *value, const void **bufferptr,
1128 size_t *len, CborValue *next)
1129{
1130 CborValue tmp;
1131 if (!next)
1132 next = &tmp;
1133 *next = *value;
1134 return get_string_chunk(next, bufferptr, len);
1135}
1136
Thiago Macieiradbc01292016-06-06 17:02:25 -07001137/* We return uintptr_t so that we can pass memcpy directly as the iteration
1138 * function. The choice is to optimize for memcpy, which is used in the base
1139 * parser API (cbor_value_copy_string), while memcmp is used in convenience API
1140 * only. */
Thiago Macieira5752ce52015-06-16 12:10:03 -07001141typedef uintptr_t (*IterateFunction)(char *, const uint8_t *, size_t);
Thiago Macieira9ae05812015-05-11 15:09:09 +09001142
Thiago Macieira5752ce52015-06-16 12:10:03 -07001143static uintptr_t iterate_noop(char *dest, const uint8_t *src, size_t len)
Thiago Macieira9ae05812015-05-11 15:09:09 +09001144{
1145 (void)dest;
1146 (void)src;
1147 (void)len;
1148 return true;
1149}
1150
Thiago Macieira5752ce52015-06-16 12:10:03 -07001151static uintptr_t iterate_memcmp(char *s1, const uint8_t *s2, size_t len)
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001152{
Thiago Macieira5752ce52015-06-16 12:10:03 -07001153 return memcmp(s1, (const char *)s2, len) == 0;
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001154}
1155
alradmsftacf202a2017-03-03 18:23:17 -08001156static uintptr_t iterate_memcpy(char *dest, const uint8_t *src, size_t len)
1157{
1158 return (uintptr_t)memcpy(dest, src, len);
1159}
1160
Thiago Macieira9ae05812015-05-11 15:09:09 +09001161static CborError iterate_string_chunks(const CborValue *value, char *buffer, size_t *buflen,
1162 bool *result, CborValue *next, IterateFunction func)
1163{
Thiago Macieirada8e35e2017-03-05 09:58:01 +01001164 cbor_assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
Thiago Macieira9ae05812015-05-11 15:09:09 +09001165
Thiago Macieira9ae05812015-05-11 15:09:09 +09001166 CborError err;
Thiago Macieira2dcf42f2017-02-24 21:17:51 -08001167 CborValue tmp;
1168 size_t total = 0;
1169 const void *ptr;
1170
1171 if (!next)
1172 next = &tmp;
1173 *next = *value;
1174 *result = true;
1175
1176 while (1) {
1177 size_t newTotal;
1178 size_t chunkLen;
1179 err = get_string_chunk(next, &ptr, &chunkLen);
Thiago Macieira9ae05812015-05-11 15:09:09 +09001180 if (err)
1181 return err;
Thiago Macieira2dcf42f2017-02-24 21:17:51 -08001182 if (!ptr)
1183 break;
1184
1185 if (unlikely(add_check_overflow(total, chunkLen, &newTotal)))
1186 return CborErrorDataTooLarge;
1187
1188 if (*result && *buflen >= newTotal)
1189 *result = !!func(buffer + total, (const uint8_t *)ptr, chunkLen);
Thiago Macieira9ae05812015-05-11 15:09:09 +09001190 else
1191 *result = false;
Thiago Macieira9ae05812015-05-11 15:09:09 +09001192
Thiago Macieira2dcf42f2017-02-24 21:17:51 -08001193 total = newTotal;
Thiago Macieira9ae05812015-05-11 15:09:09 +09001194 }
1195
Thiago Macieiradbc01292016-06-06 17:02:25 -07001196 /* is there enough room for the ending NUL byte? */
Thiago Macieirae136feb2017-02-24 21:21:04 -08001197 if (*result && *buflen > total) {
1198 uint8_t nul[] = { 0 };
1199 *result = !!func(buffer + total, nul, 1);
1200 }
Thiago Macieira9ae05812015-05-11 15:09:09 +09001201 *buflen = total;
Thiago Macieira9ae05812015-05-11 15:09:09 +09001202 return CborNoError;
1203}
1204
Thiago Macieira2312efd2015-05-06 16:07:48 -07001205/**
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001206 * \fn CborError cbor_value_copy_text_string(const CborValue *value, char *buffer, size_t *buflen, CborValue *next)
1207 *
Thiago Macieira2312efd2015-05-06 16:07:48 -07001208 * Copies the string pointed by \a value into the buffer provided at \a buffer
1209 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
1210 * copy anything and will only update the \a next value.
1211 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001212 * If the iterator \a value does not point to a text string, the behaviour is
1213 * undefined, so checking with \ref cbor_value_get_type or \ref
1214 * cbor_value_is_text_string is recommended.
1215 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001216 * If the provided buffer length was too small, this function returns an error
1217 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
1218 * of the string in order to preallocate a buffer, use
Thiago Macieira2312efd2015-05-06 16:07:48 -07001219 * cbor_value_calculate_string_length().
1220 *
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001221 * On success, this function sets the number of bytes copied to \c{*buflen}. If
1222 * the buffer is large enough, this function will insert a null byte after the
1223 * last copied byte, to facilitate manipulation of text strings. That byte is
1224 * not included in the returned value of \c{*buflen}.
Thiago Macieira2312efd2015-05-06 16:07:48 -07001225 *
1226 * The \a next pointer, if not null, will be updated to point to the next item
1227 * after this string. If \a value points to the last item, then \a next will be
1228 * invalid.
1229 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001230 * This function may not run in constant time (it will run in O(n) time on the
1231 * number of chunks). It requires constant memory (O(1)).
1232 *
Thiago Macieira2312efd2015-05-06 16:07:48 -07001233 * \note This function does not perform UTF-8 validation on the incoming text
1234 * string.
1235 *
Thiago Macieira51b56062017-02-23 16:03:13 -08001236 * \sa cbor_value_get_text_string_chunk() cbor_value_dup_text_string(), cbor_value_copy_byte_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
Thiago Macieira2312efd2015-05-06 16:07:48 -07001237 */
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001238
1239/**
1240 * \fn CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer, size_t *buflen, CborValue *next)
1241 *
1242 * Copies the string pointed by \a value into the buffer provided at \a buffer
1243 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
1244 * copy anything and will only update the \a next value.
1245 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001246 * If the iterator \a value does not point to a byte string, the behaviour is
1247 * undefined, so checking with \ref cbor_value_get_type or \ref
1248 * cbor_value_is_byte_string is recommended.
1249 *
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001250 * If the provided buffer length was too small, this function returns an error
1251 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
1252 * of the string in order to preallocate a buffer, use
1253 * cbor_value_calculate_string_length().
1254 *
1255 * On success, this function sets the number of bytes copied to \c{*buflen}. If
1256 * the buffer is large enough, this function will insert a null byte after the
1257 * last copied byte, to facilitate manipulation of null-terminated strings.
1258 * That byte is not included in the returned value of \c{*buflen}.
1259 *
1260 * The \a next pointer, if not null, will be updated to point to the next item
1261 * after this string. If \a value points to the last item, then \a next will be
1262 * invalid.
1263 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001264 * This function may not run in constant time (it will run in O(n) time on the
1265 * number of chunks). It requires constant memory (O(1)).
1266 *
Thiago Macieira51b56062017-02-23 16:03:13 -08001267 * \sa cbor_value_get_byte_string_chunk(), cbor_value_dup_text_string(), cbor_value_copy_text_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
Thiago Macieiraff130bc2015-06-19 15:15:33 -07001268 */
1269
1270CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001271 size_t *buflen, CborValue *next)
Thiago Macieira2312efd2015-05-06 16:07:48 -07001272{
Thiago Macieira9ae05812015-05-11 15:09:09 +09001273 bool copied_all;
Thiago Macieiraed5b57c2015-07-07 16:38:27 -07001274 CborError err = iterate_string_chunks(value, (char*)buffer, buflen, &copied_all, next,
alradmsftacf202a2017-03-03 18:23:17 -08001275 buffer ? iterate_memcpy : iterate_noop);
Thiago Macieira9ae05812015-05-11 15:09:09 +09001276 return err ? err :
1277 copied_all ? CborNoError : CborErrorOutOfMemory;
Thiago Macieirac70169f2015-05-06 07:49:44 -07001278}
1279
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001280/**
1281 * Compares the entry \a value with the string \a string and store the result
Thiago Macieira46a818e2015-10-08 15:13:05 +02001282 * in \a result. If the value is different from \a string \a result will
1283 * contain \c false.
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001284 *
1285 * The entry at \a value may be a tagged string. If \a is not a string or a
1286 * tagged string, the comparison result will be false.
Thiago Macieira46a818e2015-10-08 15:13:05 +02001287 *
1288 * CBOR requires text strings to be encoded in UTF-8, but this function does
1289 * not validate either the strings in the stream or the string \a string to be
1290 * matched. Moreover, comparison is done on strict codepoint comparison,
1291 * without any Unicode normalization.
1292 *
1293 * This function may not run in constant time (it will run in O(n) time on the
1294 * number of chunks). It requires constant memory (O(1)).
1295 *
1296 * \sa cbor_value_skip_tag(), cbor_value_copy_text_string()
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001297 */
1298CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result)
1299{
1300 CborValue copy = *value;
1301 CborError err = cbor_value_skip_tag(&copy);
1302 if (err)
1303 return err;
1304 if (!cbor_value_is_text_string(&copy)) {
1305 *result = false;
1306 return CborNoError;
1307 }
1308
1309 size_t len = strlen(string);
1310 return iterate_string_chunks(&copy, CONST_CAST(char *, string), &len, result, NULL, iterate_memcmp);
1311}
1312
1313/**
Thiago Macieira46a818e2015-10-08 15:13:05 +02001314 * \fn bool cbor_value_is_array(const CborValue *value)
Thiago Macieira7b623c22015-05-11 15:52:14 +09001315 *
Thiago Macieira46a818e2015-10-08 15:13:05 +02001316 * Returns true if the iterator \a value is valid and points to a CBOR array.
1317 *
1318 * \sa cbor_value_is_valid(), cbor_value_is_map()
1319 */
1320
1321/**
1322 * \fn CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
1323 *
1324 * Extracts the length of the CBOR array that \a value points to and stores it
1325 * in \a result. If the iterator \a value does not point to a CBOR array, the
1326 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1327 * cbor_value_is_array is recommended.
1328 *
1329 * If the length of this array is not encoded in the CBOR data stream, this
1330 * function will return the recoverable error CborErrorUnknownLength. You may
1331 * also check whether that is the case by using cbor_value_is_length_known().
1332 *
1333 * \note On 32-bit platforms, this function will return error condition of \ref
1334 * CborErrorDataTooLarge if the stream indicates a length that is too big to
1335 * fit in 32-bit.
1336 *
1337 * \sa cbor_value_is_valid(), cbor_value_is_length_known()
1338 */
1339
1340/**
1341 * \fn bool cbor_value_is_map(const CborValue *value)
1342 *
1343 * Returns true if the iterator \a value is valid and points to a CBOR map.
1344 *
1345 * \sa cbor_value_is_valid(), cbor_value_is_array()
1346 */
1347
1348/**
1349 * \fn CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
1350 *
1351 * Extracts the length of the CBOR map that \a value points to and stores it in
1352 * \a result. If the iterator \a value does not point to a CBOR map, the
1353 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1354 * cbor_value_is_map is recommended.
1355 *
1356 * If the length of this map is not encoded in the CBOR data stream, this
1357 * function will return the recoverable error CborErrorUnknownLength. You may
1358 * also check whether that is the case by using cbor_value_is_length_known().
1359 *
1360 * \note On 32-bit platforms, this function will return error condition of \ref
1361 * CborErrorDataTooLarge if the stream indicates a length that is too big to
1362 * fit in 32-bit.
1363 *
1364 * \sa cbor_value_is_valid(), cbor_value_is_length_known()
1365 */
1366
1367/**
1368 * Attempts to find the value in map \a map that corresponds to the text string
1369 * entry \a string. If the iterator \a value does not point to a CBOR map, the
1370 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1371 * cbor_value_is_map is recommended.
1372 *
1373 * If the item is found, it is stored in \a result. If no item is found
1374 * matching the key, then \a result will contain an element of type \ref
1375 * CborInvalidType. Matching is performed using
1376 * cbor_value_text_string_equals(), so tagged strings will also match.
1377 *
1378 * This function has a time complexity of O(n) where n is the number of
1379 * elements in the map to be searched. In addition, this function is has O(n)
1380 * memory requirement based on the number of nested containers (maps or arrays)
1381 * found as elements of this map.
1382 *
1383 * \sa cbor_value_is_valid(), cbor_value_text_string_equals(), cbor_value_advance()
Thiago Macieira7b623c22015-05-11 15:52:14 +09001384 */
1385CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element)
1386{
Thiago Macieirada8e35e2017-03-05 09:58:01 +01001387 cbor_assert(cbor_value_is_map(map));
Thiago Macieira7b623c22015-05-11 15:52:14 +09001388 size_t len = strlen(string);
1389 CborError err = cbor_value_enter_container(map, element);
1390 if (err)
1391 goto error;
1392
1393 while (!cbor_value_at_end(element)) {
Thiago Macieiradbc01292016-06-06 17:02:25 -07001394 /* find the non-tag so we can compare */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001395 err = cbor_value_skip_tag(element);
1396 if (err)
1397 goto error;
1398 if (cbor_value_is_text_string(element)) {
1399 bool equals;
1400 size_t dummyLen = len;
1401 err = iterate_string_chunks(element, CONST_CAST(char *, string), &dummyLen,
1402 &equals, element, iterate_memcmp);
1403 if (err)
1404 goto error;
1405 if (equals)
1406 return preparse_value(element);
1407 } else {
Thiago Macieiradbc01292016-06-06 17:02:25 -07001408 /* skip this key */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001409 err = cbor_value_advance(element);
1410 if (err)
1411 goto error;
1412 }
1413
Thiago Macieiradbc01292016-06-06 17:02:25 -07001414 /* skip this value */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001415 err = cbor_value_skip_tag(element);
1416 if (err)
1417 goto error;
1418 err = cbor_value_advance(element);
1419 if (err)
1420 goto error;
1421 }
1422
Thiago Macieiradbc01292016-06-06 17:02:25 -07001423 /* not found */
Thiago Macieira7b623c22015-05-11 15:52:14 +09001424 element->type = CborInvalidType;
1425 return CborNoError;
1426
1427error:
1428 element->type = CborInvalidType;
1429 return err;
1430}
1431
1432/**
Thiago Macieira46a818e2015-10-08 15:13:05 +02001433 * \fn bool cbor_value_is_float(const CborValue *value)
1434 *
1435 * Returns true if the iterator \a value is valid and points to a CBOR
1436 * single-precision floating point (32-bit).
1437 *
1438 * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_half_float()
1439 */
1440
1441/**
1442 * \fn CborError cbor_value_get_float(const CborValue *value, float *result)
1443 *
1444 * Retrieves the CBOR single-precision floating point (32-bit) value that \a
1445 * value points to and stores it in \a result. If the iterator \a value does
1446 * not point to a single-precision floating point value, the behavior is
1447 * undefined, so checking with \ref cbor_value_get_type or with \ref
1448 * cbor_value_is_float is recommended.
1449 *
1450 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_float(), cbor_value_get_double()
1451 */
1452
1453/**
1454 * \fn bool cbor_value_is_double(const CborValue *value)
1455 *
1456 * Returns true if the iterator \a value is valid and points to a CBOR
1457 * double-precision floating point (64-bit).
1458 *
1459 * \sa cbor_value_is_valid(), cbor_value_is_float(), cbor_value_is_half_float()
1460 */
1461
1462/**
1463 * \fn CborError cbor_value_get_double(const CborValue *value, float *result)
1464 *
1465 * Retrieves the CBOR double-precision floating point (64-bit) value that \a
1466 * value points to and stores it in \a result. If the iterator \a value does
1467 * not point to a double-precision floating point value, the behavior is
1468 * undefined, so checking with \ref cbor_value_get_type or with \ref
1469 * cbor_value_is_double is recommended.
1470 *
1471 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_double(), cbor_value_get_float()
1472 */
1473
1474/**
1475 * \fn bool cbor_value_is_half_float(const CborValue *value)
1476 *
1477 * Returns true if the iterator \a value is valid and points to a CBOR
1478 * single-precision floating point (16-bit).
1479 *
1480 * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_float()
1481 */
1482
1483/**
1484 * Retrieves the CBOR half-precision floating point (16-bit) value that \a
1485 * value points to and stores it in \a result. If the iterator \a value does
1486 * not point to a half-precision floating point value, the behavior is
1487 * undefined, so checking with \ref cbor_value_get_type or with \ref
1488 * cbor_value_is_half_float is recommended.
1489 *
1490 * Note: since the C language does not have a standard type for half-precision
1491 * floating point, this function takes a \c{void *} as a parameter for the
1492 * storage area, which must be at least 16 bits wide.
1493 *
1494 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_half_float(), cbor_value_get_float()
Thiago Macieirac4a73c62015-05-09 18:14:11 -07001495 */
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001496CborError cbor_value_get_half_float(const CborValue *value, void *result)
Thiago Macieirac70169f2015-05-06 07:49:44 -07001497{
Thiago Macieirada8e35e2017-03-05 09:58:01 +01001498 cbor_assert(cbor_value_is_half_float(value));
Thiago Macieirac70169f2015-05-06 07:49:44 -07001499
Thiago Macieiradbc01292016-06-06 17:02:25 -07001500 /* size has been computed already */
Thiago Macieirac70169f2015-05-06 07:49:44 -07001501 uint16_t v = get16(value->ptr + 1);
1502 memcpy(result, &v, sizeof(v));
Thiago Macieiraa43a4ef2015-05-06 20:25:18 -07001503 return CborNoError;
Thiago Macieira54a0e102015-05-05 21:25:06 -07001504}
Thiago Macieira46a818e2015-10-08 15:13:05 +02001505
1506/** @} */