1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 Intel Corporation
4 **
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
25 #define _BSD_SOURCE 1
26 #define _DEFAULT_SOURCE 1
27 #ifndef __STDC_LIMIT_MACROS
28 # define __STDC_LIMIT_MACROS 1
29 #endif
30
31 #include "tinycbor/cbor.h"
32 #include "tinycbor/cborconstants_p.h"
33 #include "tinycbor/compilersupport_p.h"
34 #include "tinycbor/extract_number_p.h"
35
36 #include <assert.h>
37 #include <string.h>
38
39 #include <tinycbor/cbor_buf_reader.h>
40 #include "tinycbor/assert_p.h" /* Always include last */
41
42 #ifndef CBOR_PARSER_MAX_RECURSIONS
43 # define CBOR_PARSER_MAX_RECURSIONS 1024
44 #endif
45
46 /**
47 * \defgroup CborParsing Parsing CBOR streams
48 * \brief Group of functions used to parse CBOR streams.
49 *
50 * TinyCBOR provides functions for pull-based stream parsing of a CBOR-encoded
51 * payload. The main data type for the parsing is a CborValue, which behaves
52 * like an iterator and can be used to extract the encoded data. It is first
53 * initialized with a call to cbor_parser_init() and is usually used to extract
54 * exactly one item, most often an array or map.
55 *
56 * Nested CborValue objects can be parsed using cbor_value_enter_container().
57 * Each call to cbor_value_enter_container() must be matched by a call to
58 * cbor_value_leave_container(), with the exact same parameters.
59 *
60 * The example below initializes a CborParser object, begins the parsing with a
61 * CborValue and decodes a single integer:
62 *
63 * \code
64 * int extract_int(const uint8_t *buffer, size_t len)
65 * {
66 * CborParser parser;
67 * CborValue value;
68 * int result;
69 * cbor_parser_init(buffer, len, 0, &buffer, &value);
70 * cbor_value_get_int(&value, &result);
71 * return result;
72 * }
73 * \endcode
74 *
75 * The code above does no error checking, which means it assumes the data comes
76 * from a source trusted to send one properly-encoded integer. The following
77 * example does the exact same operation, but includes error parsing and
78 * returns 0 on parsing failure:
79 *
80 * \code
81 * int extract_int(const uint8_t *buffer, size_t len)
82 * {
83 * CborParser parser;
84 * CborValue value;
85 * int result;
86 * if (cbor_parser_init(buffer, len, 0, &buffer, &value) != CborNoError)
87 * return 0;
88 * if (!cbor_value_is_integer(&value) ||
89 * cbor_value_get_int(&value, &result) != CborNoError)
90 * return 0;
91 * return result;
92 * }
93 * \endcode
94 *
95 * Note, in the example above, that one can't distinguish a parsing failure
96 * from an encoded value of zero. Reporting a parsing error is left as an
97 * exercise to the reader.
98 *
99 * The code above does not execute a range-check either: it is possible that
100 * the value decoded from the CBOR stream encodes a number larger than what can
101 * be represented in a variable of type \c{int}. If detecting that case is
102 * important, the code should call cbor_value_get_int_checked() instead.
103 *
104 * <h3 class="groupheader">Memory and parsing constraints</h3>
105 *
106 * TinyCBOR is designed to run with little memory and with minimal overhead.
107 * Except where otherwise noted, the parser functions always run on constant
108 * time (O(1)), do not recurse and never allocate memory (thus, stack usage is
109 * bounded and is O(1)).
110 *
111 * <h3 class="groupheader">Error handling and preconditions</h3>
112 *
113 * All functions operating on a CborValue return a CborError condition, with
114 * CborNoError standing for the normal situation in which no parsing error
115 * occurred. All functions may return parsing errors in case the stream cannot
116 * be decoded properly, be it due to corrupted data or due to reaching the end
117 * of the input buffer.
118 *
119 * Error conditions must not be ignored. All decoder functions have undefined
120 * behavior if called after an error has been reported, and may crash.
121 *
122 * Some functions are also documented to have preconditions, like
123 * cbor_value_get_int() requiring that the input be an integral value.
124 * Violation of preconditions also results in undefined behavior and the
125 * program may crash.
126 */
127
128 /**
129 * \addtogroup CborParsing
130 * @{
131 */
132
133 /**
134 * \struct CborValue
135 *
136 * This type contains one value parsed from the CBOR stream. Each CborValue
137 * behaves as an iterator in a StAX-style parser.
138 *
139 * \if privatedocs
140 * Implementation details: the CborValue contains these fields:
141 * \list
142 * \li ptr: pointer to the actual data
143 * \li flags: flags from the decoder
144 * \li extra: partially decoded integer value (0, 1 or 2 bytes)
145 * \li remaining: remaining items in this collection after this item or UINT32_MAX if length is unknown
146 * \endlist
147 * \endif
148 */
149
extract_length(const CborParser * parser,int * offset,size_t * len)150 static CborError extract_length(const CborParser *parser,
151 int *offset, size_t *len)
152 {
153 uint64_t v;
154 CborError err = extract_number(parser, offset, &v);
155 if (err) {
156 *len = 0;
157 return err;
158 }
159
160 *len = v;
161 if (v != *len)
162 return CborErrorDataTooLarge;
163 return CborNoError;
164 }
165
is_fixed_type(uint8_t type)166 static bool is_fixed_type(uint8_t type)
167 {
168 return type != CborTextStringType && type != CborByteStringType && type != CborArrayType &&
169 type != CborMapType;
170 }
171
preparse_value(CborValue * it)172 static CborError preparse_value(CborValue *it)
173 {
174 const CborParser *parser = it->parser;
175 it->type = CborInvalidType;
176
177 /* are we at the end? */
178 if (it->offset == parser->end)
179 return CborErrorUnexpectedEOF;
180
181 uint8_t descriptor = parser->d->get8(parser->d, it->offset);
182 uint8_t type = descriptor & MajorTypeMask;
183 it->type = type;
184 it->flags = 0;
185 it->extra = (descriptor &= SmallValueMask);
186
187 if (descriptor > Value64Bit) {
188 if (unlikely(descriptor != IndefiniteLength))
189 return type == CborSimpleType ? CborErrorUnknownType : CborErrorIllegalNumber;
190 if (likely(!is_fixed_type(type))) {
191 /* special case */
192 it->flags |= CborIteratorFlag_UnknownLength;
193 it->type = type;
194 return CborNoError;
195 }
196 return type == CborSimpleType ? CborErrorUnexpectedBreak : CborErrorIllegalNumber;
197 }
198
199 size_t bytesNeeded = descriptor < Value8Bit ? 0 : (1 << (descriptor - Value8Bit));
200 if (bytesNeeded + 1 > (size_t)(parser->end - it->offset))
201 return CborErrorUnexpectedEOF;
202
203 uint8_t majortype = type >> MajorTypeShift;
204 if (majortype == NegativeIntegerType) {
205 it->flags |= CborIteratorFlag_NegativeInteger;
206 it->type = CborIntegerType;
207 } else if (majortype == SimpleTypesType) {
208 switch (descriptor) {
209 case FalseValue:
210 it->extra = false;
211 it->type = CborBooleanType;
212 break;
213
214 case SinglePrecisionFloat:
215 case DoublePrecisionFloat:
216 it->flags |= CborIteratorFlag_IntegerValueTooLarge;
217 /* fall through */
218 case TrueValue:
219 case NullValue:
220 case UndefinedValue:
221 case HalfPrecisionFloat:
222 it->type = parser->d->get8(parser->d, it->offset);
223 break;
224
225 case SimpleTypeInNextByte:
226 it->extra = parser->d->get8(parser->d, it->offset + 1);
227 #ifndef CBOR_PARSER_NO_STRICT_CHECKS
228 if (unlikely(it->extra < 32)) {
229 it->type = CborInvalidType;
230 return CborErrorIllegalSimpleType;
231 }
232 #endif
233 break;
234
235 case 28:
236 case 29:
237 case 30:
238 case Break:
239 assert(false); /* these conditions can't be reached */
240 return CborErrorUnexpectedBreak;
241 }
242 return CborNoError;
243 }
244
245 /* try to decode up to 16 bits */
246 if (descriptor < Value8Bit)
247 return CborNoError;
248
249 if (descriptor == Value8Bit)
250 it->extra = parser->d->get8(parser->d, it->offset + 1);
251 else if (descriptor == Value16Bit)
252 it->extra = parser->d->get16(parser->d, it->offset + 1);
253 else
254 it->flags |= CborIteratorFlag_IntegerValueTooLarge; /* Value32Bit or Value64Bit */
255 return CborNoError;
256 }
257
preparse_next_value(CborValue * it)258 static CborError preparse_next_value(CborValue *it)
259 {
260 if (it->remaining != UINT32_MAX) {
261 /* don't decrement the item count if the current item is tag: they don't count */
262 if (it->type != CborTagType && !--it->remaining) {
263 it->type = CborInvalidType;
264 return CborNoError;
265 }
266 } else if (it->remaining == UINT32_MAX && it->offset != it->parser->end &&
267 it->parser->d->get8(it->parser->d, it->offset) == (uint8_t)BreakByte) {
268 /* end of map or array */
269 ++it->offset;
270 it->type = CborInvalidType;
271 it->remaining = 0;
272 return CborNoError;
273 }
274
275 return preparse_value(it);
276 }
277
advance_internal(CborValue * it)278 static CborError advance_internal(CborValue *it)
279 {
280 uint64_t length;
281 CborError err = extract_number(it->parser, &it->offset, &length);
282 if (err != CborNoError) {
283 return err;
284 }
285
286 if (it->type == CborByteStringType || it->type == CborTextStringType) {
287 assert(length == (size_t)length);
288 assert((it->flags & CborIteratorFlag_UnknownLength) == 0);
289 it->offset += length;
290 }
291
292 return preparse_next_value(it);
293 }
294
295 /** \internal
296 *
297 * Decodes the CBOR integer value when it is larger than the 16 bits available
298 * in value->extra. This function requires that value->flags have the
299 * CborIteratorFlag_IntegerValueTooLarge flag set.
300 *
301 * This function is also used to extract single- and double-precision floating
302 * point values (SinglePrecisionFloat == Value32Bit and DoublePrecisionFloat ==
303 * Value64Bit).
304 */
_cbor_value_decode_int64_internal(const CborValue * value)305 uint64_t _cbor_value_decode_int64_internal(const CborValue *value)
306 {
307 uint8_t val = value->parser->d->get8(value->parser->d, value->offset);
308
309 assert(value->flags & CborIteratorFlag_IntegerValueTooLarge ||
310 value->type == CborFloatType || value->type == CborDoubleType);
311
312 /* since the additional information can only be Value32Bit or Value64Bit,
313 * we just need to test for the one bit those two options differ */
314 assert((val & SmallValueMask) == Value32Bit || (val & SmallValueMask) == Value64Bit);
315 if ((val & 1) == (Value32Bit & 1))
316 return value->parser->d->get32(value->parser->d, value->offset + 1);
317
318 assert((val & SmallValueMask) == Value64Bit);
319 return value->parser->d->get64(value->parser->d, value->offset + 1);
320 }
321
322 /**
323 * Initializes the CBOR parser for parsing \a size bytes beginning at \a
324 * buffer. Parsing will use flags set in \a flags. The iterator to the first
325 * element is returned in \a it.
326 *
327 * The \a parser structure needs to remain valid throughout the decoding
328 * process. It is not thread-safe to share one CborParser among multiple
329 * threads iterating at the same time, but the object can be copied so multiple
330 * threads can iterate.
331 */
cbor_parser_init(struct cbor_decoder_reader * d,int flags,CborParser * parser,CborValue * it)332 CborError cbor_parser_init(struct cbor_decoder_reader *d, int flags,
333 CborParser *parser, CborValue *it)
334 {
335 memset(parser, 0, sizeof(*parser));
336 parser->d = d;
337 parser->end = d->message_size;
338 parser->flags = flags;
339 it->parser = parser;
340 it->offset = 0;
341 it->remaining = 1;/* there's one type altogether, usually an array or map */
342 return preparse_value(it);
343 }
344
345 /**
346 * \fn bool cbor_value_at_end(const CborValue *it)
347 *
348 * Returns true if \a it has reached the end of the iteration, usually when
349 * advancing after the last item in an array or map.
350 *
351 * In the case of the outermost CborValue object, this function returns true
352 * after decoding a single element. A pointer to the first byte of the
353 * remaining data (if any) can be obtained with cbor_value_get_next_byte().
354 *
355 * \sa cbor_value_advance(), cbor_value_is_valid(), cbor_value_get_next_byte()
356 */
357
358 /**
359 * \fn const uint8_t *cbor_value_get_next_byte(const CborValue *it)
360 *
361 * Returns a pointer to the next byte that would be decoded if this CborValue
362 * object were advanced.
363 *
364 * This function is useful if cbor_value_at_end() returns true for the
365 * outermost CborValue: the pointer returned is the first byte of the data
366 * remaining in the buffer, if any. Code can decide whether to begin decoding a
367 * new CBOR data stream from this point, or parse some other data appended to
368 * the same buffer.
369 *
370 * This function may be used even after a parsing error. If that occurred,
371 * then this function returns a pointer to where the parsing error occurred.
372 * Note that the error recovery is not precise and the pointer may not indicate
373 * the exact byte containing bad data.
374 *
375 * \sa cbor_value_at_end()
376 */
377
378 /**
379 * \fn bool cbor_value_is_valid(const CborValue *it)
380 *
381 * Returns true if the iterator \a it contains a valid value. Invalid iterators
382 * happen when iteration reaches the end of a container (see \ref
383 * cbor_value_at_end()) or when a search function resulted in no matches.
384 *
385 * \sa cbor_value_advance(), cbor_valie_at_end(), cbor_value_get_type()
386 */
387
388 /**
389 * Advances the CBOR value \a it by one fixed-size position. Fixed-size types
390 * are: integers, tags, simple types (including boolean, null and undefined
391 * values) and floating point types.
392 *
393 * If the type is not of fixed size, this function has undefined behavior. Code
394 * must be sure that the current type is one of the fixed-size types before
395 * calling this function. This function is provided because it can guarantee
396 * that runs in constant time (O(1)).
397 *
398 * If the caller is not able to determine whether the type is fixed or not, code
399 * can use the cbor_value_advance() function instead.
400 *
401 * \sa cbor_value_at_end(), cbor_value_advance(), cbor_value_enter_container(), cbor_value_leave_container()
402 */
cbor_value_advance_fixed(CborValue * it)403 CborError cbor_value_advance_fixed(CborValue *it)
404 {
405 assert(it->type != CborInvalidType);
406 assert(is_fixed_type(it->type));
407 if (!it->remaining)
408 return CborErrorAdvancePastEOF;
409 return advance_internal(it);
410 }
411
advance_recursive(CborValue * it,int nestingLevel)412 static CborError advance_recursive(CborValue *it, int nestingLevel)
413 {
414 if (is_fixed_type(it->type))
415 return advance_internal(it);
416
417 if (!cbor_value_is_container(it)) {
418 size_t len = SIZE_MAX;
419 return _cbor_value_copy_string(it, NULL, &len, it);
420 }
421
422 /* map or array */
423 if (nestingLevel == CBOR_PARSER_MAX_RECURSIONS)
424 return CborErrorNestingTooDeep;
425
426 CborError err;
427 CborValue recursed;
428 err = cbor_value_enter_container(it, &recursed);
429 if (err)
430 return err;
431 while (!cbor_value_at_end(&recursed)) {
432 err = advance_recursive(&recursed, nestingLevel + 1);
433 if (err)
434 return err;
435 }
436 return cbor_value_leave_container(it, &recursed);
437 }
438
439
440 /**
441 * Advances the CBOR value \a it by one element, skipping over containers.
442 * Unlike cbor_value_advance_fixed(), this function can be called on a CBOR
443 * value of any type. However, if the type is a container (map or array) or a
444 * string with a chunked payload, this function will not run in constant time
445 * and will recurse into itself (it will run on O(n) time for the number of
446 * elements or chunks and will use O(n) memory for the number of nested
447 * containers).
448 *
449 * \sa cbor_value_at_end(), cbor_value_advance_fixed(), cbor_value_enter_container(), cbor_value_leave_container()
450 */
cbor_value_advance(CborValue * it)451 CborError cbor_value_advance(CborValue *it)
452 {
453 assert(it->type != CborInvalidType);
454 if (!it->remaining)
455 return CborErrorAdvancePastEOF;
456 return advance_recursive(it, 0);
457 }
458
459 /**
460 * \fn bool cbor_value_is_tag(const CborValue *value)
461 *
462 * Returns true if the iterator \a value is valid and points to a CBOR tag.
463 *
464 * \sa cbor_value_get_tag(), cbor_value_skip_tag()
465 */
466
467 /**
468 * \fn CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
469 *
470 * Retrieves the CBOR tag value that \a value points to and stores it in \a
471 * result. If the iterator \a value does not point to a CBOR tag value, the
472 * behavior is undefined, so checking with \ref cbor_value_get_type or with
473 * \ref cbor_value_is_tag is recommended.
474 *
475 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_tag()
476 */
477
478 /**
479 * Advances the CBOR value \a it until it no longer points to a tag. If \a it is
480 * already not pointing to a tag, then this function returns it unchanged.
481 *
482 * This function does not run in constant time: it will run on O(n) for n being
483 * the number of tags. It does use constant memory (O(1) memory requirements).
484 *
485 * \sa cbor_value_advance_fixed(), cbor_value_advance()
486 */
cbor_value_skip_tag(CborValue * it)487 CborError cbor_value_skip_tag(CborValue *it)
488 {
489 while (cbor_value_is_tag(it)) {
490 CborError err = cbor_value_advance_fixed(it);
491 if (err)
492 return err;
493 }
494 return CborNoError;
495 }
496
497 /**
498 * \fn bool cbor_value_is_container(const CborValue *it)
499 *
500 * Returns true if the \a it value is a container and requires recursion in
501 * order to decode (maps and arrays), false otherwise.
502 */
503
504 /**
505 * Creates a CborValue iterator pointing to the first element of the container
506 * represented by \a it and saves it in \a recursed. The \a it container object
507 * needs to be kept and passed again to cbor_value_leave_container() in order
508 * to continue iterating past this container.
509 *
510 * The \a it CborValue iterator must point to a container.
511 *
512 * \sa cbor_value_is_container(), cbor_value_leave_container(), cbor_value_advance()
513 */
cbor_value_enter_container(const CborValue * it,CborValue * recursed)514 CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed)
515 {
516 CborError err;
517 assert(cbor_value_is_container(it));
518 *recursed = *it;
519
520 if (it->flags & CborIteratorFlag_UnknownLength) {
521 recursed->remaining = UINT32_MAX;
522 ++recursed->offset;
523 err = preparse_value(recursed);
524 if (err != CborErrorUnexpectedBreak)
525 return err;
526 /* actually, break was expected here
527 * it's just an empty container */
528 ++recursed->offset;
529 } else {
530 uint64_t len;
531 err = extract_number(recursed->parser, &recursed->offset, &len);
532 assert(err == CborNoError);
533
534 recursed->remaining = (uint32_t)len;
535 if (recursed->remaining != len || len == UINT32_MAX) {
536 /* back track the pointer to indicate where the error occurred */
537 recursed->offset = it->offset;
538 return CborErrorDataTooLarge;
539 }
540 if (recursed->type == CborMapType) {
541 /* maps have keys and values, so we need to multiply by 2 */
542 if (recursed->remaining > UINT32_MAX / 2) {
543 /* back track the pointer to indicate where the error occurred */
544 recursed->offset = it->offset;
545 return CborErrorDataTooLarge;
546 }
547 recursed->remaining *= 2;
548 }
549 if (len != 0)
550 return preparse_value(recursed);
551 }
552
553 /* the case of the empty container */
554 recursed->type = CborInvalidType;
555 recursed->remaining = 0;
556 return CborNoError;
557 }
558
559 /**
560 * Updates \a it to point to the next element after the container. The \a
561 * recursed object needs to point to the element obtained either by advancing
562 * the last element of the container (via cbor_value_advance(),
563 * cbor_value_advance_fixed(), a nested cbor_value_leave_container(), or the \c
564 * next pointer from cbor_value_copy_string() or cbor_value_dup_string()).
565 *
566 * The \a it and \a recursed parameters must be the exact same as passed to
567 * cbor_value_enter_container().
568 *
569 * \sa cbor_value_enter_container(), cbor_value_at_end()
570 */
cbor_value_leave_container(CborValue * it,const CborValue * recursed)571 CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed)
572 {
573 assert(cbor_value_is_container(it));
574 assert(recursed->type == CborInvalidType);
575 it->offset = recursed->offset;
576 return preparse_next_value(it);
577 }
578
579
580 /**
581 * \fn CborType cbor_value_get_type(const CborValue *value)
582 *
583 * Returns the type of the CBOR value that the iterator \a value points to. If
584 * \a value does not point to a valid value, this function returns \ref
585 * CborInvalidType.
586 *
587 * TinyCBOR also provides functions to test directly if a given CborValue object
588 * is of a given type, like cbor_value_is_text_string() and cbor_value_is_null().
589 *
590 * \sa cbor_value_is_valid()
591 */
592
593 /**
594 * \fn bool cbor_value_is_null(const CborValue *value)
595 *
596 * Returns true if the iterator \a value is valid and points to a CBOR null type.
597 *
598 * \sa cbor_value_is_valid(), cbor_value_is_undefined()
599 */
600
601 /**
602 * \fn bool cbor_value_is_undefined(const CborValue *value)
603 *
604 * Returns true if the iterator \a value is valid and points to a CBOR undefined type.
605 *
606 * \sa cbor_value_is_valid(), cbor_value_is_null()
607 */
608
609 /**
610 * \fn bool cbor_value_is_boolean(const CborValue *value)
611 *
612 * Returns true if the iterator \a value is valid and points to a CBOR boolean
613 * type (true or false).
614 *
615 * \sa cbor_value_is_valid(), cbor_value_get_boolean()
616 */
617
618 /**
619 * \fn CborError cbor_value_get_boolean(const CborValue *value, bool *result)
620 *
621 * Retrieves the boolean value that \a value points to and stores it in \a
622 * result. If the iterator \a value does not point to a boolean value, the
623 * behavior is undefined, so checking with \ref cbor_value_get_type or with
624 * \ref cbor_value_is_boolean is recommended.
625 *
626 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_boolean()
627 */
628
629 /**
630 * \fn bool cbor_value_is_simple_type(const CborValue *value)
631 *
632 * Returns true if the iterator \a value is valid and points to a CBOR Simple Type
633 * type (other than true, false, null and undefined).
634 *
635 * \sa cbor_value_is_valid(), cbor_value_get_simple_type()
636 */
637
638 /**
639 * \fn CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
640 *
641 * Retrieves the CBOR Simple Type value that \a value points to and stores it
642 * in \a result. If the iterator \a value does not point to a simple_type
643 * value, the behavior is undefined, so checking with \ref cbor_value_get_type
644 * or with \ref cbor_value_is_simple_type is recommended.
645 *
646 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_simple_type()
647 */
648
649 /**
650 * \fn bool cbor_value_is_integer(const CborValue *value)
651 *
652 * Returns true if the iterator \a value is valid and points to a CBOR integer
653 * type.
654 *
655 * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_uint64, cbor_value_get_raw_integer
656 */
657
658 /**
659 * \fn bool cbor_value_is_unsigned_integer(const CborValue *value)
660 *
661 * Returns true if the iterator \a value is valid and points to a CBOR unsigned
662 * integer type (positive values or zero).
663 *
664 * \sa cbor_value_is_valid(), cbor_value_get_uint64()
665 */
666
667 /**
668 * \fn bool cbor_value_is_negative_integer(const CborValue *value)
669 *
670 * Returns true if the iterator \a value is valid and points to a CBOR negative
671 * integer type.
672 *
673 * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_raw_integer
674 */
675
676 /**
677 * \fn CborError cbor_value_get_int(const CborValue *value, int *result)
678 *
679 * Retrieves the CBOR integer value that \a value points to and stores it in \a
680 * result. If the iterator \a value does not point to an integer value, the
681 * behavior is undefined, so checking with \ref cbor_value_get_type or with
682 * \ref cbor_value_is_integer is recommended.
683 *
684 * Note that this function does not do range-checking: integral values that do
685 * not fit in a variable of type \c{int} are silently truncated to fit. Use
686 * cbor_value_get_int_checked() that is not acceptable.
687 *
688 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
689 */
690
691 /**
692 * \fn CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
693 *
694 * Retrieves the CBOR integer value that \a value points to and stores it in \a
695 * result. If the iterator \a value does not point to an integer value, the
696 * behavior is undefined, so checking with \ref cbor_value_get_type or with
697 * \ref cbor_value_is_integer is recommended.
698 *
699 * Note that this function does not do range-checking: integral values that do
700 * not fit in a variable of type \c{int64_t} are silently truncated to fit. Use
701 * cbor_value_get_int64_checked() that is not acceptable.
702 *
703 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
704 */
705
706 /**
707 * \fn CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
708 *
709 * Retrieves the CBOR integer value that \a value points to and stores it in \a
710 * result. If the iterator \a value does not point to an unsigned integer
711 * value, the behavior is undefined, so checking with \ref cbor_value_get_type
712 * or with \ref cbor_value_is_unsigned_integer is recommended.
713 *
714 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_unsigned_integer()
715 */
716
717 /**
718 * \fn CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
719 *
720 * Retrieves the CBOR integer value that \a value points to and stores it in \a
721 * result. If the iterator \a value does not point to an integer value, the
722 * behavior is undefined, so checking with \ref cbor_value_get_type or with
723 * \ref cbor_value_is_integer is recommended.
724 *
725 * This function is provided because CBOR negative integers can assume values
726 * that cannot be represented with normal 64-bit integer variables.
727 *
728 * If the integer is unsigned (that is, if cbor_value_is_unsigned_integer()
729 * returns true), then \a result will contain the actual value. If the integer
730 * is negative, then \a result will contain the absolute value of that integer,
731 * minus one. That is, \c {actual = -result - 1}. On architectures using two's
732 * complement for representation of negative integers, it is equivalent to say
733 * that \a result will contain the bitwise negation of the actual value.
734 *
735 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
736 */
737
738 /**
739 * Retrieves the CBOR integer value that \a value points to and stores it in \a
740 * result. If the iterator \a value does not point to an integer value, the
741 * behavior is undefined, so checking with \ref cbor_value_get_type or with
742 * \ref cbor_value_is_integer is recommended.
743 *
744 * Unlike cbor_value_get_int64(), this function performs a check to see if the
745 * stored integer fits in \a result without data loss. If the number is outside
746 * the valid range for the data type, this function returns the recoverable
747 * error CborErrorDataTooLarge. In that case, use either
748 * cbor_value_get_uint64() (if the number is positive) or
749 * cbor_value_get_raw_integer().
750 *
751 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64()
752 */
cbor_value_get_int64_checked(const CborValue * value,int64_t * result)753 CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result)
754 {
755 assert(cbor_value_is_integer(value));
756 uint64_t v = _cbor_value_extract_int64_helper(value);
757
758 /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
759 * "[if] the new type is signed and the value cannot be represented in it; either the
760 * result is implementation-defined or an implementation-defined signal is raised."
761 *
762 * The range for int64_t is -2^63 to 2^63-1 (int64_t is required to be
763 * two's complement, C11 7.20.1.1 paragraph 3), which in CBOR is
764 * represented the same way, differing only on the "sign bit" (the major
765 * type).
766 */
767
768 if (unlikely(v > (uint64_t)INT64_MAX))
769 return CborErrorDataTooLarge;
770
771 *result = v;
772 if (value->flags & CborIteratorFlag_NegativeInteger)
773 *result = -*result - 1;
774 return CborNoError;
775 }
776
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 integer value, the
780 * behavior is undefined, so checking with \ref cbor_value_get_type or with
781 * \ref cbor_value_is_integer is recommended.
782 *
783 * Unlike cbor_value_get_int(), this function performs a check to see if the
784 * stored integer fits in \a result without data loss. If the number is outside
785 * the valid range for the data type, this function returns the recoverable
786 * error CborErrorDataTooLarge. In that case, use one of the other integer
787 * functions to obtain the value.
788 *
789 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64(),
790 * cbor_value_get_uint64(), cbor_value_get_int64_checked(), cbor_value_get_raw_integer()
791 */
cbor_value_get_int_checked(const CborValue * value,int * result)792 CborError cbor_value_get_int_checked(const CborValue *value, int *result)
793 {
794 assert(cbor_value_is_integer(value));
795 uint64_t v = _cbor_value_extract_int64_helper(value);
796
797 /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
798 * "[if] the new type is signed and the value cannot be represented in it; either the
799 * result is implementation-defined or an implementation-defined signal is raised."
800 *
801 * But we can convert from signed to unsigned without fault (paragraph 2).
802 *
803 * The range for int is implementation-defined and int is not guaranteed use
804 * two's complement representation (int32_t is).
805 */
806
807 if (value->flags & CborIteratorFlag_NegativeInteger) {
808 if (unlikely(v > (unsigned) -(INT_MIN + 1)))
809 return CborErrorDataTooLarge;
810
811 *result = v;
812 *result = -*result - 1;
813 } else {
814 if (unlikely(v > (uint64_t)INT_MAX))
815 return CborErrorDataTooLarge;
816
817 *result = v;
818 }
819 return CborNoError;
820
821 }
822
823 /**
824 * \fn bool cbor_value_is_length_known(const CborValue *value)
825 *
826 * Returns true if the length of this type is known without calculation. That
827 * is, if the length of this CBOR string, map or array is encoded in the data
828 * stream, this function returns true. If the length is not encoded, it returns
829 * false.
830 *
831 * If the length is known, code can call cbor_value_get_string_length(),
832 * cbor_value_get_array_length() or cbor_value_get_map_length() to obtain the
833 * length. If the length is not known but is necessary, code can use the
834 * cbor_value_calculate_string_length() function (no equivalent function is
835 * provided for maps and arrays).
836 */
837
838 /**
839 * \fn bool cbor_value_is_text_string(const CborValue *value)
840 *
841 * Returns true if the iterator \a value is valid and points to a CBOR text
842 * string. CBOR text strings are UTF-8 encoded and usually contain
843 * human-readable text.
844 *
845 * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
846 * cbor_value_copy_text_string(), cbor_value_dup_text_string()
847 */
848
849 /**
850 * \fn bool cbor_value_is_byte_string(const CborValue *value)
851 *
852 * Returns true if the iterator \a value is valid and points to a CBOR text
853 * string. CBOR byte strings are binary data with no specified encoding or
854 * format.
855 *
856 * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
857 * cbor_value_copy_byte_string(), cbor_value_dup_byte_string()
858 */
859
860 /**
861 * \fn CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
862 *
863 * Extracts the length of the byte or text string that \a value points to and
864 * stores it in \a result. If the iterator \a value does not point to a text
865 * string or a byte string, the behaviour is undefined, so checking with \ref
866 * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
867 * cbor_value_is_byte_string is recommended.
868 *
869 * If the length of this string is not encoded in the CBOR data stream, this
870 * function will return the recoverable error CborErrorUnknownLength. You may
871 * also check whether that is the case by using cbor_value_is_length_known().
872 *
873 * If the length of the string is required but the length was not encoded, use
874 * cbor_value_calculate_string_length(), but note that that function does not
875 * run in constant time.
876 *
877 * \note On 32-bit platforms, this function will return error condition of \ref
878 * CborErrorDataTooLarge if the stream indicates a length that is too big to
879 * fit in 32-bit.
880 *
881 * \sa cbor_value_is_valid(), cbor_value_is_length_known(), cbor_value_calculate_string_length()
882 */
883
884 /**
885 * Calculates the length of the byte or text string that \a value points to and
886 * stores it in \a len. If the iterator \a value does not point to a text
887 * string or a byte string, the behaviour is undefined, so checking with \ref
888 * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
889 * cbor_value_is_byte_string is recommended.
890 *
891 * This function is different from cbor_value_get_string_length() in that it
892 * calculates the length even for strings sent in chunks. For that reason, this
893 * function may not run in constant time (it will run in O(n) time on the
894 * number of chunks). It does use constant memory (O(1)).
895 *
896 * \note On 32-bit platforms, this function will return error condition of \ref
897 * CborErrorDataTooLarge if the stream indicates a length that is too big to
898 * fit in 32-bit.
899 *
900 * \sa cbor_value_get_string_length(), cbor_value_copy_string(), cbor_value_is_length_known()
901 */
cbor_value_calculate_string_length(const CborValue * value,size_t * len)902 CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len)
903 {
904 *len = SIZE_MAX;
905 return _cbor_value_copy_string(value, NULL, len, NULL);
906 }
907
908 /* We return uintptr_t so that we can pass memcpy directly as the iteration
909 * function. The choice is to optimize for memcpy, which is used in the base
910 * parser API (cbor_value_copy_string), while memcmp is used in convenience API
911 * only. */
912 typedef uintptr_t (*IterateFunction)(struct cbor_decoder_reader *d, char *dst, int src_offset, size_t len);
913
iterate_noop(struct cbor_decoder_reader * d,char * dst,int src_offset,size_t len)914 static uintptr_t iterate_noop(struct cbor_decoder_reader *d, char *dst, int src_offset, size_t len)
915 {
916 (void)d;
917 (void)dst;
918 (void)src_offset;
919 (void)len;
920 return true;
921 }
922
iterate_string_chunks(const CborValue * value,char * buffer,size_t * buflen,bool * result,CborValue * next,IterateFunction func)923 static CborError iterate_string_chunks(const CborValue *value, char *buffer, size_t *buflen,
924 bool *result, CborValue *next, IterateFunction func)
925 {
926 assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
927
928 size_t total;
929 CborError err;
930 int offset = value->offset;
931 if (cbor_value_is_length_known(value)) {
932 /* easy case: fixed length */
933 err = extract_length(value->parser, &offset, &total);
934 if (err)
935 return err;
936 if (total > (size_t)(value->parser->end - offset))
937 return CborErrorUnexpectedEOF;
938 if (total <= *buflen)
939 *result = !!func(value->parser->d, buffer, offset, total);
940 else
941 *result = false;
942 offset += total;
943 } else {
944 /* chunked */
945 ++offset;
946 total = 0;
947 *result = true;
948 while (true) {
949 uint8_t val;
950 size_t chunkLen;
951 size_t newTotal;
952
953 if (offset == value->parser->end)
954 return CborErrorUnexpectedEOF;
955
956 val = value->parser->d->get8(value->parser->d, offset);
957
958 if (val == (uint8_t)BreakByte) {
959 ++offset;
960 break;
961 }
962
963 /* is this the right type? */
964 if ((val & MajorTypeMask) != value->type)
965 return CborErrorIllegalType;
966
967 err = extract_length(value->parser, &offset, &chunkLen);
968 if (err)
969 return err;
970
971 if (unlikely(add_check_overflow(total, chunkLen, &newTotal)))
972 return CborErrorDataTooLarge;
973
974 if (chunkLen > (size_t)(value->parser->end - offset))
975 return CborErrorUnexpectedEOF;
976
977 if (*result && *buflen >= newTotal)
978 *result = !!func(value->parser->d, buffer + total, offset, chunkLen);
979 else
980 *result = false;
981
982 offset += chunkLen;
983 total = newTotal;
984 }
985 }
986
987 /* is there enough room for the ending NUL byte? */
988 if (*result && *buflen > total) {
989 /* we are just trying to write a NULL byte here,, but this is hard
990 * because this is called by function pointer with an abstract
991 * reader. Since this is the output buffer, we can assume that if
992 * we have a valid buffer its ok to write a NULL here */
993 if(buffer) {
994 *(buffer + total) = '\0';
995 }
996 }
997 *buflen = total;
998
999 if (next) {
1000 *next = *value;
1001 next->offset = offset;
1002 return preparse_next_value(next);
1003 }
1004 return CborNoError;
1005 }
1006
1007 /**
1008 * \fn CborError cbor_value_copy_text_string(const CborValue *value, char *buffer, size_t *buflen, CborValue *next)
1009 *
1010 * Copies the string pointed by \a value into the buffer provided at \a buffer
1011 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
1012 * copy anything and will only update the \a next value.
1013 *
1014 * If the iterator \a value does not point to a text string, the behaviour is
1015 * undefined, so checking with \ref cbor_value_get_type or \ref
1016 * cbor_value_is_text_string is recommended.
1017 *
1018 * If the provided buffer length was too small, this function returns an error
1019 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
1020 * of the string in order to preallocate a buffer, use
1021 * cbor_value_calculate_string_length().
1022 *
1023 * On success, this function sets the number of bytes copied to \c{*buflen}. If
1024 * the buffer is large enough, this function will insert a null byte after the
1025 * last copied byte, to facilitate manipulation of text strings. That byte is
1026 * not included in the returned value of \c{*buflen}.
1027 *
1028 * The \a next pointer, if not null, will be updated to point to the next item
1029 * after this string. If \a value points to the last item, then \a next will be
1030 * invalid.
1031 *
1032 * This function may not run in constant time (it will run in O(n) time on the
1033 * number of chunks). It requires constant memory (O(1)).
1034 *
1035 * \note This function does not perform UTF-8 validation on the incoming text
1036 * string.
1037 *
1038 * \sa cbor_value_dup_text_string(), cbor_value_copy_byte_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
1039 */
1040
1041 /**
1042 * \fn CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer, size_t *buflen, CborValue *next)
1043 *
1044 * Copies the string pointed by \a value into the buffer provided at \a buffer
1045 * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
1046 * copy anything and will only update the \a next value.
1047 *
1048 * If the iterator \a value does not point to a byte string, the behaviour is
1049 * undefined, so checking with \ref cbor_value_get_type or \ref
1050 * cbor_value_is_byte_string is recommended.
1051 *
1052 * If the provided buffer length was too small, this function returns an error
1053 * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
1054 * of the string in order to preallocate a buffer, use
1055 * cbor_value_calculate_string_length().
1056 *
1057 * On success, this function sets the number of bytes copied to \c{*buflen}. If
1058 * the buffer is large enough, this function will insert a null byte after the
1059 * last copied byte, to facilitate manipulation of null-terminated strings.
1060 * That byte is not included in the returned value of \c{*buflen}.
1061 *
1062 * The \a next pointer, if not null, will be updated to point to the next item
1063 * after this string. If \a value points to the last item, then \a next will be
1064 * invalid.
1065 *
1066 * This function may not run in constant time (it will run in O(n) time on the
1067 * number of chunks). It requires constant memory (O(1)).
1068 *
1069 * \sa cbor_value_dup_text_string(), cbor_value_copy_text_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
1070 */
1071
_cbor_value_copy_string(const CborValue * value,void * buffer,size_t * buflen,CborValue * next)1072 CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
1073 size_t *buflen, CborValue *next)
1074 {
1075 bool copied_all;
1076 CborError err = iterate_string_chunks(value, (char*)buffer, buflen, &copied_all, next,
1077 buffer ? (IterateFunction) value->parser->d->cpy : iterate_noop);
1078 return err ? err :
1079 copied_all ? CborNoError : CborErrorOutOfMemory;
1080 }
1081
1082 /**
1083 * Compares the entry \a value with the string \a string and store the result
1084 * in \a result. If the value is different from \a string \a result will
1085 * contain \c false.
1086 *
1087 * The entry at \a value may be a tagged string. If \a is not a string or a
1088 * tagged string, the comparison result will be false.
1089 *
1090 * CBOR requires text strings to be encoded in UTF-8, but this function does
1091 * not validate either the strings in the stream or the string \a string to be
1092 * matched. Moreover, comparison is done on strict codepoint comparison,
1093 * without any Unicode normalization.
1094 *
1095 * This function may not run in constant time (it will run in O(n) time on the
1096 * number of chunks). It requires constant memory (O(1)).
1097 *
1098 * \sa cbor_value_skip_tag(), cbor_value_copy_text_string()
1099 */
cbor_value_text_string_equals(const CborValue * value,const char * string,bool * result)1100 CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result)
1101 {
1102 CborValue copy = *value;
1103 CborError err = cbor_value_skip_tag(©);
1104 if (err)
1105 return err;
1106 if (!cbor_value_is_text_string(©)) {
1107 *result = false;
1108 return CborNoError;
1109 }
1110
1111 size_t len = strlen(string);
1112 return iterate_string_chunks(©, CONST_CAST(char *, string), &len,
1113 result, NULL, value->parser->d->cmp);
1114 }
1115
1116 /**
1117 * \fn bool cbor_value_is_array(const CborValue *value)
1118 *
1119 * Returns true if the iterator \a value is valid and points to a CBOR array.
1120 *
1121 * \sa cbor_value_is_valid(), cbor_value_is_map()
1122 */
1123
1124 /**
1125 * \fn CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
1126 *
1127 * Extracts the length of the CBOR array that \a value points to and stores it
1128 * in \a result. If the iterator \a value does not point to a CBOR array, the
1129 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1130 * cbor_value_is_array is recommended.
1131 *
1132 * If the length of this array is not encoded in the CBOR data stream, this
1133 * function will return the recoverable error CborErrorUnknownLength. You may
1134 * also check whether that is the case by using cbor_value_is_length_known().
1135 *
1136 * \note On 32-bit platforms, this function will return error condition of \ref
1137 * CborErrorDataTooLarge if the stream indicates a length that is too big to
1138 * fit in 32-bit.
1139 *
1140 * \sa cbor_value_is_valid(), cbor_value_is_length_known()
1141 */
1142
1143 /**
1144 * \fn bool cbor_value_is_map(const CborValue *value)
1145 *
1146 * Returns true if the iterator \a value is valid and points to a CBOR map.
1147 *
1148 * \sa cbor_value_is_valid(), cbor_value_is_array()
1149 */
1150
1151 /**
1152 * \fn CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
1153 *
1154 * Extracts the length of the CBOR map that \a value points to and stores it in
1155 * \a result. If the iterator \a value does not point to a CBOR map, the
1156 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1157 * cbor_value_is_map is recommended.
1158 *
1159 * If the length of this map is not encoded in the CBOR data stream, this
1160 * function will return the recoverable error CborErrorUnknownLength. You may
1161 * also check whether that is the case by using cbor_value_is_length_known().
1162 *
1163 * \note On 32-bit platforms, this function will return error condition of \ref
1164 * CborErrorDataTooLarge if the stream indicates a length that is too big to
1165 * fit in 32-bit.
1166 *
1167 * \sa cbor_value_is_valid(), cbor_value_is_length_known()
1168 */
1169
1170 /**
1171 * Attempts to find the value in map \a map that corresponds to the text string
1172 * entry \a string. If the iterator \a value does not point to a CBOR map, the
1173 * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
1174 * cbor_value_is_map is recommended.
1175 *
1176 * If the item is found, it is stored in \a result. If no item is found
1177 * matching the key, then \a result will contain an element of type \ref
1178 * CborInvalidType. Matching is performed using
1179 * cbor_value_text_string_equals(), so tagged strings will also match.
1180 *
1181 * This function has a time complexity of O(n) where n is the number of
1182 * elements in the map to be searched. In addition, this function is has O(n)
1183 * memory requirement based on the number of nested containers (maps or arrays)
1184 * found as elements of this map.
1185 *
1186 * \sa cbor_value_is_valid(), cbor_value_text_string_equals(), cbor_value_advance()
1187 */
cbor_value_map_find_value(const CborValue * map,const char * string,CborValue * element)1188 CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element)
1189 {
1190 assert(cbor_value_is_map(map));
1191 size_t len = strlen(string);
1192 CborError err = cbor_value_enter_container(map, element);
1193 if (err)
1194 goto error;
1195
1196 while (!cbor_value_at_end(element)) {
1197 /* find the non-tag so we can compare */
1198 err = cbor_value_skip_tag(element);
1199 if (err)
1200 goto error;
1201 if (cbor_value_is_text_string(element)) {
1202 bool equals;
1203 size_t dummyLen = len;
1204 err = iterate_string_chunks(element, CONST_CAST(char *, string), &dummyLen,
1205 &equals, element, map->parser->d->cmp);
1206 if (err)
1207 goto error;
1208 if (equals && string[dummyLen] == '\0')
1209 return preparse_value(element);
1210 } else {
1211 /* skip this key */
1212 err = cbor_value_advance(element);
1213 if (err)
1214 goto error;
1215 }
1216
1217 /* skip this value */
1218 err = cbor_value_skip_tag(element);
1219 if (err)
1220 goto error;
1221 err = cbor_value_advance(element);
1222 if (err)
1223 goto error;
1224 }
1225
1226 /* not found */
1227 element->type = CborInvalidType;
1228 return CborNoError;
1229
1230 error:
1231 element->type = CborInvalidType;
1232 return err;
1233 }
1234
1235 /**
1236 * \fn bool cbor_value_is_float(const CborValue *value)
1237 *
1238 * Returns true if the iterator \a value is valid and points to a CBOR
1239 * single-precision floating point (32-bit).
1240 *
1241 * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_half_float()
1242 */
1243
1244 /**
1245 * \fn CborError cbor_value_get_float(const CborValue *value, float *result)
1246 *
1247 * Retrieves the CBOR single-precision floating point (32-bit) value that \a
1248 * value points to and stores it in \a result. If the iterator \a value does
1249 * not point to a single-precision floating point value, the behavior is
1250 * undefined, so checking with \ref cbor_value_get_type or with \ref
1251 * cbor_value_is_float is recommended.
1252 *
1253 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_float(), cbor_value_get_double()
1254 */
1255
1256 /**
1257 * \fn bool cbor_value_is_double(const CborValue *value)
1258 *
1259 * Returns true if the iterator \a value is valid and points to a CBOR
1260 * double-precision floating point (64-bit).
1261 *
1262 * \sa cbor_value_is_valid(), cbor_value_is_float(), cbor_value_is_half_float()
1263 */
1264
1265 /**
1266 * \fn CborError cbor_value_get_double(const CborValue *value, float *result)
1267 *
1268 * Retrieves the CBOR double-precision floating point (64-bit) value that \a
1269 * value points to and stores it in \a result. If the iterator \a value does
1270 * not point to a double-precision floating point value, the behavior is
1271 * undefined, so checking with \ref cbor_value_get_type or with \ref
1272 * cbor_value_is_double is recommended.
1273 *
1274 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_double(), cbor_value_get_float()
1275 */
1276
1277 /**
1278 * \fn bool cbor_value_is_half_float(const CborValue *value)
1279 *
1280 * Returns true if the iterator \a value is valid and points to a CBOR
1281 * single-precision floating point (16-bit).
1282 *
1283 * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_float()
1284 */
1285
1286 /**
1287 * Retrieves the CBOR half-precision floating point (16-bit) value that \a
1288 * value points to and stores it in \a result. If the iterator \a value does
1289 * not point to a half-precision floating point value, the behavior is
1290 * undefined, so checking with \ref cbor_value_get_type or with \ref
1291 * cbor_value_is_half_float is recommended.
1292 *
1293 * Note: since the C language does not have a standard type for half-precision
1294 * floating point, this function takes a \c{void *} as a parameter for the
1295 * storage area, which must be at least 16 bits wide.
1296 *
1297 * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_half_float(), cbor_value_get_float()
1298 */
cbor_value_get_half_float(const CborValue * value,void * result)1299 CborError cbor_value_get_half_float(const CborValue *value, void *result)
1300 {
1301 assert(cbor_value_is_half_float(value));
1302
1303 /* size has been computed already */
1304 uint16_t v = value->parser->d->get16(value->parser->d, value->offset + 1);
1305 memcpy(result, &v, sizeof(v));
1306 return CborNoError;
1307 }
1308
1309
1310 /** @} */
1311