tinycbor: Update to v0.3.2
[platform/upstream/iotivity.git] / extlibs / tinycbor / tinycbor / src / cbor.h
1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 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 #ifndef CBOR_H
26 #define CBOR_H
27
28 #include <assert.h>
29 #include <limits.h>
30 #include <stddef.h>
31 #include <stdint.h>
32 #include <string.h>
33 #include <stdio.h>
34
35 #ifdef __cplusplus
36 extern "C" {
37 #else
38 #include <stdbool.h>
39 #endif
40
41 #ifndef SIZE_MAX
42 /* Some systems fail to define SIZE_MAX in <stdint.h>, even though C99 requires it...
43  * Conversion from signed to unsigned is defined in 6.3.1.3 (Signed and unsigned integers) p2,
44  * which says: "the value is converted by repeatedly adding or subtracting one more than the
45  * maximum value that can be represented in the new type until the value is in the range of the
46  * new type."
47  * So -1 gets converted to size_t by adding SIZE_MAX + 1, which results in SIZE_MAX.
48  */
49 #  define SIZE_MAX ((size_t)-1)
50 #endif
51
52 #ifndef CBOR_API
53 #  define CBOR_API
54 #endif
55 #ifndef CBOR_PRIVATE_API
56 #  define CBOR_PRIVATE_API
57 #endif
58 #ifndef CBOR_INLINE_API
59 #  if defined(__cplusplus)
60 #    define CBOR_INLINE inline
61 #    define CBOR_INLINE_API inline
62 #  else
63 #    define CBOR_INLINE_API static CBOR_INLINE
64 #    if defined(_MSC_VER)
65 #      define CBOR_INLINE __inline
66 #    elif defined(__GNUC__)
67 #      define CBOR_INLINE __inline__
68 #    elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
69 #      define CBOR_INLINE inline
70 #    else
71 #      define CBOR_INLINE
72 #    endif
73 #  endif
74 #endif
75
76 typedef enum CborType {
77     CborIntegerType     = 0x00,
78     CborByteStringType  = 0x40,
79     CborTextStringType  = 0x60,
80     CborArrayType       = 0x80,
81     CborMapType         = 0xa0,
82     CborTagType         = 0xc0,
83     CborSimpleType      = 0xe0,
84     CborBooleanType     = 0xf5,
85     CborNullType        = 0xf6,
86     CborUndefinedType   = 0xf7,
87     CborHalfFloatType   = 0xf9,
88     CborFloatType       = 0xfa,
89     CborDoubleType      = 0xfb,
90
91     CborInvalidType     = 0xff              /* equivalent to the break byte, so it will never be used */
92 } CborType;
93
94 typedef uint64_t CborTag;
95 typedef enum CborKnownTags {
96     CborDateTimeStringTag          = 0,        /* RFC 3339 format: YYYY-MM-DD hh:mm:ss+zzzz */
97     CborUnixTime_tTag              = 1,
98     CborPositiveBignumTag          = 2,
99     CborNegativeBignumTag          = 3,
100     CborDecimalTag                 = 4,
101     CborBigfloatTag                = 5,
102     CborExpectedBase64urlTag       = 21,
103     CborExpectedBase64Tag          = 22,
104     CborExpectedBase16Tag          = 23,
105     CborUriTag                     = 32,
106     CborBase64urlTag               = 33,
107     CborBase64Tag                  = 34,
108     CborRegularExpressionTag       = 35,
109     CborMimeMessageTag             = 36,       /* RFC 2045-2047 */
110     CborSignatureTag               = 55799
111 } CborKnownTags;
112
113 /* Error API */
114
115 typedef enum CborError {
116     CborNoError = 0,
117
118     /* errors in all modes */
119     CborUnknownError,
120     CborErrorUnknownLength,         /* request for length in array, map, or string with indeterminate length */
121     CborErrorAdvancePastEOF,
122     CborErrorIO,
123
124     /* parser errors streaming errors */
125     CborErrorGarbageAtEnd = 256,
126     CborErrorUnexpectedEOF,
127     CborErrorUnexpectedBreak,
128     CborErrorUnknownType,           /* can only heppen in major type 7 */
129     CborErrorIllegalType,           /* type not allowed here */
130     CborErrorIllegalNumber,
131     CborErrorIllegalSimpleType,     /* types of value less than 32 encoded in two bytes */
132
133     /* parser errors in strict mode parsing only */
134     CborErrorUnknownSimpleType = 512,
135     CborErrorUnknownTag,
136     CborErrorInappropriateTagForType,
137     CborErrorDuplicateObjectKeys,
138     CborErrorInvalidUtf8TextString,
139
140     /* encoder errors */
141     CborErrorTooManyItems = 768,
142     CborErrorTooFewItems,
143
144     /* internal implementation errors */
145     CborErrorDataTooLarge = 1024,
146     CborErrorNestingTooDeep,
147     CborErrorUnsupportedType,
148
149     /* errors in converting to JSON */
150     CborErrorJsonObjectKeyIsAggregate,
151     CborErrorJsonObjectKeyNotString,
152
153     CborErrorOutOfMemory = ~0U / 2 + 1,
154     CborErrorInternalError = ~0U
155 } CborError;
156
157 CBOR_API const char *cbor_error_string(CborError error);
158
159 /* Encoder API */
160 struct CborEncoder
161 {
162     union {
163         uint8_t *ptr;
164         ptrdiff_t bytes_needed;
165     };
166     const uint8_t *end;
167     size_t added;
168     int flags;
169 };
170 typedef struct CborEncoder CborEncoder;
171
172 static const size_t CborIndefiniteLength = SIZE_MAX;
173
174 CBOR_API void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags);
175 CBOR_API CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value);
176 CBOR_API CborError cbor_encode_int(CborEncoder *encoder, int64_t value);
177 CBOR_API CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value);
178 CBOR_API CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value);
179 CBOR_API CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag);
180 CBOR_API CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length);
181 CBOR_INLINE_API CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
182 { return cbor_encode_text_string(encoder, string, strlen(string)); }
183 CBOR_API CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length);
184 CBOR_API CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value);
185
186 CBOR_INLINE_API CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
187 { return cbor_encode_simple_value(encoder, (int)value - 1 + (CborBooleanType & 0x1f)); }
188 CBOR_INLINE_API CborError cbor_encode_null(CborEncoder *encoder)
189 { return cbor_encode_simple_value(encoder, CborNullType & 0x1f); }
190 CBOR_INLINE_API CborError cbor_encode_undefined(CborEncoder *encoder)
191 { return cbor_encode_simple_value(encoder, CborUndefinedType & 0x1f); }
192
193 CBOR_INLINE_API CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
194 { return cbor_encode_floating_point(encoder, CborHalfFloatType, value); }
195 CBOR_INLINE_API CborError cbor_encode_float(CborEncoder *encoder, float value)
196 { return cbor_encode_floating_point(encoder, CborFloatType, &value); }
197 CBOR_INLINE_API CborError cbor_encode_double(CborEncoder *encoder, double value)
198 { return cbor_encode_floating_point(encoder, CborDoubleType, &value); }
199
200 CBOR_API CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length);
201 CBOR_API CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length);
202 CBOR_API CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder);
203 CBOR_API CborError cbor_encoder_close_container_checked(CborEncoder *encoder, const CborEncoder *containerEncoder);
204
205 CBOR_INLINE_API size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
206 {
207     return (size_t)(encoder->ptr - buffer);
208 }
209
210 CBOR_INLINE_API size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
211 {
212     return encoder->end ? 0 : (size_t)encoder->bytes_needed;
213 }
214
215 /* Parser API */
216
217 enum CborParserIteratorFlags
218 {
219     CborIteratorFlag_IntegerValueTooLarge   = 0x01,
220     CborIteratorFlag_NegativeInteger        = 0x02,
221     CborIteratorFlag_UnknownLength          = 0x04,
222     CborIteratorFlag_ContainerIsMap         = 0x20
223 };
224
225 struct CborParser
226 {
227     const uint8_t *end;
228     int flags;
229 };
230 typedef struct CborParser CborParser;
231
232 struct CborValue
233 {
234     const CborParser *parser;
235     const uint8_t *ptr;
236     uint32_t remaining;
237     uint16_t extra;
238     uint8_t type;
239     uint8_t flags;
240 };
241 typedef struct CborValue CborValue;
242
243 CBOR_API CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it);
244
245 CBOR_INLINE_API bool cbor_value_at_end(const CborValue *it)
246 { return it->remaining == 0; }
247 CBOR_INLINE_API const uint8_t *cbor_value_get_next_byte(const CborValue *it)
248 { return it->ptr; }
249 CBOR_API CborError cbor_value_advance_fixed(CborValue *it);
250 CBOR_API CborError cbor_value_advance(CborValue *it);
251 CBOR_INLINE_API bool cbor_value_is_container(const CborValue *it)
252 { return it->type == CborArrayType || it->type == CborMapType; }
253 CBOR_API CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed);
254 CBOR_API CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed);
255
256 CBOR_PRIVATE_API uint64_t _cbor_value_decode_int64_internal(const CborValue *value);
257 CBOR_INLINE_API uint64_t _cbor_value_extract_int64_helper(const CborValue *value)
258 {
259     return value->flags & CborIteratorFlag_IntegerValueTooLarge ?
260                 _cbor_value_decode_int64_internal(value) : value->extra;
261 }
262
263 CBOR_INLINE_API bool cbor_value_is_valid(const CborValue *value)
264 { return value && value->type != CborInvalidType; }
265 CBOR_INLINE_API CborType cbor_value_get_type(const CborValue *value)
266 { return (CborType)value->type; }
267
268 /* Null & undefined type */
269 CBOR_INLINE_API bool cbor_value_is_null(const CborValue *value)
270 { return value->type == CborNullType; }
271 CBOR_INLINE_API bool cbor_value_is_undefined(const CborValue *value)
272 { return value->type == CborUndefinedType; }
273
274 /* Booleans */
275 CBOR_INLINE_API bool cbor_value_is_boolean(const CborValue *value)
276 { return value->type == CborBooleanType; }
277 CBOR_INLINE_API CborError cbor_value_get_boolean(const CborValue *value, bool *result)
278 {
279     assert(cbor_value_is_boolean(value));
280     *result = !!value->extra;
281     return CborNoError;
282 }
283
284 /* Simple types */
285 CBOR_INLINE_API bool cbor_value_is_simple_type(const CborValue *value)
286 { return value->type == CborSimpleType; }
287 CBOR_INLINE_API CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
288 {
289     assert(cbor_value_is_simple_type(value));
290     *result = (uint8_t)value->extra;
291     return CborNoError;
292 }
293
294 /* Integers */
295 CBOR_INLINE_API bool cbor_value_is_integer(const CborValue *value)
296 { return value->type == CborIntegerType; }
297 CBOR_INLINE_API bool cbor_value_is_unsigned_integer(const CborValue *value)
298 { return cbor_value_is_integer(value) && (value->flags & CborIteratorFlag_NegativeInteger) == 0; }
299 CBOR_INLINE_API bool cbor_value_is_negative_integer(const CborValue *value)
300 { return cbor_value_is_integer(value) && (value->flags & CborIteratorFlag_NegativeInteger); }
301
302 CBOR_INLINE_API CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
303 {
304     assert(cbor_value_is_integer(value));
305     *result = _cbor_value_extract_int64_helper(value);
306     return CborNoError;
307 }
308
309 CBOR_INLINE_API CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
310 {
311     assert(cbor_value_is_unsigned_integer(value));
312     *result = _cbor_value_extract_int64_helper(value);
313     return CborNoError;
314 }
315
316 CBOR_INLINE_API CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
317 {
318     assert(cbor_value_is_integer(value));
319     *result = (int64_t) _cbor_value_extract_int64_helper(value);
320     if (value->flags & CborIteratorFlag_NegativeInteger)
321         *result = -*result - 1;
322     return CborNoError;
323 }
324
325 CBOR_INLINE_API CborError cbor_value_get_int(const CborValue *value, int *result)
326 {
327     assert(cbor_value_is_integer(value));
328     *result = (int) _cbor_value_extract_int64_helper(value);
329     if (value->flags & CborIteratorFlag_NegativeInteger)
330         *result = -*result - 1;
331     return CborNoError;
332 }
333
334 CBOR_API CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result);
335 CBOR_API CborError cbor_value_get_int_checked(const CborValue *value, int *result);
336
337 CBOR_INLINE_API bool cbor_value_is_length_known(const CborValue *value)
338 { return (value->flags & CborIteratorFlag_UnknownLength) == 0; }
339
340 /* Tags */
341 CBOR_INLINE_API bool cbor_value_is_tag(const CborValue *value)
342 { return value->type == CborTagType; }
343 CBOR_INLINE_API CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
344 {
345     assert(cbor_value_is_tag(value));
346     *result = _cbor_value_extract_int64_helper(value);
347     return CborNoError;
348 }
349 CBOR_API CborError cbor_value_skip_tag(CborValue *it);
350
351 /* Strings */
352 CBOR_INLINE_API bool cbor_value_is_byte_string(const CborValue *value)
353 { return value->type == CborByteStringType; }
354 CBOR_INLINE_API bool cbor_value_is_text_string(const CborValue *value)
355 { return value->type == CborTextStringType; }
356
357 CBOR_INLINE_API CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
358 {
359     assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
360     if (!cbor_value_is_length_known(value))
361         return CborErrorUnknownLength;
362     uint64_t v = _cbor_value_extract_int64_helper(value);
363     *length = v;
364     if (*length != v)
365         return CborErrorDataTooLarge;
366     return CborNoError;
367 }
368
369 CBOR_PRIVATE_API CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
370                                                    size_t *buflen, CborValue *next);
371 CBOR_PRIVATE_API CborError _cbor_value_dup_string(const CborValue *value, void **buffer,
372                                                   size_t *buflen, CborValue *next);
373
374 CBOR_API CborError cbor_value_calculate_string_length(const CborValue *value, size_t *length);
375
376 CBOR_INLINE_API CborError cbor_value_copy_text_string(const CborValue *value, char *buffer,
377                                                       size_t *buflen, CborValue *next)
378 {
379     assert(cbor_value_is_text_string(value));
380     return _cbor_value_copy_string(value, buffer, buflen, next);
381 }
382 CBOR_INLINE_API CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer,
383                                                       size_t *buflen, CborValue *next)
384 {
385     assert(cbor_value_is_byte_string(value));
386     return _cbor_value_copy_string(value, buffer, buflen, next);
387 }
388
389 CBOR_INLINE_API CborError cbor_value_dup_text_string(const CborValue *value, char **buffer,
390                                                      size_t *buflen, CborValue *next)
391 {
392     assert(cbor_value_is_text_string(value));
393     return _cbor_value_dup_string(value, (void **)buffer, buflen, next);
394 }
395 CBOR_INLINE_API CborError cbor_value_dup_byte_string(const CborValue *value, uint8_t **buffer,
396                                                      size_t *buflen, CborValue *next)
397 {
398     assert(cbor_value_is_byte_string(value));
399     return _cbor_value_dup_string(value, (void **)buffer, buflen, next);
400 }
401
402 /* ### TBD: partial reading API */
403
404 CBOR_API CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result);
405
406 /* Maps and arrays */
407 CBOR_INLINE_API bool cbor_value_is_array(const CborValue *value)
408 { return value->type == CborArrayType; }
409 CBOR_INLINE_API bool cbor_value_is_map(const CborValue *value)
410 { return value->type == CborMapType; }
411
412 CBOR_INLINE_API CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
413 {
414     assert(cbor_value_is_array(value));
415     if (!cbor_value_is_length_known(value))
416         return CborErrorUnknownLength;
417     uint64_t v = _cbor_value_extract_int64_helper(value);
418     *length = v;
419     if (*length != v)
420         return CborErrorDataTooLarge;
421     return CborNoError;
422 }
423
424 CBOR_INLINE_API CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
425 {
426     assert(cbor_value_is_map(value));
427     if (!cbor_value_is_length_known(value))
428         return CborErrorUnknownLength;
429     uint64_t v = _cbor_value_extract_int64_helper(value);
430     *length = v;
431     if (*length != v)
432         return CborErrorDataTooLarge;
433     return CborNoError;
434 }
435
436 CBOR_API CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element);
437
438 /* Floating point */
439 CBOR_INLINE_API bool cbor_value_is_half_float(const CborValue *value)
440 { return value->type == CborHalfFloatType; }
441 CBOR_API CborError cbor_value_get_half_float(const CborValue *value, void *result);
442
443 CBOR_INLINE_API bool cbor_value_is_float(const CborValue *value)
444 { return value->type == CborFloatType; }
445 CBOR_INLINE_API CborError cbor_value_get_float(const CborValue *value, float *result)
446 {
447     assert(cbor_value_is_float(value));
448     assert(value->flags & CborIteratorFlag_IntegerValueTooLarge);
449     uint32_t data = (uint32_t)_cbor_value_decode_int64_internal(value);
450     memcpy(result, &data, sizeof(*result));
451     return CborNoError;
452 }
453
454 CBOR_INLINE_API bool cbor_value_is_double(const CborValue *value)
455 { return value->type == CborDoubleType; }
456 CBOR_INLINE_API CborError cbor_value_get_double(const CborValue *value, double *result)
457 {
458     assert(cbor_value_is_double(value));
459     assert(value->flags & CborIteratorFlag_IntegerValueTooLarge);
460     uint64_t data = _cbor_value_decode_int64_internal(value);
461     memcpy(result, &data, sizeof(*result));
462     return CborNoError;
463 }
464
465 /* Human-readable (dump) API */
466 CBOR_API CborError cbor_value_to_pretty_advance(FILE *out, CborValue *value);
467 CBOR_INLINE_API CborError cbor_value_to_pretty(FILE *out, const CborValue *value)
468 {
469     CborValue copy = *value;
470     return cbor_value_to_pretty_advance(out, &copy);
471 }
472
473 #ifdef __cplusplus
474 }
475 #endif
476
477 #endif /* CBOR_H */
478